sql / expert
Snippet
Recursive Hierarchy Traversal
Recursive Common Table Expressions (CTEs) allow for the traversal of self-referencing relationships, such as organizational charts or bill of materials, which are otherwise impossible to query with a fixed number of joins. The anchor member defines the starting point, and the recursive member references the CTE itself to build the result set iteratively.
snippet.sql
1
2
3
4
5
6
7
8
9
10
WITH RECURSIVE subordinates AS (SELECT id, manager_id, nameFROM employeesWHERE name = 'Alice'UNION ALLSELECT e.id, e.manager_id, e.nameFROM employees eINNER JOIN subordinates s ON s.id = e.manager_id)SELECT * FROM subordinates;
Breakdown
1
WITH RECURSIVE subordinates AS (
Starts the recursive CTE definition by naming the temporary result set.
2
SELECT id, manager_id, name FROM employees WHERE name = 'Alice'
The anchor member: selects the initial row to start the recursion.
3
UNION ALL
Combines the anchor result with the results of subsequent recursive iterations.
4
SELECT e.id, e.manager_id, e.name FROM employees e
The recursive member: selects candidates for the next level of the hierarchy.
5
INNER JOIN subordinates s ON s.id = e.manager_id
The join condition that links the new rows to the already discovered subordinates.