Walk a hierarchy
- SQL course
- Advanced
- Lesson 9/81
- 4 min
Use a recursive CTE to walk a parent-child relationship.
Hierarchy query
With a recursive CTE you query manager-employee hierarchies. Each person reports to a parent.
WITH RECURSIVE org AS (
SELECT id, name, manager_id, 1 AS level
FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id, o.level + 1
FROM employees e JOIN org o ON e.manager_id = o.id
)
SELECT * FROM org;This query produces the organization tree.
WITH RECURSIVE defines a self-referencing temporary result set (CTE) named org; the query after it uses it like a table. All columns are selected from org.
Hierarchy query — details
The anchor picks the top manager, the recursive adds each subordinate level. level shows depth.
In the anchor WHERE manager_id IS NULL picks the person with no manager; in the recursive part employees are joined to those whose manager was found on the previous level.
Practice Hierarchy query
Write an org hierarchy query: anchor the root, recursively add subordinates.
Starter code
-- hierarchy query
WITH RECURSIVE org AS (
SELECT id, name, manager_id, 1 AS levelSample solution
WITH RECURSIVE org AS (
SELECT id, name, manager_id, 1 AS level
FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id, o.level + 1
FROM employees e JOIN org o ON e.manager_id = o.id
)
SELECT * FROM org;Expected output
id name level 1 Fatma 1 2 Ayşe 2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Walk a hierarchy: match the terms
| Term | Meaning |
|---|---|
hierarchy |
tree |
manager |
parent |
subordinate |
child |
level |
depth |
2 Add level
SELECT id, name, manager_id, 1 AS ____
SELECT id, name, manager_id, 1 AS level
Explanation: In the anchor query level starts at 1 and is increased by one on each recursion.
3 What does the anchor pick in a hierarchy query?
- The top person Correct answer
- Everyone
- The bottom person
- The leaves
Explanation: The anchor picks the top person.