Jesteś na dobrej drodze. Rozważ użycie tego :
with recursive tree as (
select id,
parent_id,
array[id] as all_parents,
name as parent_name
from hierarchy
where parent_id = 0
union all
select c.id,
p.parent_id,
p.all_parents,
p.parent_name
from hierarchy c
join tree p
on c.parent_id = p.id
and c.id <> all (p.all_parents)
)
select id, parent_id, parent_name
from tree;