Recursive CTEs for hierarchies in SQL Server: anchor and recursive members, depth and path tracking, MAXRECURSION, cycle detection, indexing, and alternatives such as hierarchyid and closure tables.
A recursive CTE has an anchor member (the starting rows, such as the CEO or a root category) and a recursive member that joins the CTE back to the table on ParentId, combined with UNION ALL. SQL Server repeats the recursive member level by level until it returns no rows. The default MAXRECURSION is 100 levels; hitting it raises an error, which often means a cycle in the data. I carry a depth and a path column to order results and detect cycles, and I index ParentId so each level is a seek.
For read-heavy trees, hierarchyid or a closure table answer subtree queries without recursion, at the cost of more work when nodes move.
"For an adjacency list, where each row has a ParentId, I use a recursive CTE. The anchor member selects the starting point, say the manager I'm interested in. Then UNION ALL, and the recursive member joins the table to the CTE itself on e.ParentId = cte.EmployeeId. SQL Server runs the anchor once, then keeps running the recursive part using only the rows produced by the previous iteration, until an iteration returns nothing. Under the hood it's a spool: rows go onto a worktable stack and nested loops pull them off.
I usually carry two extra columns: a Level counter and a Path, like /1/7/42/, built as I go. The level lets me limit depth or indent output; the path lets me sort the tree properly and detect cycles: if the child's id already appears in the path, I stop recursing. That matters because bad data happens. Someone sets a manager's manager to their own report, and the query loops until it hits the default MAXRECURSION of 100 and fails. Setting MAXRECURSION 0 to make the error go away just turns that into an infinite loop.
Performance-wise, each level is a join, so an index on ParentId is essential, otherwise every iteration scans the table. For a tree that's read constantly and changes rarely, like a product category tree on an e-commerce site, I'd consider hierarchyid, where a subtree query is a range seek on the path, or a closure table that stores every ancestor-descendant pair. Both make reads fast and moves expensive. The mistake I see is recursing in C# with one query per level, which turns a 6-level tree into hundreds of round trips."
| Model | Subtree query | Move a node | Fits |
|---|---|---|---|
| Adjacency list + recursive CTE | Recursive, one join per level | Update one ParentId | Most OLTP trees, frequent changes |
hierarchyid |
Range seek with IsDescendantOf |
Update every row in the moved subtree (GetReparentedValue) |
Read-heavy, deep trees, ordered output |
| Closure table | Single join | Delete and insert many pairs | Many ancestor/descendant queries, reporting |
| Materialised path string | LIKE '/1/7/%' (sargable prefix) |
Rewrite paths of the subtree | Simple, portable |
A permissions check walked an org chart in C#, issuing one query per level for each request: about 8 round trips and 35 ms per call at 400 requests per second. Replacing it with one recursive CTE, an index on ManagerId and a 5-minute cache cut it to one 2 ms query. A bad data row later created a cycle, and the path check returned a clear error instead of a recursion failure.
Checks the candidate can write a correct recursive CTE and handle depth, cycles and performance.
Green flags
Red flags
Anchor: SELECT ... WHERE EmployeeId = @root -> level 0 rows
|
Recursive: JOIN Employees e ON e.ManagerId = cte.EmployeeId
(uses ONLY the rows from the previous iteration)
|
level 1 rows -> level 2 rows -> ... -> empty -> stop
Plan shape:
Index Spool (Lazy, stack)
└─ Concatenation
├─ Index Seek (anchor)
└─ Nested Loops
├─ Table Spool (reads previous level)
└─ Index Seek (Employees.IX_ManagerId) <- needs this index
The recursive part is always nested loops, so the inner side must be a seek.
UNION ALL between anchor and recursive members.GROUP BY, TOP, aggregates, DISTINCT or outer joins referencing the CTE.varchar(4000) in both members.The default limit is 100 levels; OPTION (MAXRECURSION n) allows up to 32,767, and 0 means unlimited. The limit protects you from cycles; keep it at a realistic depth such as 50 for an org chart.
Build a delimited path: CAST('/' + CAST(EmployeeId AS varchar(20)) + '/' AS varchar(4000)). In the recursive member, add WHERE cte.Path NOT LIKE '%/' + CAST(e.EmployeeId AS varchar(20)) + '/%'. Also prevent cycles at write time: a check in the command that moves a node.
A CLR-based system type storing a compact binary path. GetAncestor, GetDescendant, IsDescendantOf, GetLevel. A depth-first index on the hierarchyid column makes subtree queries a range seek. Moving a subtree means updating every descendant's value.
A table (AncestorId, DescendantId, Depth) with a row for every pair including self. Subtree = WHERE AncestorId = @id. Insert a node by copying its parent's ancestor rows. Storage grows with depth × nodes.
ManagerId; compare logical reads.hierarchyid and compare subtree query plans.Org chart traversal with depth, path ordering and cycle protection.
CREATE TABLE dbo.Employees (
EmployeeId int NOT NULL CONSTRAINT PK_Employees PRIMARY KEY,
ManagerId int NULL CONSTRAINT FK_Employees_Manager REFERENCES dbo.Employees(EmployeeId),
FullName nvarchar(200) NOT NULL,
CONSTRAINT CK_Employees_NotOwnManager CHECK (ManagerId <> EmployeeId)
);
CREATE INDEX IX_Employees_ManagerId ON dbo.Employees (ManagerId) INCLUDE (FullName); -- seek per level
GO
DECLARE @RootId int = 1;
WITH OrgChart AS (
-- Anchor: the starting manager
SELECT e.EmployeeId, e.ManagerId, e.FullName,
0 AS Lvl,
CAST(CONCAT('/', e.EmployeeId, '/') AS varchar(4000)) AS Path
FROM dbo.Employees e
WHERE e.EmployeeId = @RootId
UNION ALL
-- Recursive: direct reports of the previous level
SELECT e.EmployeeId, e.ManagerId, e.FullName,
oc.Lvl + 1,
CAST(CONCAT(oc.Path, e.EmployeeId, '/') AS varchar(4000))
FROM dbo.Employees e
JOIN OrgChart oc ON e.ManagerId = oc.EmployeeId
WHERE oc.Path NOT LIKE CONCAT('%/', e.EmployeeId, '/%') -- stop on cycles
)
SELECT REPLICATE(N' ', Lvl) + FullName AS OrgTree, Lvl, Path
FROM OrgChart
ORDER BY Path
OPTION (MAXRECURSION 50); -- realistic depth, not 0
-- hierarchyid alternative: subtree = range seek
CREATE TABLE dbo.Categories (
Node hierarchyid NOT NULL CONSTRAINT PK_Categories PRIMARY KEY, -- depth-first order
Lvl AS Node.GetLevel() PERSISTED,
CategoryId int NOT NULL UNIQUE,
Name nvarchar(100) NOT NULL
);
DECLARE @parent hierarchyid = (SELECT Node FROM dbo.Categories WHERE CategoryId = 12);
SELECT CategoryId, Name, Lvl
FROM dbo.Categories
WHERE Node.IsDescendantOf(@parent) = 1
ORDER BY Node;
Note: string paths sort lexically (/10/ before /2/); pad ids or use hierarchyid when exact sibling order matters.
MAXRECURSION 0 to silence the error. Why it is wrong: The error usually means a cycle; unlimited recursion turns it into a runaway query. Instead: Find the cycle, add path-based detection and a realistic limit.ParentId with the columns you return included.CAST to the same type and length in both members.hierarchyid.hierarchyid for a tree that is reorganised daily. Why it is wrong: Moving a subtree rewrites every descendant. Instead: Use an adjacency list with a recursive CTE for frequently changing trees.The senior part is choosing the storage model by read/write pattern, and protecting against bad data. Adjacency lists are simple and cheap to change; recursive CTEs make them queryable. When the tree is read thousands of times a second, either cache it in the app (trees of a few thousand nodes fit easily in memory) or store a precomputed form.
| Option | Fits when | Cost | Not when |
|---|---|---|---|
| Recursive CTE | Changing trees, moderate depth | One join per level | Hot path at high RPS without caching |
| hierarchyid | Read-heavy, ordered subtree queries | Moves rewrite subtrees, CLR type in EF Core needs mapping | Frequent reorganisation |
| Closure table | Many ancestor queries, reporting | Extra storage, write logic | Very deep, very large trees |
| App-side cache | Small tree, read on every request | Cache invalidation | Large or highly volatile trees |
Measure with SET STATISTICS IO per level count and watch the spool operators in the actual plan.
A tree is a hierarchy of nodes with one root, where each node has children and no cycles. A binary tree limits each node to two children (left, right). A binary search tree (BST) adds an ordering rule: left subtree < node < right subtree, so search, insert and delete take O(height).
If the tree is balanced, height is O(log n); if you insert sorted data into a plain BST it degenerates into a linked list with O(n) height. Self-balancing trees (red-black, AVL) keep O(log n); .NET's SortedSet and SortedDictionary are red-black trees.
Traversals: in-order (sorted output for a BST), pre-order (copy/serialise), post-order (delete/evaluate), level-order (BFS).
Trees are everywhere: database B+ tree indexes, file systems, JSON/XML/DOM, Roslyn syntax trees, expression trees, org charts.
Validate on write: before setting ParentId = @newParent for node @id, run a recursive CTE from @newParent up to the root and reject the move if @id appears among its ancestors. Do the check and update in one transaction with UPDLOCK, HOLDLOCK (or serializable) on the affected rows so two concurrent moves can't create a cycle together. Add CHECK (ParentId <> Id) for the trivial case.
How to tell it (STAR)
**S:** At [company], our approval API walked the org chart from C#, one query per level. **T:** I was asked to cut its latency and stop the hangs we saw after a bad data change. **A:** I replaced the loop with a recursive CTE, added an index on ManagerId, a path check for cycles and a sensible MAXRECURSION, and added validation so moves can't create cycles. **R:** SQL time per request dropped from about [35 ms] to [2 ms], and the cycle that had caused hangs now produced a clear error and was blocked at write time.
Last updated 23 Nov 2026.