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

📚 Interview question

What is a common table expression (CTE) in T-SQL? Show when it improves a query, explain why SQL Server does not materialise a CTE and what that means if you reference it twice, and compare CTEs with derived tables (subqueries) and temp tables.

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.

Intermediate Sql Intermediate cte execution-plans query-performance sql-server t-sql temp-tables

🎯 Key points

  • A CTE is a named query scoped to the single statement that follows WITH
  • SQL Server inlines CTEs like derived tables; nothing is cached or materialised (no MATERIALIZED hint as in PostgreSQL)
  • Referencing a CTE twice evaluates it twice (two scans in the plan); an occasional optimiser spool can't be relied on
  • Performance is the same as the equivalent subquery; the benefit is readability and reuse within one statement
  • Use a temp table when the result is reused across statements, needs statistics, or benefits from an index you create on it
  • The previous statement must end with a semicolon before WITH
  • CTEs enable recursion and updating or deleting through a CTE (e.g. removing duplicates with ROW_NUMBER)

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 vs derived table vs temp table

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate can write CTEs and knows they are inlined rather than materialised.

Green flags

  • Says CTEs are inlined and perform like derived tables
  • Knows referencing a CTE twice evaluates it twice
  • Chooses temp tables for reuse, statistics or splitting a large query
  • Uses a CTE with ROW_NUMBER to delete duplicates

Red flags

  • Believes CTEs are cached or always faster
  • Can't explain when a temp table would be better

📚 Learn in depth

1. How a CTE is processed

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.

2. Syntax rules

  • WITH must start the statement, so the previous statement needs a terminating semicolon (hence the habit of writing ;WITH).
  • Several CTEs are comma-separated, and later ones can reference earlier ones.
  • ORDER BY inside a CTE is not allowed without TOP/OFFSET, and it doesn't guarantee output order anyway.

3. Modifying through a CTE

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;

4. When a temp table wins

  • The intermediate result is reused in several statements.
  • The query is so large the optimiser times out; splitting it gives smaller, better-estimated plans.
  • Estimates for the intermediate step are badly off; a temp table gives real statistics after it is filled.

The cost: tempdb I/O, and statistics changes can trigger recompiles.

5. CTEs and EF Core

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.

Try it yourself

  1. Write a CTE that aggregates a large table, reference it twice, and count the scans in the actual plan.
  2. Rewrite it with a temp table and compare SET STATISTICS IO output.
  3. Delete duplicate rows using a CTE with ROW_NUMBER.
  4. Write the same query as a CTE and as a derived table and confirm the plans are identical.

💻 Code

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;

⚠ Common mistakes

  • Mistake: Assuming a CTE is computed once and cached. Why it is wrong: SQL Server inlines it; each reference re-runs the query. Instead: Use a temp table when the result is expensive and reused.
  • Mistake: Rewriting a slow subquery as a CTE to make it faster. Why it is wrong: The plan is identical. Instead: Fix indexes, predicates or estimates; use the CTE only for readability.
  • Mistake: Forgetting the semicolon before WITH. Why it is wrong: The parser reads WITH as part of the previous statement and errors. Instead: Terminate every statement with a semicolon.
  • Mistake: Putting 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.
  • Mistake: Building a 15-step CTE chain for a hot query. Why it is wrong: It becomes one huge query that the optimiser may time out on, with compounding estimate errors. Instead: Split heavy steps into temp tables and measure.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions updating or deleting through a CTE Why: Checks practical use of ROW_NUMBER with a CTE and safe deletion.
    How to answer

    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.

  2. When: Candidate mentions that CTEs can be recursive Why: Checks recursive CTEs for hierarchies, MAXRECURSION and cycle handling.
    How to 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.

  3. When: Candidate uses ROW_NUMBER inside a CTE Why: Checks window function fluency: frames, ties and indexing.
    How to answer

    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.

↩ Usually asked after

More in SQL Features

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me