How do you design a SQL query to handle hierarchical data stored in a flat table?
Instruction: Describe the approach and write a SQL query to manage and retrieve hierarchical data (such as organizational structures) that is stored in a flat table.
Updated
Official answer
An adjacency list stores a parent ID on each row. A recursive CTE can begin at rows without a parent and follow child links. This PostgreSQL example includes a separate cyclic component:
WITH RECURSIVE employees(id, name, manager_id) AS (
VALUES (1,'Ari',NULL::integer), (2,'Bo',1), (3,'Cy',2),
(4,'Dee',5), (5,'Eli',4)
), hierarchy(id, name, manager_id, depth, path) AS (
SELECT id, name, manager_id, 0, ARRAY[id]
FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id, h.depth+1, h.path || e.id
FROM employees e JOIN hierarchy h ON e.manager_id = h.id
WHERE NOT e.id = ANY(h.path)
)
SELECT id, name, depth, path FROM hierarchy ORDER BY path;
The result contains Ari at depth 0, Bo at 1 and Cy at 2. Dee and Eli are unreachable from a NULL-parent root and are omitted. A root traversal therefore does not certify the whole table is a valid tree. Compare reached IDs with all IDs and investigate orphaned or cyclic components separately.
Use unique IDs and appropriate foreign keys; a self-referencing foreign key alone does not prohibit cycles. Path order gives a deterministic traversal here, while depth/name order would be a different presentation. Bound operational resources for large hierarchies.