×

sql · level 3 · unit 4 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A recursive CTE can walk a one level at a time.

In the staff table, each person's boss_id points at their boss. That makes a tree: Grace at the top, her managers below, their teams below them. One join finds one level. Recursion finds them all.

The anchor picks the top, the row whose boss_id IS NULL. The step joins staff to the rows found last round, finding everyone whose boss is among them, and adds 1 to the .

A path built with || shows each person's chain of bosses. The recursion stops by itself when nobody is left to find.

WITH RECURSIVE team(id, name, depth, path) AS (
  SELECT id, name, 0, name FROM staff WHERE boss_id IS NULL
  UNION ALL
  SELECT s.id, s.name, t.depth + 1, t.path || ' > ' || s.name
  FROM staff AS s
  JOIN team AS t ON s.boss_id = t.id
)
SELECT depth, name, path FROM team ORDER BY path;

Sorting by the path keeps every team right under its boss.