BeginnerCoder

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.

Want it another way?
Task

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.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with SQL Deep Dive

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.