Last active
March 25, 2026 08:23
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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