Skip to content

Lesson 9 of 29Joining and aggregating

Recursive CTEs and Hierarchies

Walk org charts, category trees and graphs in one query with WITH RECURSIVE, generate date series, guard against cycles, and choose how to store trees.

20 min read0/4 questions

Every company has trees in its data. Employees have managers, categories have parent categories, comments have parent comments, folders contain folders. Then someone asks for "everyone in Marcus's organisation, at any depth", or "the breadcrumb for this product page". The tempting fix is a loop in application code: fetch the children, then their children, one query per level. That is slow, it races with writes, and it breaks on the day someone creates a cycle. A recursive CTE answers these questions in one query, inside the database. This lesson shows how the engine runs one, the patterns you will reuse at work, how to keep bad data from making it loop forever, and when a tree in SQL is the wrong tool.

The anatomy of a recursive CTE

You met plain CTEs in Subqueries, CTEs and Set Operations. A recursive CTE is one that refers to itself. It always has the same three parts:

WITH RECURSIVE name AS (
  anchor member            -- runs once: the starting rows
  UNION ALL
  recursive member         -- refers to name, runs again and again
)
SELECT ... FROM name;

The simplest example counts to five:

Python
from shopdb import connect, showdb = connect()show(db, """WITH RECURSIVE counter(n) AS ( SELECT 1 -- anchor: the starting row UNION ALL SELECT n + 1 FROM counter WHERE n < 5 -- recursive member)SELECT n FROM counter""")
Output
Press Run (⌘ Enter) to see what happens.

The name "recursive" is a little misleading. The engine does not call anything recursively. It runs a loop, and the clearest way to understand it is the algorithm the Postgres documentation describes:

  1. Run the anchor. Put its rows in the result and in a scratch area called the working table.
  2. Run the recursive member, where every mention of the CTE's name means "the working table", which holds only the rows from the previous round, not the whole result so far.
  3. Add the new rows to the result. They replace the working table.
  4. If the working table is empty, stop. Otherwise go back to step 2.

So recursion ends when a round produces no new rows. In the counter, the round that starts with n = 5 produces nothing, because WHERE n < 5 is false. Nothing in the language stops a query whose recursive member always produces rows. That is the cycle problem, and it gets its own section below.

Predict the outputPython

What does this print?

from shopdb import connect
db = connect()
rows = db.execute("""
WITH RECURSIVE c(n) AS (
SELECT 1
UNION ALL
SELECT n + 3 FROM c WHERE n < 10
)
SELECT n FROM c
""").fetchall()
print([r[0] for r in rows])
Need a nudge? Hints walk you through it.

Walking down an org chart

The employees table stores the tree as an adjacency list: each row points at its parent through manager_id. To get everyone under Priya, the CTO, the anchor selects Priya and the recursive member joins employees to the previous round on e.manager_id = r.id, which means "the direct reports of everyone found last round".

The working table, round by round
roundnamedepth
0Priya0

Anchor. WHERE id = 1 finds Priya. She is the whole working table.

1/4

Real queries carry extra columns along the way. A depth counter tells you how far down each person is. A chain string records the path from the top, which is useful both for display and for sorting the result into tree order:

Python
from shopdb import connect, showdb = connect()show(db, """WITH RECURSIVE reports AS ( SELECT id, name, title, manager_id, 0 AS depth, name AS chain FROM employees WHERE id = 1 UNION ALL SELECT e.id, e.name, e.title, e.manager_id, r.depth + 1, r.chain || ' > ' || e.name FROM employees e JOIN reports r ON e.manager_id = r.id)SELECT depth, substr(' ', 1, depth * 4) || name AS org_chart, titleFROM reportsORDER BY chain""")
Output
Press Run (⌘ Enter) to see what happens.

Sorting by the path string puts every person directly under their manager. That works here because names do not contain >. In production you would build the path from ids, or from a zero-padded sort key, so that renaming someone does not reorder the chart.

Going up the tree is the same pattern with the join flipped: start from one person and join to the row whose id is the current row's manager_id. This is "who is in Mei's chain of command?", the check behind "can this manager approve this expense?":

Python
from shopdb import connect, showdb = connect()# Walk UP from one employee to the top of the treeshow(db, """WITH RECURSIVE up AS ( SELECT id, name, manager_id, 0 AS steps FROM employees WHERE id = 5 UNION ALL SELECT m.id, m.name, m.manager_id, up.steps + 1 FROM employees m JOIN up ON m.id = up.manager_id)SELECT steps, name FROM up ORDER BY steps""")
Output
Press Run (⌘ Enter) to see what happens.

Walking up visits one row per level, so it is cheap even in a huge table, as long as id is indexed (it is the primary key). Walking down needs an index on the parent column, manager_id here, or every round scans the whole table. Postgres does not index foreign key columns automatically, so check that this index exists.

Category breadcrumbs and subtrees

Categories are the same shape. Start from the roots (parent_id IS NULL) and build a path string as you go down, and every category gets its breadcrumb:

Python
from shopdb import connect, showdb = connect()show(db, """WITH RECURSIVE crumbs AS ( SELECT id, name, parent_id, name AS path FROM categories WHERE parent_id IS NULL UNION ALL SELECT c.id, c.name, c.parent_id, crumbs.path || ' > ' || c.name FROM categories c JOIN crumbs ON c.parent_id = crumbs.id)SELECT id, path FROM crumbs ORDER BY path""")print()# Every product anywhere under Computers (id 2), including subcategoriesshow(db, """WITH RECURSIVE subtree AS ( SELECT id FROM categories WHERE id = 2 UNION ALL SELECT c.id FROM categories c JOIN subtree s ON c.parent_id = s.id)SELECT p.name, p.price_centsFROM products pWHERE p.category_id IN (SELECT id FROM subtree)ORDER BY p.price_cents DESC""")
Output
Press Run (⌘ Enter) to see what happens.

The second query is the one product pages need: "show everything in Computers" must include Laptops and Accessories, however deep the tree goes. The recursive CTE collects the ids of the subtree, and an ordinary IN does the rest. For one product page, walking up from its category to the root is cheaper still, and gives you the breadcrumb directly.

Generating rows: calendars and gap filling

A recursive CTE does not need a table at all. The counter generated numbers; the same trick generates dates. Here is the reporting bug it fixes: a "checkouts per day" chart built with GROUP BY simply has no row for a day with zero checkouts, so the chart skips the day and the line looks fine when it should drop to zero. The fix is to generate every day, then LEFT JOIN the real counts to it:

Python
from shopdb import connect, showdb = connect()show(db, """WITH RECURSIVE days(day) AS ( SELECT date('2025-06-01') UNION ALL SELECT date(day, '+1 day') FROM days WHERE day < '2025-06-07'),checkouts AS ( SELECT date(created_at) AS day, COUNT(*) AS n FROM events WHERE kind = 'checkout' GROUP BY date(created_at))SELECT d.day, COALESCE(c.n, 0) AS checkoutsFROM days dLEFT JOIN checkouts c ON c.day = d.dayORDER BY d.day""")
Output
Press Run (⌘ Enter) to see what happens.

In Postgres you would not write the recursion, because generate_series is built in and works with timestamps and intervals:

SELECT d::date AS day, COUNT(e.id) AS checkouts
FROM generate_series(date '2025-06-01', date '2025-06-07', interval '1 day') AS d
LEFT JOIN events e
  ON e.kind = 'checkout'
 AND e.created_at >= d
 AND e.created_at <  d + interval '1 day'
GROUP BY d
ORDER BY d;

Two details carry over from earlier lessons. The kind = 'checkout' condition sits in ON, not WHERE, or the LEFT JOIN turns back into an inner join and the empty days vanish again (Joins of Every Kind). And COUNT(e.id) counts only matched rows, so empty days show 0, where COUNT(*) would show 1. SQLite does have a generate_series table function, but as a loadable extension that Python's sqlite3 does not include, so in SQLite you use the recursive CTE.

Cycles: when the tree is not a tree

manager_id only promises that the manager exists. Nothing stops a bad data fix from making Priya report to Ana, who reports up to Priya. Now the "tree" has a loop, and a recursive walk goes round it forever. In Postgres that query runs until statement_timeout kills it or the disk fills with temporary files.

The standard protection is to carry the path and refuse to visit a node already on it. A depth limit is a second safety net for data you do not trust:

Python
from shopdb import connect, showdb = connect()# A bad data fix: Priya now "reports to" Ana, who reports up to Priya.db.execute("UPDATE employees SET manager_id = 7 WHERE id = 1") show(db, """WITH RECURSIVE reports AS ( SELECT id, name, 0 AS depth, ',' || id || ',' AS visited FROM employees WHERE id = 3 UNION ALL SELECT e.id, e.name, r.depth + 1, r.visited || e.id || ',' FROM employees e JOIN reports r ON e.manager_id = r.id WHERE instr(r.visited, ',' || e.id || ',') = 0 -- not seen on this path AND r.depth < 20 -- safety net)SELECT depth, name, visited FROM reports ORDER BY depth, id""")
Output
Press Run (⌘ Enter) to see what happens.

Starting from Sofia, the walk goes down to Ana, then "down" to Priya (who now reports to Ana), Marcus and his team. When it reaches Sofia again, she is already in visited, so the loop ends. The commas around each id stop id 1 from matching inside 12. Notice that the output itself is the bug report: Priya appearing under Sofia is impossible in a real org chart.

Postgres 14 added a standard clause that does this bookkeeping for you, plus one that controls traversal order:

WITH RECURSIVE reports AS (
  SELECT id, name, manager_id FROM employees WHERE id = 3
  UNION ALL
  SELECT e.id, e.name, e.manager_id
  FROM employees e JOIN reports r ON e.manager_id = r.id
)
SEARCH DEPTH FIRST BY id SET tree_order
CYCLE id SET is_cycle USING path
SELECT * FROM reports
WHERE NOT is_cycle
ORDER BY tree_order;

CYCLE id tracks the ids seen on each path in the path column and marks the row that closes a loop with is_cycle = true, without recursing further from it. SEARCH DEPTH FIRST (or BREADTH FIRST) fills tree_order so that ordering by it gives a depth-first or breadth-first listing.

The real fix belongs in the data. Prevent cycles at write time: a check in the service that changes reporting lines, or a trigger that walks up from the new manager and rejects the change if it reaches the employee.

UNION or UNION ALL inside recursion

With UNION, each round throws away rows that are exact duplicates of rows already in the result. That also stops a cycle, but only if the rows really repeat:

Python
from shopdb import connect, showdb = connect()db.execute("UPDATE employees SET manager_id = 7 WHERE id = 1")# No depth column: rows repeat exactly, so UNION stops the loopshow(db, """WITH RECURSIVE under_sofia(id) AS ( SELECT 3 UNION SELECT e.id FROM employees e JOIN under_sofia u ON e.manager_id = u.id)SELECT COUNT(*) AS people FROM under_sofia""")# Same query with UNION ALL would loop forever; LIMIT caps it hereshow(db, """WITH RECURSIVE under_sofia(id) AS ( SELECT 3 UNION ALL SELECT e.id FROM employees e JOIN under_sofia u ON e.manager_id = u.id)SELECT COUNT(*) AS rows_before_limit FROM (SELECT id FROM under_sofia LIMIT 1000)""")
Output
Press Run (⌘ Enter) to see what happens.

Add a depth or path column and every row is unique again, so UNION no longer protects you. Use UNION ALL with explicit path checks for trees and graphs, and UNION when you only need the set of reachable ids. The outer LIMIT stopping an endless recursion works in SQLite and Postgres because rows are produced lazily, but treat it as a debugging trick, not a design.

Quick check
Your recursive org-chart CTE selects id, name, depth and uses UNION instead of UNION ALL. The data has a cycle. What happens?
Need a nudge? A hint rules out a wrong answer.

Graphs, shortest chains and the limits of SQL

An org chart is a tree: one path to each node. A graph, like "who follows whom", has many paths to the same node and cycles everywhere. The same pattern can still answer "what is the shortest chain from Ada to Barbara?":

Python
from shopdb import connect, showdb = connect()db.executescript("""CREATE TABLE follows (src TEXT, dst TEXT);INSERT INTO follows VALUES ('ada', 'grace'), ('ada', 'alan'), ('grace', 'linus'), ('alan', 'linus'), ('linus', 'tim'), ('alan', 'tim'), ('tim', 'ada'), ('tim', 'barbara');""")show(db, """WITH RECURSIVE walk(node, hops, path) AS ( SELECT 'ada', 0, 'ada' UNION ALL SELECT f.dst, w.hops + 1, w.path || '>' || f.dst FROM walk w JOIN follows f ON f.src = w.node WHERE instr('>' || w.path || '>', '>' || f.dst || '>') = 0 AND w.hops < 6)SELECT hops, path FROM walkWHERE node = 'barbara'ORDER BY hopsLIMIT 1""")print(db.execute("""WITH RECURSIVE walk(node, hops, path) AS ( SELECT 'ada', 0, 'ada' UNION ALL SELECT f.dst, w.hops + 1, w.path || '>' || f.dst FROM walk w JOIN follows f ON f.src = w.node WHERE instr('>' || w.path || '>', '>' || f.dst || '>') = 0 AND w.hops < 6)SELECT COUNT(*) FROM walk""").fetchone()[0], "paths explored")
Output
Press Run (⌘ Enter) to see what happens.

It works, and the second number shows the cost. The visited check is per path, not global, so the query explores every simple path from Ada, not every node once like the breadth-first search you would write in code. Eight edges give 11 paths. In a social graph where each person follows hundreds of others, the number of paths grows exponentially with depth, and a "six degrees" query will never finish.

That is the boundary. Recursive CTEs are excellent for trees and for shallow, bounded walks of a graph. For deep or dense graph questions, the options are:

  • Load the edges into application memory and run a real BFS or Dijkstra, as in Graphs in the Algorithms & Patterns course.
  • A Postgres extension built for it, such as pgRouting for weighted shortest paths.
  • Postgres 19 adds SQL/PGQ, the standard property-graph query syntax (GRAPH_TABLE with MATCH patterns). It is new in 19, so check the release notes and your provider's version before planning around it.
  • A graph database such as Neo4j, when traversals are the core of the product. NoSQL Families and When to Use Them compares these options.

Storing trees: five designs

The adjacency list (a parent_id column) is the default, and with recursive CTEs it is usually enough. When reads of whole subtrees are very frequent, or the tree is deep, teams pick a different shape. Each one makes some operation cheap by making another expensive.

DesignHow it stores the treeRead a subtreeInsert a nodeMove a subtree
Adjacency listparent_id on each rowRecursive CTEOne rowOne update
Materialised pathpath = '1/2/3/' text on each rowLIKE '1/2/%', indexableOne row, copy the parent's pathRewrite every descendant's path
Closure tableExtra table of every (ancestor, descendant, depth) pairOne indexed joinOne row per ancestorDelete and reinsert many pairs
Nested setslft and rgt numbers from a depth-first walkRange query BETWEEN, very fastRenumber about half the tableRenumber a large part of the table
Postgres ltreeA materialised path type with operatorspath <@ 'top.electronics' with a GiST indexOne rowRewrite descendants, one update statement

Some rules of thumb:

  • Start with an adjacency list, an index on parent_id, and recursive CTEs. It is simple, every write touches one row, and integrity is just a foreign key.
  • Use a materialised path or ltree for read-heavy trees such as categories and threaded comments, where you constantly need "everything under X" and moves are rare. Many teams keep parent_id as the source of truth and the path as a derived column.
  • Use a closure table when you need fast ancestor and descendant queries in both directions, for example permission inheritance, and can afford the extra rows (roughly nodes × average depth).
  • Avoid nested sets for data that changes. They appear in older systems and some CMS plugins; inserting one node can rewrite thousands of rows.
Put it in order5 steps

Put the steps of evaluating a recursive CTE in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Match the pairs0/4 matched

Match each requirement to the tree design that fits it best.

Choose an item, then its match on the other side.
Key terms
recursive CTE
A CTE that refers to itself, written WITH RECURSIVE, used to walk trees and graphs or generate rows.
anchor member
The non-recursive part of a recursive CTE. It runs once and produces the starting rows.
recursive member
The part after UNION ALL that refers to the CTE. Each round it sees only the previous round's rows.
working table
The rows produced by the latest round. Recursion stops when it is empty.
adjacency list
Storing a tree as a parent_id column on each row. Simple to write, read with recursive CTEs.
closure table
A table with one row for every ancestor-descendant pair, trading storage and write cost for fast reads.
CYCLE clause
Postgres 14+ syntax that tracks visited rows in a recursive CTE and marks the row that closes a loop.