Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 13 / Topic 3 of 8

Recursive CTEs

Part 5's self join walked one level of the org chart. Trees of unknown depth — org charts, category hierarchies, bills of materials — need WITH RECURSIVE: an anchor query seeds the result, a recursive query extends it until it adds nothing new:

WITH RECURSIVE org AS (
  SELECT employee_id, name, title, 1 AS level, name::text AS path
  FROM employees
  WHERE manager_id IS NULL
  UNION ALL
  SELECT e.employee_id, e.name, e.title, org.level + 1,
         org.path || ' > ' || e.name
  FROM employees AS e
  JOIN org ON e.manager_id = org.employee_id
)
SELECT level, name, title, path
FROM org
ORDER BY path;
 level | name  |   title    |        path         
-------+-------+------------+---------------------
     1 | Nina  | CEO        | Nina
     2 | Omar  | CTO        | Nina > Omar
     3 | Arjun | Engineer   | Nina > Omar > Arjun
     3 | Lena  | Engineer   | Nina > Omar > Lena
     2 | Priya | Sales Head | Nina > Priya
     3 | Dev   | Sales Rep  | Nina > Priya > Dev
(6 rows)

Read it as generations: the anchor finds Nina (no manager); round two finds everyone reporting to the result so far; and so on until a round adds nobody. The path column accumulating as it goes is the classic debugging-and-display trick. Same shape walks shopdb's categories.parent_id tree — the exercise does exactly that.

Two practical cautions: use UNION ALL (plain UNION's de-dup is usually wasted work), and remember a cycle in the data (A manages B manages A) recurses forever — real systems add a depth guard (WHERE level < 20) or track visited ids.

🧪 Quick quiz — answer from memory, then check.

  1. The two parts of a recursive CTE, and what joins them?
  2. When does the recursion stop?
Show the answers
  1. An anchor (non-recursive) query and a recursive query referencing the CTE itself, joined by UNION [ALL].
  2. When the recursive step produces no new rows (or your guard cuts it off).

Done here? The practice set for Part 13 — 6 exercises with solutions — is on the part page.

Search the guide