How can SQL be used to manage hierarchical data, such as organizational structures?
Instruction: Discuss the approaches and SQL features that can be used to model and query hierarchical data.
Updated
Official answer
An adjacency list stores each node's parent ID. It is simple to update, while a recursive query follows multiple levels. Other models include a closure table of ancestor/descendant pairs, materialized paths, or nested-set boundaries; each trades read convenience against storage and update work.
For PostgreSQL employees(employee_id integer PRIMARY KEY, manager_id integer), this retrieves manager 10 and reachable descendants:
WITH RECURSIVE tree AS (
SELECT employee_id, manager_id, 0 AS depth,
ARRAY[employee_id] AS path
FROM employees WHERE employee_id = 10
UNION ALL
SELECT e.employee_id, e.manager_id, t.depth + 1, t.path || e.employee_id
FROM tree AS t
JOIN employees AS e ON e.manager_id = t.employee_id
WHERE NOT e.employee_id = ANY(t.path)
)
SELECT employee_id, manager_id, depth
FROM tree
ORDER BY path;
The anchor includes manager 10; no such employee produces no rows. The path check stops revisiting a node on the same path, so corrupt cycles terminate. This query does not report every cycle in the whole table or prove the hierarchy is valid. A foreign key rejects missing parents but does not enforce acyclicity. Index the parent key for a measured traversal workload and consider depth, fan-out and authorization when returning subtrees.