According to your description, I assume that you mean first-order width, which can be easily done using the WITH RECURSIVE query (PostgreSQL 8.4+):
WITH RECURSIVE tree AS ( SELECT node_name, id, parent_id, NULL::varchar AS parent_name FROM foo WHERE parent_id IS NULL UNION SELECT node_name, f1.id, f1.parent_id, tree.node_name AS parent_name FROM tree JOIN foo f1 ON f1.parent_id = tree.id ) SELECT node_name, empno, parent_id, node_name FROM tree;
You can also use the depth order using the following SQL:
WITH RECURSIVE tree AS ( SELECT node_name, id, parent_id, NULL::varchar AS parent_name, id::text AS path FROM foo WHERE parent_id IS NULL UNION SELECT node_name, f1.id, f1.parent_id, tree.node_name AS parent_name, tree.path || '-' || f1.id::text AS path FROM tree JOIN foo f1 ON f1.parent_id = tree.id ) SELECT node_name, empno, parent_id, node_name, path FROM tree ORDER BY path;
Diogo biazus
source share