sql / expert
Snippet
Recursive Common Table Expressions (CTEs)
Recursive CTEs are used to traverse hierarchical data structures like organizational charts or bill of materials. They consist of an anchor member and a recursive member joined by UNION ALL.
snippet.sql
1
2
3
4
5
6
7
8
9
10
WITH RECURSIVE subordinates AS (SELECT employee_id, manager_id, nameFROM employeesWHERE manager_id IS NULLUNION ALLSELECT e.employee_id, e.manager_id, e.nameFROM employees eINNER JOIN subordinates s ON s.employee_id = e.manager_id)SELECT * FROM subordinates;
Breakdown
1
WITH RECURSIVE subordinates AS
Defines the CTE name and marks it as recursive.
2
WHERE manager_id IS NULL
The anchor member: selects the starting point (e.g., the CEO).
3
INNER JOIN subordinates s ON s.employee_id = e.manager_id
The recursive member: joins the table back to the CTE to find the next level of the hierarchy.