Recursive CTEs

A query that feeds its own output back in, one level at a time, until nothing new comes back.

Recursive CTEs

Walking a hierarchy

query.sql SQLite
Result

Worth knowing

A recursive CTE has two halves joined by UNION ALL: an anchor that runs once, and a step that runs against what the last round produced.
It stops when the step returns no rows. Nothing else stops it.
The step reads only the previous round's rows, not the whole accumulated set. That is what makes it a level-by-level walk.
A cycle in the data means the step never comes back empty. Carry a depth column and cap it.

Overview

A recursive CTE has an anchor query that starts the result and a recursive term that finds the next rows. The recursive term refers to the CTE itself. Each iteration adds rows until no new rows are produced or a guard stops the process.

In this guide
  1. The two parts
  2. Termination and cycles
  3. When recursion fits
  4. Carry a path to avoid revisiting nodes
  5. Check the output grain
  6. Further reading

The two parts

query.sqlSQLite
Result

The anchor starts at top-level employees; each step finds direct reports and increments depth. The depth condition is a guard, not proof that the source data is acyclic.

Termination and cycles

A recursive query needs a reason to stop. A finite hierarchy may terminate naturally, but cycles in graph-like data can revisit a node indefinitely, especially with UNION ALL. You can carry a path or visited set to detect repeats, use a depth bound, or enforce acyclic data elsewhere. These strategies have different costs and syntax by engine.

UNION removes duplicate rows between iterations, which can sometimes stop repeated states but may be more expensive and does not solve every cycle when the recursive row includes changing state such as depth.

When recursion fits

Recursive CTEs are useful for organizational trees, category paths, dependency walks, and generated sequences. For a known fixed number of levels, ordinary joins may be easier. Inspect limits and recursion behavior on the target engine. See CTEs.

Carry a path to avoid revisiting nodes

For a graph with possible cycles, carry a path of visited IDs along with the current node. Before expanding to a neighbor, check that the neighbor is not already in the path. This makes cycle handling explicit, though string paths can be slow or tricky for IDs that contain delimiters; some databases offer arrays or built-in cycle clauses. Also decide whether the output should contain a node once or once per distinct path. Those are different questions and may produce very different row counts.

Check the output grain

A recursive walk can return a node once, once per path, or once per depth depending on the columns carried through recursion and the duplicate-elimination rule. Adding depth or a path means two visits to the same node are no longer duplicate rows. That may be correct for path analysis but surprising when counting reachable nodes. Decide whether cycles are invalid, whether multiple paths matter, and what the result row represents before choosing UNION versus UNION ALL or adding a distinct step.

Further reading

Check yourself

0 of 3

Answer without scrolling back up.

  1. What stops a recursive CTE?

  2. What does the recursive step read on each round?

  3. How do you turn a descendants query into an ancestors query?

Cheat sheet

Recursive CTEs

Write a recursive CTE that walks an org chart row by row, follow each iteration of the loop, and see how SQL follows a chain of unknown length.

DATABASE · vizlearn.in/database/recursive_ctes_in_sql.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.

Teaching a course with this? Individual teachers can use it freely; for a whole department or programme, see institutional licences.