📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you query a hierarchy such as an org chart or a product category tree in SQL Server? Write a recursive CTE, explain the anchor and recursive members, MAXRECURSION, how you detect and stop cycles, and when you would use hierarchyid or a closure table instead.

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.

Mid-Level Sql Intermediate hierarchies hierarchyid query-performance recursive-cte sql-server t-sql

🎯 Key points

  • Anchor member selects the starting rows; recursive member joins the CTE back to the table, combined with UNION ALL
  • Recursion stops when the recursive member returns no rows
  • Default MAXRECURSION is 100; OPTION (MAXRECURSION n) allows up to 32,767, and 0 removes the limit, so set a realistic depth instead
  • Detect cycles by carrying a path string and checking the child id is not already in it before recursing
  • Prevent cycles at write time too: validate ancestors when a node is moved, in the same transaction
  • Index the parent column (ParentId) so each level is a seek
  • hierarchyid stores the path compactly for fast subtree queries; closure tables store every ancestor-descendant pair
  • Choose by read/write ratio: cache small read-heavy trees in the app, precompute large ones

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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."


Hierarchy storage options

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

Production example

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.

🔍 What the interviewer is checking

Checks the candidate can write a correct recursive CTE and handle depth, cycles and performance.

Green flags

  • Correct anchor, UNION ALL and recursive member
  • Knows MAXRECURSION default of 100 and why not to use 0 blindly
  • Detects cycles with a path and indexes the parent column
  • Knows hierarchyid or closure tables as alternatives with trade-offs

Red flags

  • Uses UNION instead of UNION ALL or can't stop recursion
  • Walks the tree with one query per level from the app

📚 Learn in depth

1. Execution model

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.

2. Rules for the recursive member

  • Must use UNION ALL between anchor and recursive members.
  • Cannot use GROUP BY, TOP, aggregates, DISTINCT or outer joins referencing the CTE.
  • Column types must match exactly; cast the path to varchar(4000) in both members.

3. MAXRECURSION

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.

4. Cycle detection

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.

5. hierarchyid

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.

6. Closure table

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.

Try it yourself

  1. Build a 10,000-row employee table with a 7-level hierarchy and run the recursive CTE with and without an index on ManagerId; compare logical reads.
  2. Create a cycle deliberately and observe the MAXRECURSION error, then add the path check.
  3. Convert the table to hierarchyid and compare subtree query plans.
  4. Load a closure table and compare query and insert costs.

💻 Code

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.

⚠ Common mistakes

  • Mistake: Setting 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.
  • Mistake: No index on the parent column. Why it is wrong: Each iteration is a nested loop join, so every level scans the table. Instead: Index ParentId with the columns you return included.
  • Mistake: Walking the tree from C# one level per query. Why it is wrong: Round trips multiply with depth and fan-out. Instead: One recursive CTE, or a cached tree.
  • Mistake: Mismatched types between anchor and recursive members. Why it is wrong: SQL Server raises "types don't match" for computed columns like the path. Instead: CAST to the same type and length in both members.
  • Mistake: Ordering by level and expecting a tree layout. Why it is wrong: That gives breadth-first order, not parent-then-children. Instead: Order by a path (padded) or hierarchyid.
  • Mistake: Choosing 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.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate talks about tree traversal or depth-first ordering Why: Checks the underlying tree and B-tree concepts behind hierarchy queries and indexes.
    How to answer

    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.

  2. When: Candidate mentions cycle detection in the query Why: Checks whether they fix bad data at write time, not only at read time.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Permission check walking the org chart one query per level
Situation
An [HR approvals] API on Azure App Service checked whether a user could approve a request by walking the org chart in C#, one SQL query per management level, against an Employees table of [40,000] rows.
Signals
p95 latency for approval endpoints was 35 ms of SQL time and rising; Application Insights showed 6-10 SQL dependencies per request; a later data fix introduced a cycle and requests hung until timeout.
Investigation
Grouped Application Insights dependencies by operation and saw repeated identical queries with different ManagerId values. Captured the SQL, confirmed there was no index on ManagerId (each query scanned). Ran the recursive CTE in SSMS with SET STATISTICS IO ON to compare reads.
Resolution
Replaced the loop with one recursive CTE upward from the requester, added an index on ManagerId with included columns, path-based cycle detection and MAXRECURSION 50, and cached the result for 5 minutes. Fixed the cyclic row.
Prevention
Added a write-time validation preventing cycles when managers change, an integration test with a cyclic fixture, and an alert on dependency count per request.

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.

↩ Usually asked after

More in SQL Features

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me