Skip to content

Instantly share code, notes, and snippets.

@AlexWheeler
Created October 28, 2016 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlexWheeler/1bc8577a25d638b7faafca263e7242a4 to your computer and use it in GitHub Desktop.
Save AlexWheeler/1bc8577a25d638b7faafca263e7242a4 to your computer and use it in GitHub Desktop.
WITH RECURSIVE tree AS (
SELECT id, ARRAY[]::INTEGER[] AS ancestors
FROM test WHERE parent_id IS NULL
UNION ALL
SELECT test.id, tree.ancestors || test.parent_id
FROM test, tree
WHERE test.parent_id = tree.id
) SELECT * FROM tree
--test table
id, parent_id
1, NULL
2, 1
3, 1
Result
id, ancestors
1 {}
2 {1}
3 {1}
but I want
id, ancestors
1 {2, 3}
2 {}
3 {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment