Non-recursive CTEs in SQL Server: syntax and readability, inlining rather than materialisation, the cost of referencing a CTE more than once, and choosing between CTEs, derived tables and temp tables.
A CTE is a named query defined with WITH name AS (...) and visible only to the one statement that follows. It makes multi-step logic readable: filter, then aggregate, then join, each step named. SQL Server does not materialise it: the optimiser inlines the CTE exactly like a derived table, so it performs the same as the equivalent subquery. The catch is that if you reference a CTE twice, its query runs twice. When an intermediate result is expensive, reused across statements, or needs statistics or an index, I put it in a temp table instead.
Trade-off: CTEs are free for readability, but they're not a cache.
"A CTE is a named, temporary result for one statement. I write WITH RecentOrders AS (...), then the SELECT that uses it. Its scope ends at that statement. I use them to break a query into readable steps, for recursion, and to update or delete through a window function, like removing duplicates with ROW_NUMBER.
The important mechanism is that SQL Server treats a non-recursive CTE as an inline view. During binding it's substituted into the query, so the optimiser sees one big query and can push predicates into it, reorder joins and so on. That means a CTE is never faster or slower than the same derived table. It also means SQL Server doesn't cache it. If I reference the CTE twice, say once to get totals and once to get the maximum, the plan shows the underlying tables scanned twice. Unlike PostgreSQL, there's no MATERIALIZED keyword to force it.
When I need the intermediate result more than once, across statements, or when the optimiser's estimates for it are bad, I use a temp table. A temp table has statistics, I can index it, and it splits a monster query into steps the optimiser can estimate properly, at the cost of tempdb writes and possible recompiles. The mistake I see is people assuming a CTE is computed once, then wondering why a query that joins the CTE to itself does double the reads. CTEs are about readability; temp tables are about controlling evaluation."
| CTE | Derived table | Temp table (#t) |
|
|---|---|---|---|
| Scope | One statement | One statement | Session/procedure |
| Materialised | No (inlined) | No (inlined) | Yes, in tempdb |
| Statistics/indexes | No | No | Yes |
| Referenced twice | Evaluated twice | Must be repeated | Read twice, computed once |
| Recursion | Yes | No | No |
| Best for | Readability, recursion, update via window function | Small one-off subqueries | Expensive intermediate results, reuse, bad estimates |
A dashboard query used a CTE over 30 days of OrderEvents and joined it to itself to compare each day with the previous one. The plan showed two scans of a 90-million-row table, 1.8 million logical reads and 14 seconds. Loading the daily aggregate (30 rows) into a temp table first, then self-joining it, took 0.9 seconds and 120,000 reads. A LAG window function over the aggregate would have removed the self-join entirely.
Checks that the candidate can write CTEs and knows they are inlined rather than materialised.
Green flags
Red flags
WITH Big AS (SELECT CustomerId, SUM(Total) AS Spend FROM Orders GROUP BY CustomerId)
SELECT ... FROM Big b1 JOIN Big b2 ON ...
binding / algebrisation
|
v
SELECT ... FROM (SELECT ... GROUP BY ...) b1
JOIN (SELECT ... GROUP BY ...) b2 ON ...
Plan:
Hash Match (Inner Join)
├─ Hash Match (Aggregate)
│ └─ Clustered Index Scan (Orders) <- first evaluation
└─ Hash Match (Aggregate)
└─ Clustered Index Scan (Orders) <- second evaluation
The optimiser may occasionally add a spool, but you can't rely on it.
WITH must start the statement, so the previous statement needs a terminating semicolon (hence the habit of writing ;WITH).ORDER BY inside a CTE is not allowed without TOP/OFFSET, and it doesn't guarantee output order anyway.If the CTE references one base table, you can UPDATE or DELETE through it. This is the idiomatic dedupe:
WITH d AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY Email ORDER BY CreatedAt) AS rn FROM Customers)
DELETE FROM d WHERE rn > 1;
The cost: tempdb I/O, and statistics changes can trigger recompiles.
EF Core doesn't generate CTEs from LINQ (it uses derived tables), which is fine because they're equivalent. Use FromSql with a CTE when you need recursion.
SET STATISTICS IO output.ROW_NUMBER.A readable multi-step query with CTEs, the double-evaluation trap, and the temp table fix.
-- Readable steps: filter, aggregate, rank
WITH RecentOrders AS (
SELECT o.OrderId, o.CustomerId, o.Total
FROM dbo.Orders o
WHERE o.OrderDate >= DATEADD(day, -90, SYSUTCDATETIME())
),
CustomerSpend AS (
SELECT CustomerId, SUM(Total) AS Spend, COUNT(*) AS OrderCount
FROM RecentOrders
GROUP BY CustomerId
)
SELECT TOP (20) c.CustomerId, c.Name, s.Spend, s.OrderCount
FROM CustomerSpend s
JOIN dbo.Customers c ON c.CustomerId = s.CustomerId
ORDER BY s.Spend DESC;
-- Trap: CustomerSpend referenced twice = aggregated twice
WITH CustomerSpend AS (
SELECT CustomerId, SUM(Total) AS Spend FROM dbo.Orders GROUP BY CustomerId
)
SELECT s.CustomerId, s.Spend
FROM CustomerSpend s
WHERE s.Spend > (SELECT AVG(Spend) * 3 FROM CustomerSpend); -- second scan of Orders
-- Fix when it is expensive: compute once into a temp table
DROP TABLE IF EXISTS #CustomerSpend;
SELECT CustomerId, SUM(Total) AS Spend
INTO #CustomerSpend
FROM dbo.Orders
GROUP BY CustomerId;
DECLARE @threshold decimal(19,4) = (SELECT AVG(Spend) * 3 FROM #CustomerSpend);
SELECT CustomerId, Spend FROM #CustomerSpend WHERE Spend > @threshold;
WITH. Why it is wrong: The parser reads WITH as part of the previous statement and errors. Instead: Terminate every statement with a semicolon.ORDER BY in a CTE and expecting ordered results. Why it is wrong: Only the outer query's ORDER BY guarantees order. Instead: Order in the final SELECT.Knowing that CTEs are inlined is the senior signal; most candidates think they're a temporary table. The practical skill is deciding when to stop the optimiser treating everything as one query. Temp tables act as a deliberate checkpoint: real statistics, a chance to index, and smaller plans.
| Option | Fits when | Cost | Not when |
|---|---|---|---|
| CTE | Readability, recursion, dedupe via ROW_NUMBER | Re-evaluated per reference | Expensive result used twice |
| Derived table | Small inline subquery | Harder to read when nested | Logic reused in the same query |
| Temp table | Reuse, bad estimates, very large queries | tempdb writes, recompiles | Tiny results in a hot OLTP path |
Prove it with the actual plan (count the scans) and SET STATISTICS IO, TIME ON.
Use a CTE with ROW_NUMBER() OVER (PARTITION BY <business key> ORDER BY CreatedAt DESC, Id DESC) and DELETE FROM cte WHERE rn > 1. The tie-breaker makes it deterministic. On a large table, delete in batches (DELETE TOP (5000) in a loop) to keep the log and locks small, back up or copy the rows first, and then add a unique constraint or index so duplicates can't come back.
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.
A window function computes a value across a set of rows related to the current row, defined by OVER (PARTITION BY ... ORDER BY ... ROWS ...), without collapsing the rows like GROUP BY. ROW_NUMBER gives a unique sequence, RANK leaves gaps on ties, DENSE_RANK doesn't. LAG/LEAD read the previous or next row, replacing self-joins. SUM() OVER (ORDER BY ...) gives running totals.
Two things matter in production: specify ROWS UNBOUNDED PRECEDING for running totals, because the default RANGE frame uses an on-disk spool and groups ties; and create a POC index (partition, order, covering) so the plan avoids a big Sort. You can't filter on a window result in WHERE, so wrap it in a CTE.
Last updated 23 Nov 2026.