By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
drop table if exists prlines;
create table if not exists prlines (id int, prev_id int);
insert into prlines values (1, NULL), (2, NULL), (3, 1), (4, 2), (5, 3), (6, 5), (7, 6);
Records: 7 Duplicates: 0 Warnings: 0
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;
prev_id |
---|
3 |
1 |
6 |
7 |