Recursive common table expressions in SQL Server

Every organisation that runs on a relational database eventually stores a hierarchy somewhere. A grocery chain keeps a network of stores under regional divisions; a brewery keeps a bill of materials where a carton of cans sits inside a pallet, inside a layer, inside a shipment; a government agency keeps a chain of authority between a national office and a local service desk. In Australia these structures are easy to spot in the systems behind the supermarket aisles at Coles and Woolworths, the freight manifests moving through Australia Post, and the reporting lines inside an insurer or a bank headquartered in Sydney or Melbourne.

SQL Server gives you a declarative way to walk those relationships without writing a cursor, a while loop, or a stored procedure that fetches one row at a time. That tool is the recursive common table expression, and it is part of the SQL standard rather than a proprietary hack. The tricky part is rarely the syntax; it is understanding how the engine evaluates the query, how deep the hierarchy goes before the default safety limit kicks in, and how to avoid the classic infinite loop caused by a circular reference in dirty data.

That last point matters more here than it might in a tidy North American dataset. Australian reporting often spans statutory hierarchies that cross boundaries: an ABN connected to a trust, a consent record under a My Health Records Act 2012 framework, a policy document attached to a corporate entity. A single mis-keyed parent identifier can turn a clean hierarchy into a loop, and a query written on a development copy with hand-made data will happily hide the problem until it runs against production at 9am on the morning of a quarterly Business Activity Statement lodgement.

This article builds a recursive CTE from scratch, then applies it to practical patterns: org charts, bill of materials, transitive closure for compliance mapping, and a date spine aligned to the Australian financial year. Along the way you will meet the restrictions that surprise people, the type conversion that truncates a path string, and the guardrails that keep a hierarchy walk safe when a federal deadline is closing in.

How SQL Server evaluates a recursive query

A recursive query expression in T-SQL has two members joined by a set operator. The anchor member selects the starting rows, usually the root of a hierarchy where the parent column is NULL. The recursive member references the CTE exactly once, and the engine evaluates it repeatedly, feeding each pass's new rows back in as input to the next pass, until a pass produces no additional rows. That repeated evaluation is what lets the query climb from a general manager to their direct reports to their reports' reports without a single procedural loop.

The syntax is standard SQL, but the keyword differs by platform. PostgreSQL asks for WITH RECURSIVE, and Oracle offers CONNECT BY PRIOR with START WITH. SQL Server needs neither; the presence of the recursive reference inside the CTE tells the engine what to do. The set operator between the members is usually UNION ALL, and the UNION ALL on the final result then tells the reader that duplicate rows are expected, which is normal for tree traversal.

Under the hood, SQL Server runs the recursion as a loop with a spool rather than as a set-based join. This has two practical consequences. First, the recursive member has to stay lean: no GROUP BY, no HAVING, no ORDER BY, no outer joins in which the recursive reference appears on the nullable side, and no subqueries in the recursive part. Second, performance is driven less by statistics and more by the shape of the join and the presence of an index on the parent column. If you find yourself running the same hierarchy walk repeatedly, materialising it into a temporary table with an index on the depth column is usually faster than re-running the recursion for every report.

Most schemas in the wild use the adjacency list model, where each row stores a single parent identifier. It is simple to maintain and easy to insert into, and it is what you will see in Australian ERP and practice management systems. The alternatives are the nested set model, which stores a left and right value for every node, and the hierarchyid type that ships with SQL Server, which encodes path information in a compact binary form and gives you GetLevel, GetAncestor, and IsDescendantOf without any recursion at all. hierarchyid is excellent for hierarchies you control, but it cannot represent multiple parents, and migrating an existing adjacency list to it is a data migration project in its own right.

Building a hierarchy step by step

Start with a table where each employee points at their manager. This is a deliberately ordinary schema, and it is the shape used by most Australian corporate systems.

CREATE TABLE dbo.Employee
(
    EmployeeId int NOT NULL PRIMARY KEY,
    FullName   nvarchar(120) NOT NULL,
    ManagerId  int NULL,
    Position   nvarchar(80) NOT NULL
);

The anchor member picks the root, and the recursive member joins children onto their parent. The Depth column gives the level in the tree, and the Path column concatenates the identifiers so you can build a breadcrumb or detect cycles later.

WITH EmployeeHierarchy AS
(
    SELECT
        e.EmployeeId,
        e.ManagerId,
        e.FullName,
        e.Position,
        0 AS Depth,
        CAST(N'/' + CAST(e.EmployeeId AS nvarchar(20)) + N'/' AS nvarchar(400)) AS Path
    FROM dbo.Employee AS e
    WHERE e.ManagerId IS NULL

    UNION ALL

    SELECT
        e.EmployeeId,
        e.ManagerId,
        e.FullName,
        e.Position,
        h.Depth + 1,
        CAST(h.Path + CAST(e.EmployeeId AS nvarchar(20)) + N'/' AS nvarchar(400))
    FROM dbo.Employee AS e
    INNER JOIN EmployeeHierarchy AS h
        ON e.ManagerId = h.EmployeeId
)
SELECT EmployeeId, FullName, Position, Depth, Path
FROM EmployeeHierarchy
OPTION (MAXRECURSION 100);

Two details in that script cause more support tickets than anything else. The CAST calls around Path exist because the anchor member decides the data type and length of every column in the result set. If the anchor produces nvarchar(60) and the recursive member produces nvarchar(400), the engine takes the anchor's definition and you get a string truncation error the moment the path grows. Declare the widest length in the anchor and cast on the recursive side as well, and keep the arithmetic types explicit so Depth increments cleanly.

The MAXRECURSION option is the other one. SQL Server defaults to 100 levels, and when a hierarchy is deeper than that the query fails with error 457, telling you the maximum recursion has been exhausted. A reporting line under a national retailer rarely goes past five or six levels, but a bill of materials for an Australian manufacturing operation, a genealogy of a land title, or a chain of subcontracted labour supply relationships can exceed it comfortably. OPTION (MAXRECURSION 0) removes the limit, and it should be used with deliberate care, because a cycle in the data combined with an unlimited recursion will run until the machine gives up.

Traversal patterns for Australian reporting problems

The org chart above is the classic example, and it scales to any parent-child table: a chain of responsibility for a claim, a tree of maintenance tasks under an asset, a store network rolled up to a region. The Depth column lets you filter to direct reports only, or to everyone three levels below the general manager, which is how a regional operations team usually wants its cut of the data.

A bill of materials is the same traversal with a different question. Instead of asking who reports to whom, you ask what a finished product is made of, and how many of each component are required at each level. Australian food and beverage manufacturers build these structures constantly, and a recursive CTE will flatten them into a single row per component per level so a planner can explode a shipment into a picking list. If the same parts appear at several levels, a second pass over the flattened result can roll them up into a total quantity.

Transitive closure is the pattern that earns its keep in compliance work. Under the Privacy Act 1988 and the Australian Privacy Principles, an organisation needs to know which entities share data and on what basis. Where those relationships are stored as parent-child rows, a recursive CTE produces the full set of downstream recipients, including indirect ones, so a data-sharing register can be checked for gaps. Healthcare data adds another layer: the My Health Records Act 2012 and the corresponding state legislation create hierarchies of consent and of custodianship, and the same traversal answers "which records does this access request actually touch". Where entity identifiers appear, an ABN lookup tells you whether the counterpart is an incorporated company, a trust, or an individual, which changes the legal obligations that apply.

Finally, hierarchies exist in time. Australian reporting runs on a financial year starting 1 July and ending 30 June, with quarterly BAS periods and a 10% GST applied to most sales, so a reporting calendar is a genuine hierarchy of periods, quarters, and years rather than a flat list of dates. A recursive CTE can generate that spine from a single seed row, and it does so more reliably than a WHILE loop that someone has to maintain. The same query can be tuned for local habits: storing dates as date types and formatting them as dd/mm/yyyy at presentation time, using ISO week numbers for operational reporting that crosses state borders, and remembering that daylight saving applies in New South Wales, Victoria, South Australia, Tasmania, and the Australian Capital Territory, while Queensland, the Northern Territory, and Western Australia sit on a fixed offset.

Guardrails, limits and common failure modes

The failure you will meet first is the runaway cycle. If row A's parent is row B and row B's parent is row A, the recursion never finds a stopping point; with the default limit you get error 457, and with MAXRECURSION 0 you get an execution plan that grows until it exhausts memory. SQL Server has no CYCLE clause, so detection has to be built in. The Path string gives you the means: compare the candidate identifier against the accumulated path and refuse any row whose identifier already appears in it.

    SELECT
        e.EmployeeId,
        h.Depth + 1,
        CAST(h.Path + CAST(e.EmployeeId AS nvarchar(20)) + N'/' AS nvarchar(400))
    FROM dbo.Employee AS e
    INNER JOIN EmployeeHierarchy AS h
        ON e.ManagerId = h.EmployeeId
    WHERE h.Path NOT LIKE N'%/' + CAST(e.EmployeeId AS nvarchar(20)) + N'/%'

The same trick prevents a hierarchy from walking into an unrelated branch that shares an identifier, so it pays to keep the path even when you do not display it. Where a hierarchy is guaranteed acyclic by a foreign key constraint and validated on write, the check can be relaxed, but treating the path as cheap insurance is usually the better trade.

The second common failure is a truncation error that only appears on a Friday afternoon. As noted earlier, the anchor member fixes the column widths for the whole result set, so if your Path column is nvarchar(200) in the anchor, a deep enough hierarchy will fail even though every individual identifier is short. The third is the silent one: NULL parents in the anchor and NULL joins in the recursive member both behave differently from what people expect, and a NULL in the parent column of an otherwise valid row simply drops that row out of the traversal without warning.

Performance problems usually trace back to the join in the recursive member. Without an index on the parent column, each pass scans the whole table, so a hierarchy of a few hundred rows can degrade badly once you point it at a table with millions of rows. Build a nonclustered index on the parent identifier, keep the recursive member's projection to the columns you actually need, and if the same walk feeds several reports, materialise it into a temporary table and index that table instead of repeating the recursion. Query Store and execution plans in Azure SQL and recent SQL Server versions will show the passes, and the spool operator in the plan is the visible sign of the loop.

Practices that keep hierarchy walks healthy

The following habits cover most of the trouble I have seen in Australian production systems, where a hierarchy query feeds a board pack, a regulatory lodgement, or an operational dashboard before a 30 June close.

Take the pattern into your own schema

Pick one parent-child table you already own, a staff structure, a product component list, a consent or entity relationship, and build the anchor and recursive members for it in a scratch database. Add a depth column, add a path column, then deliberately insert a circular reference and confirm your guard catches it. Once that behaves, rewrite it as a stored procedure or view that materialises the result, and put it behind the report that currently relies on a hand-maintained hierarchy or a chain of ad hoc joins.

If you want more SQL Server and .NET material along these lines, Kilt and Code is where I write up the things that come out of real client work, including the testing and debugging habits that keep a hierarchy walk honest. You can follow the blog for new articles, browse the open-source projects, or get in touch about a schema where the recursion is proving awkward.