Created
January 6, 2026 08:48
-
-
Save igrishaev/8fc14f3a1b8879c81de92ac913d390f6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 │ | |
| └────┴───────────┴───────┘ | |
Author
igrishaev
commented
Jan 6, 2026
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment