Subqueries and CTEs
Recursive CTEs
Follow employee-to-manager links through several levels.
Lesson 43 of 84
Reading: about 2 min
Lesson + practice: about 15 min
Difficulty: Intermediate
On this page4 sections
This lesson uses DDI_SQL_Training dataset v1.0.0 on SQL Server 2019 or later. Follow employee-to-manager links through several levels.
Run the example
sql
WITH Hierarchy AS (
SELECT EmployeeID, ManagerID, FirstName, 0 AS Depth
FROM dbo.Employees WHERE ManagerID IS NULL
UNION ALL
SELECT e.EmployeeID, e.ManagerID, e.FirstName, h.Depth + 1
FROM dbo.Employees AS e
JOIN Hierarchy AS h ON e.ManagerID = h.EmployeeID
)
SELECT EmployeeID, ManagerID, FirstName, Depth
FROM Hierarchy
ORDER BY Depth, EmployeeID
OPTION (MAXRECURSION 100);Read it step by step
- The anchor starts with employees who have no manager.
- The recursive branch finds direct reports of rows already in Hierarchy.
- UNION ALL continues by level; MAXRECURSION bounds accidental cycles or runaway recursion.
Check the result
| EmployeeID | ManagerID | FirstName | Depth |
|---|---|---|---|
| 1 | NULL | Amina | 0 |
| 5 | NULL | Oliver | 0 |
| 9 | NULL | Priya | 0 |
| 2 | 1 | Grace | 1 |
| 3 | 1 | Marcus | 1 |
| 4 | 1 | Sofia | 1 |
| 6 | 5 | Daniel | 1 |
| 7 | 5 | Leah | 1 |
| 8 | 5 | Noah | 1 |
| 10 | 9 | Fatima | 1 |
| 11 | 9 | James | 1 |
| 12 | 5 | Eva | 1 |
Depth 0 is a root employee; later depths are links away from a root.
Practice
Starting at EmployeeID 1, list that employee and all descendants with their depth.
Check your answer and expected result
Reveal answer
sql
WITH Reports AS (
SELECT EmployeeID, ManagerID, 0 AS Depth
FROM dbo.Employees WHERE EmployeeID = 1
UNION ALL
SELECT e.EmployeeID, e.ManagerID, r.Depth + 1
FROM dbo.Employees AS e
JOIN Reports AS r ON e.ManagerID = r.EmployeeID
)
SELECT EmployeeID, ManagerID, Depth
FROM Reports
ORDER BY Depth, EmployeeID
OPTION (MAXRECURSION 100);| EmployeeID | ManagerID | Depth |
|---|---|---|
| 1 | NULL | 0 |
| 2 | 1 | 1 |
| 3 | 1 | 1 |
| 4 | 1 | 1 |
The anchor includes employee 1, and each recursion step adds their direct reports.
Your progress
Reveal the check answer or reach the end to complete this lesson.