Skip to content

Instantly share code, notes, and snippets.

@rickhall2000
Last active February 1, 2016 16:07
Show Gist options
  • Save rickhall2000/e15d9656ac176e61f1b4 to your computer and use it in GitHub Desktop.
Save rickhall2000/e15d9656ac176e61f1b4 to your computer and use it in GitHub Desktop.
-- drop table bleh;
create table bleh (id char(2) Primary Key,
parent_id char(2) );
insert into bleh VALUES ('A1', null);
insert into bleh VALUES ('A2', 'A1');
insert into bleh VALUES ('A3', 'A2');
insert into bleh VALUES ('A4', 'A3');
insert into bleh VALUES ('B1', null);
insert into bleh VALUES ('B2', 'B1');
insert into bleh VALUES ('B3', 'B1');
insert into bleh VALUES ('B4', 'B2');
WITH RECURSIVE p(id, parent_id) AS (
SELECT id, parent_id
FROM bleh
WHERE bleh.id = 'B2' -- change to get a different tree/entry point
UNION ALL
SELECT b.id, b.parent_id
FROM p p
JOIN bleh b
ON b.id = p.parent_id),
c(id, parent_id) AS (
SELECT id, parent_id
FROM p
WHERE p.parent_id IS NULL
UNION ALL
SELECT b.id, b.parent_id
FROM c c
JOIN bleh b
ON b.parent_id = c.id)
SELECT * FROM c
ORDER BY id;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment