Skip to content

Instantly share code, notes, and snippets.

@jmasonherr
Created February 4, 2019 15:53
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 jmasonherr/d076cd494c84519b718ce0b312f3524c to your computer and use it in GitHub Desktop.
Save jmasonherr/d076cd494c84519b718ce0b312f3524c to your computer and use it in GitHub Desktop.
Bottom up recursive SQL example
-- A bottom-up recursive Postgres query on a table named 'family'
-- with three columns: id, parent_id, child_id
WITH RECURSIVE bottom_up_family (
parent_id, child_id, depth, path
) AS (
SELECT
fam_initial.parent_id,
fam_initial.child_id,
1,
ARRAY[fam_initial.child_id]
FROM family as fam_initial
WHERE child_id = 1000
UNION
SELECT
fam_recurse.parent_id,
fam_recurse.child_id,
prev_query.depth + 1,
path || fam_recurse.parent_id
FROM family fam_recurse
JOIN bottom_up_family prev_query
ON prev_query.parent_id = fam_recurse.child_id
)
SELECT * FROM bottom_up_family
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment