Dengan Postgres Anda dapat menggunakan ekspresi tabel umum rekursif:
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 berdasarkan contoh Anda:http://sqlfiddle.com/#!11/59319/19
(Saya mengganti spasi untuk indentasi dengan garis bawah karena SQLFiddle tidak menampilkan spasi dengan benar)