Skip to content

Instantly share code, notes, and snippets.

@igrishaev
Created January 6, 2026 08:48
Show Gist options
  • Select an option

  • Save igrishaev/8fc14f3a1b8879c81de92ac913d390f6 to your computer and use it in GitHub Desktop.

Select an option

Save igrishaev/8fc14f3a1b8879c81de92ac913d390f6 to your computer and use it in GitHub Desktop.
create table tree(
id text primary key,
parent_id text null
);
insert into tree values
('a', null),
('b', 'a'),
('c', 'a'),
('d', 'b'),
('e', 'b'),
('f', 'c'),
('g', 'c');
prepare get_branch as
with recursive sub as (
select tree.*, 0 as level from tree where id = $1
UNION ALL
select tree.*, sub.level + 1
from tree, sub
where tree.parent_id = sub.id
)
select * from sub order by level;
execute get_branch('b');
┌────┬───────────┬───────┐
│ id │ parent_id │ level │
├────┼───────────┼───────┤
│ b │ a │ 0 │
│ d │ b │ 1 │
│ e │ b │ 1 │
└────┴───────────┴───────┘
prepare get_path as
with recursive sub as (
select tree.*, 0 as level from tree where id = $1
union all
select tree.*, sub.level - 1
from tree, sub
where tree.id = sub.parent_id
)
select * from sub order by level;
execute get_path('b');
┌────┬───────────┬───────┐
│ id │ parent_id │ level │
├────┼───────────┼───────┤
│ a │ <null> │ -1 │
│ b │ a │ 0 │
└────┴───────────┴───────┘
@igrishaev
Copy link
Author

execute get_path('f');
┌────┬───────────┬───────┐
│ id │ parent_id │ level │
├────┼───────────┼───────┤
│ a  │ <null>    │    -2 │
│ c  │ a         │    -1 │
│ f  │ c         │     0 │
└────┴───────────┴───────┘

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment