Recursive queries using common table expressions
iterative fixpoint: anchor rows, then recursive member joined to the prior level until no rows (MAXRECURSION default 100, 0 = unlimited)
What changes
- Input
- anchor member sources, then the CTE's own previous iteration
- Output or change
- union of all iteration levels
Syntax at a glance
WITH cte_name ( column_name [ ,...n ] ) AS ( CTE_query_definition -- Anchor member is defined. UNION ALL CTE_query_definition -- Recursive member is defined referencing cte_name. )
Work example
A small hierarchy or sequence must be read one level at a time from a clear starting row.
Run the bounded sample. Mark the anchor and recursive members, then prove the stop condition before raising MAXRECURSION.
Check your work Recursive queries using common table expressions. The query returns levels 1 through 4 and stops. The recursion limit stays finite.
Practice SQL
Open in SQL Flow;WITH Levels AS
(
SELECT 1 AS LevelNumber
UNION ALL
SELECT LevelNumber + 1 FROM Levels WHERE LevelNumber < 4
)
SELECT LevelNumber FROM Levels OPTION (MAXRECURSION 5);
Open Microsoft Learn for full syntax, permissions, and details for your version.