By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
CREATE TABLE
INSERT 0 3
| data |
|---|
| {root_1,child_1,childchild_1} |
| {root_1,child_1,childchild_2} |
| {root_2,child_2} |
SELECT 3
| title | parent |
|---|---|
| child_2 | root_2 |
| childchild_2 | child_1 |
| root_1 | null |
| childchild_1 | child_1 |
| root_2 | null |
| child_1 | root_1 |
SELECT 6
| title | parent | row_number |
|---|---|---|
| child_2 | root_2 | 1 |
| childchild_2 | child_1 | 2 |
| root_1 | null | 3 |
| childchild_1 | child_1 | 4 |
| root_2 | null | 5 |
| child_1 | root_1 | 6 |
SELECT 6
| title | parent | row_number |
|---|---|---|
| child_2 | root_2 | 1 |
| childchild_2 | child_1 | 2 |
| root_1 | null | 3 |
| childchild_1 | child_1 | 4 |
| root_2 | null | 5 |
| child_1 | root_1 | 6 |
SELECT 6
| id | title | parent_id |
|---|---|---|
| 2 | childchild_2 | 6 |
| 4 | childchild_1 | 6 |
| 6 | child_1 | 3 |
| 1 | child_2 | 5 |
| 3 | root_1 | null |
| 5 | root_2 | null |
SELECT 6