Lesson 1 of 3 Advanced Query Techniques

Common Table Expressions and Recursion

This lesson explains how CTEs structure complex queries and how recursive CTEs walk hierarchies of unknown depth.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe the scope and evaluation of a common table expression.
  • Explain the anchor and recursive members of a recursive CTE.
  • Identify how MAXRECURSION and cycle checks protect recursive queries.

Non-recursive CTEs

A CTE is introduced with WITH name (optional column list) AS (query) and is visible to the single statement that follows, which can be SELECT, INSERT, UPDATE, DELETE or MERGE. Several CTEs are separated by commas, and later ones can reference earlier ones, which turns a deeply nested query into readable steps. A statement before WITH must end with a semicolon.

WITH Monthly AS (
    SELECT CustomerID, DATETRUNC(month, OrderDate) AS OrderMonth, SUM(TotalDue) AS Revenue
    FROM Sales.Orders
    GROUP BY CustomerID, DATETRUNC(month, OrderDate)
), Ranked AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY OrderMonth ORDER BY Revenue DESC) AS rn
    FROM Monthly
)
SELECT OrderMonth, CustomerID, Revenue
FROM Ranked
WHERE rn <= 5;

A CTE is not stored: the optimizer expands it wherever it is referenced, so a CTE referenced twice can be evaluated twice. When an intermediate result is expensive and reused across statements, a temporary table is better.

True or false

Non-recursive CTEs

Exam skills 1.3.1

Decide whether each statement about CTEs is true.

Log in to try this activity Interactive activities are free with an account.

Recursive CTEs

A recursive CTE contains an anchor member, which returns the starting rows, then UNION ALL and a recursive member that joins the CTE to the table to find the next level. Execution repeats the recursive member with the rows produced by the previous iteration until it returns no rows. A level counter and a path string are often carried along to show depth and lineage.

WITH CategoryTree AS (
    SELECT CategoryID, ParentID, Name, 0 AS Depth,
           CAST(Name AS nvarchar(1000)) AS Path
    FROM Catalog.Category
    WHERE ParentID IS NULL                       -- anchor: top-level categories
    UNION ALL
    SELECT c.CategoryID, c.ParentID, c.Name, t.Depth + 1,
           CAST(t.Path + N' > ' + c.Name AS nvarchar(1000))
    FROM Catalog.Category AS c
    JOIN CategoryTree AS t ON c.ParentID = t.CategoryID   -- recursive member
)
SELECT * FROM CategoryTree
OPTION (MAXRECURSION 50);

The following diagram shows the iterations of a recursive CTE.

How a recursive CTE runs. The anchor member returns the starting rows, such as top-level categories. The recursive member joins the CTE to the table to find the next level and runs again with the rows the previous iteration produced, until it returns no rows. UNION ALL combines every level, and MAXRECURSION limits the depth so a cycle cannot loop forever.
Each iteration uses only the rows the previous one produced.
Put in order

How a recursive CTE runs

Exam skills 1.3.1

Put the stages of recursive CTE execution in order.

Log in to try this activity Interactive activities are free with an account.

Recursion limits and cycles

The default limit is 100 recursion levels; the statement fails with an error when it is exceeded. OPTION (MAXRECURSION n) raises or lowers the limit, and 0 removes it. A cycle in the data, such as two categories that are each other's parent, would recurse forever, so the limit is a safety net, and a path check such as WHERE t.Path NOT LIKE '%' + c.Name + '%' or a visited-ID list prevents revisiting nodes. Column types in the anchor and recursive members must match exactly, which is why the example casts the path.

Worked example

An organization chart

An Employees table stores each employee's ManagerID. A report must list everyone who reports to a given director at any depth, with their level below the director. Some branches are 120 levels deep after a data migration created long chains. Which query should the developer write?

Write a recursive CTE whose anchor selects the director and whose recursive member joins Employees on ManagerID = cte.EmployeeID, carrying a level counter, and add OPTION (MAXRECURSION 200) or 0 with a cycle check. Without the option, the query fails after 100 levels. A fixed number of self-joins cannot handle an unknown depth.

Check yourself

What is the default recursion limit of a recursive CTE, and how is it changed?

Show answer

100 levels; OPTION (MAXRECURSION n) changes it, and 0 removes the limit.

Exam Tips

Remember for the exam

  • Unknown-depth hierarchy: recursive CTE with anchor UNION ALL recursive member.
  • Default recursion limit is 100; change it with OPTION (MAXRECURSION n).
  • A CTE lasts for one statement and may be evaluated once per reference.
  • Anchor and recursive column types must match.