How-To Guide

How to Write Recursive CTEs for Hierarchies

Query trees and graphs in SQL with recursive common table expressions, including cycle protection and depth-limited traversal.

On this page

  1. Introduction
  2. Modeling Hierarchies
  3. The Recursive CTE Structure
  4. Preventing Infinite Recursion
  5. Traversing Upward and Building Paths
  6. Performance Considerations
  7. Using Recursive CTEs Well
  8. Conclusion

Introduction

Hierarchical data is everywhere: an org chart, a bill of materials, a comment thread, a category tree. A relational table stores it as rows that point at their parent, which is compact but awkward to query: a single SELECT returns one level. Recursive common table expressions let SQL walk the hierarchy in one query, producing the descendant set, the ancestor chain, or a depth-annotated tree. This article covers the recursive CTE structure, downward and upward traversal, cycle protection, and the performance characteristics that decide whether a recursive query is fast enough.

Modeling Hierarchies

The adjacency-list model stores a parent_id on each row. It is simple to write and to update: moving a subtree is one row update. Its weakness is reads, because finding all descendants of a node requires following the chain level by level. Other models exist, such as nested sets or materialized paths, which trade write complexity for cheaper reads. When the read pattern is recursive and the tree is not enormous, an adjacency list plus a recursive CTE is usually the best combination.

Choose based on which operation dominates. If you constantly read whole subtrees and rarely move nodes, a materialized path or a closure table may be faster. If you mostly update and occasionally query, the adjacency list with a recursive query is simpler and correct.

The Recursive CTE Structure

A recursive CTE has two parts joined by UNION ALL: an anchor term that selects the starting rows, and a recursive term that references the CTE and selects the next level. The database evaluates the anchor, then repeatedly evaluates the recursive term over the rows produced by the previous iteration until an iteration produces no new rows. The result is the union of all iterations.

WITH RECURSIVE subtree AS (
  -- Anchor: the starting employee
  SELECT id, manager_id, name, 1 AS depth
  FROM employees
  WHERE id = 42

  UNION ALL

  -- Recursive: everyone whose manager is in the previous level
  SELECT e.id, e.manager_id, e.name, s.depth + 1
  FROM employees e
  JOIN subtree s ON e.manager_id = s.id
)
SELECT id, name, depth
FROM subtree
ORDER BY depth, name;

Preventing Infinite Recursion

If the data contains a cycle, such as a row that is its own ancestor through a chain, the recursive query never terminates: each iteration produces a row that produces another. Never run a recursive query on unvalidated data without a guard. The simplest guard is a depth limit in the recursive term; a stronger one is to track the visited path and stop when a value repeats.

-- Depth-limited traversal (safe against cycles)
WITH RECURSIVE subtree AS (
  SELECT id, manager_id, 1 AS depth, ARRAY[id] AS path
  FROM employees WHERE id = 42
  UNION ALL
  SELECT e.id, e.manager_id, s.depth + 1, s.path || e.id
  FROM employees e
  JOIN subtree s ON e.manager_id = s.id
  WHERE s.depth < 20                 -- hard cap
    AND NOT e.id = ANY(s.path)       -- do not revisit a node
)
SELECT id, depth FROM subtree;

-- PostgreSQL: the cycle clause stops on a repeated key automatically
WITH RECURSIVE subtree AS (
  SELECT id, manager_id FROM employees WHERE id = 42
  UNION ALL
  SELECT e.id, e.manager_id FROM employees e
  JOIN subtree s ON e.manager_id = s.id
) CYCLE id SET is_cycle USING path
SELECT * FROM subtree WHERE NOT is_cycle;

Traversing Upward and Building Paths

The same structure walks upward by joining the CTE’s parent_id to the table’s id instead of the other way around, producing the ancestor chain of a node. That is what you need to answer “what is the path from this row to the root” or to render a breadcrumb. Accumulate the path as you go so the final row holds the full chain.

For a bill of materials you may also want to aggregate quantities up the tree: each parent’s total is the sum of its children’s totals, computed bottom-up. A recursive query can carry an accumulated quantity down from the root, or you can traverse top-down to collect nodes and aggregate in a separate step. Which is easier depends on whether the multiplication factor applies on the way down.

Performance Considerations

A recursive CTE is iterative: the recursive term runs once per level, and the work is proportional to the number of rows visited. For a shallow tree that is trivial; for a deep or wide one it can be expensive. The index on parent_id matters most, because each iteration joins on it. Without that index the join scans, and the cost grows quickly with the number of nodes.

Materialize the result when the tree is stable and read often: compute the closure table or the materialized path once and query it with a simple indexed join. This turns an O(nodes) recursive query into an O(1) lookup for the common “is X a descendant of Y” question. Keep the materialization in sync with triggers or a scheduled rebuild, and accept the write amplification as the price of fast reads.

Using Recursive CTEs Well

Use a recursive CTE when you need a specific traversal and the tree is not so large that recomputing it is too costly. Always guard against cycles and cap the depth. Index the join column. Return only the columns you need, because carrying wide rows through many iterations multiplies memory and I/O.

Do not use a recursive CTE as a substitute for a better data model when the query is on a hot path. If subtree lookups happen on every request, the right answer may be a materialized closure table updated on write, not a recursive query on each read. Measure the query with EXPLAIN and decide from the plan, not from intuition.

Conclusion

Recursive CTEs let SQL express the traversal that a parent_id column implies. Structure them as an anchor plus a recursive term, guard against cycles with a depth cap or visited path, walk upward by reversing the join, and index the join column so each iteration is cheap. For hot-path reads on stable trees, materialize the traversal into a closure table or path column and query it with a plain index. The recursive query is the tool for the occasional traversal; the materialized form is the tool for the frequent one.

Sources: PostgreSQL: WITH queries (recursive), SQL recursive CTE, MySQL: recursive CTEs.

FAQ

What happens if a recursive CTE encounters a cycle?
Without a guard it loops forever, producing rows each iteration. Cap the depth in the recursive term, track the visited path and stop on a repeat, or use the database CYCLE clause. Always guard recursive queries on data you do not fully trust.
When should I use a closure table instead of a recursive CTE?
When subtree or ancestor lookups are on a hot path and the tree is stable. A closure table or materialized path turns the traversal into an indexed lookup, at the cost of maintaining it on write. Use the recursive query for occasional traversals on an adjacency list.

Related Examples