clear markdown compare help best fiddles feedback dbanow.uk
clear markdown donate comments/suggestions/bugs a leap of faith? bible365 diddy dollings
By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0. 2591633 fiddles created (45699 in the last week).

CREATE TABLE descriptor_value ( id bigint NOT NULL, value varchar(250), parent_id bigint ) ; insert into descriptor_value values(1, 'foo', null), (2, 'bar', 1), (3, 'baz', 2);
3 rows affected
 hidden batch(es)


with recursive cte as ( select id child_id, id parent_id, 1 lvl, parent_id real_parent_id from descriptor_value dv union all select c.child_id, dv.id parent_id, lvl + 1, dv.parent_id from cte c inner join descriptor_value dv on dv.id = c.real_parent_id ) select child_id, parent_id, lvl from cte order by child_id, lvl
child_id parent_id lvl
1 1 1
2 2 1
2 1 2
3 3 1
3 2 2
3 1 3
 hidden batch(es)