Recursive CTEs
A recursive CTE repeats a query on its own results, which is how SQL walks a tree of unknown depth.
On this page · 5 min · Intermediate
On this page
- Learning objectives
- Explanation
- Step-by-step screens
- Code example
- Step by step
- Real-world use
- Common mistakes
- Best practices
- Remember this
- Practice exercise
- Mini quiz
- Related topics
- My notes
- Reading time
- 5 min
- Difficulty
- Intermediate
- Updated
- Nov 26, 2026
Related tutorials
Learning objectives#
- Write an anchor and a recursive member
- Track the level and path
- Stop infinite loops with MAXRECURSION
- Use it for category trees and date ranges
Explanation#
A recursive CTE has two parts joined by UNION ALL: the anchor (the starting rows, such as top-level categories) and the recursive member, which joins the CTE to the table to find the next level.
SQL Server runs the recursive member again and again on the rows produced in the previous round until it returns no rows.
Carry a Level column (Level + 1) and a Path string to sort and indent the output. The default limit is 100 levels; OPTION (MAXRECURSION n) changes it (0 = unlimited — dangerous with bad data).
The same technique generates sequences, such as every date in a month, without a numbers table.
Step-by-step screens#
Drawings of SQL Server 2022 Setup and SQL Server Management Studio (SSMS 20) with the ShopDB sample database. The red numbers match the numbered actions under each picture; names on your computer will differ.
Loading pictures…
Code example: Category tree with levels and paths#
WITH Tree AS (
SELECT CategoryId, Name, ParentId, 0 AS Level,
CAST(Name AS NVARCHAR(400)) AS Path
FROM Categories
WHERE ParentId IS NULL -- anchor: top level
UNION ALL
SELECT c.CategoryId, c.Name, c.ParentId, t.Level + 1,
CAST(t.Path + N' > ' + c.Name AS NVARCHAR(400))
FROM Categories AS c
JOIN Tree AS t ON c.ParentId = t.CategoryId -- recursive member
)
SELECT REPLICATE(N' ', Level) + Name AS Category, Path
FROM Tree
ORDER BY Path
OPTION (MAXRECURSION 20);
Category Path
----------------------- ------------------------------------
Electronics Electronics
Computers Electronics > Computers
Laptops Electronics > Computers > Laptops
Monitors Electronics > Computers > Monitors
Phones Electronics > PhonesThis example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.
Step-by-step explanation#
- The anchor selects categories with no parent.
- The recursive member finds the children of the previous level.
- Level and Path grow with each round.
- Indentation and ORDER BY Path show the tree.
- MAXRECURSION 20 protects against a loop in bad data.
Real-world use case#
An online shop builds its category menu and breadcrumb trails (“Electronics > Computers > Laptops”) with one recursive query.
Common mistakes#
Recursive CTEs require UNION ALL.
A category that is its own ancestor loops until MAXRECURSION stops it with an error. Validate parent IDs.
Best practices#
- Index ParentId
- Cast string columns to a fixed type in both parts
- Set MAXRECURSION deliberately
- Consider hierarchyid for very large trees
Remember this#
Anchor UNION ALL recursive member.
Level + 1 each round.
Default limit: 100.
Practice exercise#
Your task: Write a recursive CTE that returns the numbers 1 to 10.
Show solution
WITH N AS (SELECT 1 AS n UNION ALL SELECT n + 1 FROM N WHERE n < 10)
SELECT n FROM N;
Mini quiz#
What is the default maximum recursion level?
Want more? Practise all SQL Server MCQs · SQL Server interview questions
My notes#
Saved in this browser.