Skip to content

Instantly share code, notes, and snippets.

@alairock
Last active February 3, 2017 19:30
Show Gist options
  • Save alairock/dfa925255bb52a5fcbc05e92e3f7ceb3 to your computer and use it in GitHub Desktop.
Save alairock/dfa925255bb52a5fcbc05e92e3f7ceb3 to your computer and use it in GitHub Desktop.
Recursive tree crawling in Postgres.
WITH RECURSIVE file_depth
AS (
SELECT
id,
parent_folder_id,
1 AS depth
FROM files
WHERE files.parent_folder_id = '0'
UNION
SELECT
f.id,
f.parent_folder_id,
parent.depth + 1 AS depth
FROM file_depth AS parent, files f
WHERE f.parent_folder_id = parent.id
AND depth < 10
) SELECT * FROM file_depth;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment