Med Postgres kan du använda ett rekursivt vanligt tabelluttryck:
with recursive rel_tree as (
select rel_id, rel_name, rel_parent, 1 as level, array[rel_id] as path_info
from relations
where rel_parent is null
union all
select c.rel_id, rpad(' ', p.level * 2) || c.rel_name, c.rel_parent, p.level + 1, p.path_info||c.rel_id
from relations c
join rel_tree p on c.rel_parent = p.rel_id
)
select rel_id, rel_name
from rel_tree
order by path_info;
SQLFiddle baserat på ditt exempel:http://sqlfiddle.com/#!11/59319/19
(Jag ersatte mellanslagen för indrag med understreck eftersom SQLFiddle inte visar mellanslagen korrekt)