Hierarchy traversal: descendants and ancestors
Overview
A recursive CTE follows relationships across multiple levels. In the existing employee fixture, manager_id connects an employee to an immediate manager; recursion finds indirect relationships too.
First example
WITH RECURSIVE team(id, name, depth) AS ( SELECT id, name, 0 FROM join_staff WHERE id = 1 UNION ALL SELECT s.id, s.name, t.depth + 1 FROM join_staff s JOIN team t ON s.manager_id = t.id WHERE t.depth < 10)SELECT id, name, depth FROM team ORDER BY depth, id;Observed SQLite result (rows in JSON):
[ [ 1, "Mina", 0 ], [ 2, "Reza", 1 ], [ 3, "Neda", 1 ], [ 4, "Omid", 2 ]]How it works
The first anchor selects Mina at depth zero; the recursive join finds staff reporting to the current node. Omid is two levels below Mina. The second query reverses the join direction to find Omid and his chain of managers. The outer ORDER BY depth, id creates a stable level-first display; it does not prescribe evaluation order. Both queries cap depth at 10 and use the known acyclic staff fixture. On arbitrary graphs add cycle detection; a depth cap alone may omit legitimate deeper records. PostgreSQL SEARCH can generate a sorting column, not force a physical visitation order.
Practical example
WITH RECURSIVE chain(id, name, manager_id, depth) AS ( SELECT id, name, manager_id, 0 FROM join_staff WHERE id = 4 UNION ALL SELECT s.id, s.name, s.manager_id, c.depth + 1 FROM join_staff s JOIN chain c ON s.id = c.manager_id WHERE c.depth < 10)SELECT id, name, depth FROM chain ORDER BY depth, id;Observed SQLite result (rows in JSON):
[ [ 4, "Omid", 0 ], [ 2, "Reza", 1 ], [ 1, "Mina", 2 ]]Practice and mistakes
Practice: start at Reza (ID 2); return Reza and Omid. Then start at a nonexistent ID and predict the result (no rows). For a bill of materials, carry the quantity along each path and aggregate after recursion; different paths may represent real additional units.