SQL & Relational Databases (50 Qs)•Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)
Recursive CTEs: Querying Trees and Hierarchies in SQL.
senior LevelCode ExampleDatabases & SQLData Structures
In Simple Words: A Recursive CTE references itself to traverse hierarchical data (organization charts, category trees, bill of materials) in pure SQL without procedural code loops:
- Anchor Member: Initial query that selects the root nodes.
- Recursive Member: Joins the CTE with the table to select child nodes until no rows remain.
sql
-- Traversing an organization management hierarchy
WITH RECURSIVE OrgChart AS (
-- 1. Anchor: Top-level CEO (manager_id is NULL)
SELECT employee_id, name, manager_id, 1 AS level
FROM employees
WHERE manager_id IS NULL
UNION ALL
-- 2. Recursive step: Join subordinate employees with their managers
SELECT e.employee_id, e.name, e.manager_id, o.level + 1
FROM employees e
INNER JOIN OrgChart o ON e.manager_id = o.employee_id
)
SELECT * FROM OrgChart ORDER BY level, name;