Skip to content

Instantly share code, notes, and snippets.

@halcyon
Forked from rickhall2000/pg sample data
Created February 1, 2016 16:07
Show Gist options
  • Save halcyon/ceb85d23e09c8410a80d to your computer and use it in GitHub Desktop.
Save halcyon/ceb85d23e09c8410a80d 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