[Answered ]-Query all connected ancestors and descendants in a self referencing table

1👍

You can use a recursive cte:

with recursive cte(p, c, f) as (
   select p.*, p.prev_id = 5 from prlines p where p.id = 5 or p.prev_id = 5
   union all
   select p.*, c.f from cte c join prlines p on case when c.f then p.prev_id = c.p else p.id = c.c end
)
select case when f then p else c end prev_id from cte where c is not null order by f;

Output:

prev_id
3
1
6
7

See demo.

Leave a comment