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.sqlSQLite
WITH RECURSIVE chain(id, name, manager_id, level) AS (
-- Anchor: where the walk starts.
SELECT id, name, manager_id, 1
FROM employees
WHERE manager_id IS NULL
UNION ALL
-- Recursive step: everyone reporting to someone already found.
SELECT e.id, e.name, e.manager_id, c.level + 1
FROM employees e
JOIN chain c ON e.manager_id = c.id
)
SELECT level, name FROM chain ORDER BY level, name;
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.
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.
WITH RECURSIVE descendants(id, depth) AS (
SELECT id, 0 FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT e.id, d.depth + 1
FROM employees AS e
JOIN descendants AS d ON e.manager_id = d.id
WHERE d.depth < 10
)
SELECT id, depth FROM descendants;
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.
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.