Overview

A common table expression (CTE), written WITH name AS (...), names a subquery so the main query reads top to bottom. A recursive CTE repeatedly feeds its own output back in, which is how SQL walks hierarchies and graphs.

Core concepts

  • A plain CTE is mainly about readability. Whether it is inlined or materialised depends on the engine. PostgreSQL 12 and later inline a non-recursive, side-effect-free CTE that is referenced once, and you can force the behaviour with AS MATERIALIZED / AS NOT MATERIALIZED. SQL Server expands a CTE into the query like a view, so it is not a materialised result you can reuse cheaply. Oracle’s optimizer decides by cost whether to materialise it.
  • A recursive CTE has an anchor member, UNION ALL, and a recursive member that references the CTE. Evaluation repeats until the recursive member returns no rows.

Worked example

Org chart with a table employees(id, name, manager_id). Verified on PostgreSQL 17:

WITH RECURSIVE org AS (
  SELECT id, name, manager_id, 1 AS depth
  FROM employees WHERE manager_id IS NULL
  UNION ALL
  SELECT e.id, e.name, e.manager_id, o.depth + 1
  FROM employees e JOIN org o ON e.manager_id = o.id
)
SELECT * FROM org ORDER BY depth, id;

Output: CEO (depth 1), VP (2), Dev lead and Ops (3), Dev (4). SQL Server and Oracle omit the RECURSIVE keyword (WITH org AS (...)); SQL Server also requires UNION ALL.

Pitfalls and production notes

  • Cycles (A manages B manages A) loop forever. Track the path (path || id) and stop on revisit, or use the engine’s cycle clause (CYCLE in PostgreSQL 14+ and Oracle). SQL Server stops with the MAXRECURSION limit (default 100).
  • Do not assume a CTE is a performance fence; check the plan (query-planning).
  • Prefer a table or index-friendly rewrite when the same CTE is used many times in a heavy query.
  • For deep hierarchies that are read often, consider a closure table or materialised path instead.

Practice questions

  1. Generate the dates of a month with a recursive CTE.
  2. Find all descendants of one manager, with the path as text.
  3. When would AS MATERIALIZED help in PostgreSQL?

References

sql-window-functions · sql-joins · normalization