Skip to content

Instantly share code, notes, and snippets.

@mrk21
Last active March 25, 2026 08:23
Show Gist options
  • Select an option

  • Save mrk21/140f8abe8bfe7bb4707446593fbf4ec2 to your computer and use it in GitHub Desktop.

Select an option

Save mrk21/140f8abe8bfe7bb4707446593fbf4ec2 to your computer and use it in GitHub Desktop.
A recursive CTE technique for fast retrieval of unique values from a specific column in a PostgreSQL table. By leveraging a B-Tree index for index-only scans, it performs significantly faster and lighter than a regular SELECT DISTINCT.
WITH RECURSIVE foo_ids AS (
(SELECT foo_id FROM hoges ORDER BY foo_id LIMIT 1)
UNION ALL
SELECT (SELECT foo_id FROM hoges WHERE foo_id > f.foo_id ORDER BY foo_id LIMIT 1)
FROM foo_ids f
WHERE f.foo_id IS NOT NULL
)
SELECT foo_id FROM foo_ids WHERE foo_id IS NOT NULL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment