Lesson 22 — Recursive hierarchy (expert)
Walking a hierarchy with a recursive CTE
Lesson 15 found one level (each employee's manager). To get everyone under a manager, at any depth, use a recursive CTE: the anchor selects the starting person, and the recursive step joins staff whose manager_id is someone already found.
WITH RECURSIVE tree(id, label) AS (
SELECT id, label FROM folders WHERE id = 1
UNION ALL
SELECT f.id, f.label FROM folders f JOIN tree t ON f.parent_id = t.id
) SELECT label FROM tree
Why it matters: "all subfolders", "all replies in a thread", "everyone in my department" are recursive questions.
Fill in the recursive step's ON condition: staff whose manager_id is an id already in team. Expected: Bo, Dee, Eve, Fay.
Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.
A quick 3-question quiz on this lesson — instant feedback.
Ready for more? Optional paid resources that pick up where this lesson leaves off.
Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.
Project-based SQL Deep Dive courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for SQL Deep Dive books — check the publication year so the examples match current versions.
Search Amazon →