AI Hints
Home›PostgreSQL Tutorial›ROLLUP and CTEs
PostgreSQL · Lesson 30 of 120

Recursive CTEs

Walk a tree.

⏱ 2 min read▶ Video at 25:41🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Riverside's staff form a tree. Each person has a manager, up to the owner. To list the whole chain, a recursive CTE keeps joining until it runs out of people.

  • Staff
  • Managers
  • The whole tree

The org chart

The first part starts with the owner, who has no manager. Union all then adds people whose manager is already in the result, one level deeper each time. Run it. Everyone, with their level in the tree.

query.sqlsql
WITH RECURSIVE chart AS (
  SELECT staff_id, name, role, 1 AS level
  FROM staff WHERE manager_id IS NULL
  UNION ALL
  SELECT s.staff_id, s.name, s.role, c.level + 1
  FROM staff s JOIN chart c ON s.manager_id = c.staff_id
)
SELECT repeat('  ', level - 1) || name AS name, role, level
FROM chart ORDER BY level, name;
Output
      name      |      role      | level
----------------+----------------+-------
 Helen Ward     | Owner          |     1
   Marcus Lee   | Store Manager  |     2
   Priya Nair   | Online Manager |     2
     Amy Chen   | Web Support    |     3
     Leo Grant  | Warehouse      |     3
     Noah Price | Bookseller     |     3
     Sara Odum  | Bookseller     |     3
     Tom Baker  | Bookseller     |     3
(8 rows)

Recursive uses

Org charts and category trees. Threads of replies. Routes through a network. And generating series of numbers or dates. Always make sure the recursion stops.

keyvalue
Treesorg charts, categories
Threadsreplies
Graphsroutes
Stopmake sure it ends

Summary

Recursive CTEs start with a base row, then repeat a join until nothing new appears. Next, window functions.

Key takeaways
  • WITH RECURSIVE
  • Base case
  • UNION ALL
Next up: Window Functions — calculations across rows