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

📚 Interview question

When would you use a temp table, a table variable or a CTE in SQL Server? Explain how they differ in statistics, recompilation, scope, transactions and tempdb usage, and what table variable deferred compilation changed in SQL Server 2019.

Temp tables versus table variables versus CTEs in SQL Server: statistics and cardinality estimates, recompiles, scope, transaction behaviour, tempdb usage, deferred compilation and memory-optimised table variables.

Mid-Level Theory Intermediate cardinality-estimation query-performance sql-server table-variables temp-tables tempdb

🎯 Key points

  • Both #temp tables and @table variables live in tempdb; neither is purely in memory
  • Temp tables get auto-created column statistics (histograms) and allow any index; table variables never get column statistics, only constraints and inline indexes
  • Before 2019 a table variable was estimated at 1 row; deferred compilation (compat level 150+) uses the actual row count at first compile, still without a histogram
  • Temp tables can trigger recompiles when their statistics cross modification thresholds (approximate, version-dependent); table variables rarely recompile
  • Table variable changes are not undone by ROLLBACK of the user transaction; temp table changes are
  • Scope: #temp visible to nested procedures in the session; @table only in its batch; CTE only in one statement
  • Inserts into table variables run serially; SELECT INTO or INSERT WITH (TABLOCK) into a temp table can run in parallel
  • Memory-optimised table variables avoid tempdb allocation contention for high-frequency small sets

⏱ 30-second answer

All three hold an intermediate result, but differently. A CTE is just an inlined query for one statement, with no storage. A temp table (#t) is a real table in tempdb with statistics, any index you like, and visibility to nested procedures; statistics changes can cause recompiles. A table variable (@t) also lives in tempdb but has no column statistics; before SQL Server 2019 the optimiser assumed 1 row, which caused terrible plans on large sets. Deferred compilation (compatibility level 150+) now uses the real row count at first compile, but still no histogram. Table variables also ignore ROLLBACK.

Rule: temp tables for anything sizeable or joined; table variables for small sets or TVPs; CTEs for readability.

🗣 Full answer (senior)

How I would answer this in an interview

"First, a myth: table variables aren't in-memory. Both temp tables and table variables are allocated in tempdb; small ones may stay in the buffer pool either way. The real differences are statistics and compilation. A temp table is a proper table. When I fill it, SQL Server builds column statistics, I can add any index after loading, and the optimiser gets a real histogram for the next statement. The price is that crossing statistics thresholds can trigger a recompile of the statements that use it.

A table variable has no column statistics. Before SQL Server 2019 the optimiser guessed one row at compile time, so if I loaded 500,000 rows and joined them, I'd get nested loops and a query that ran for minutes. At compatibility level 150 and above, deferred compilation compiles the statement on first execution with the actual row count, which fixes the worst case, but it still can't see value distribution and the count is fixed for the cached plan. Table variables also don't take part in transactions: if I ROLLBACK, the rows I inserted into the table variable stay. That's occasionally useful for keeping an error log across a rollback.

Scope differs too: a temp table created in a procedure is visible to procedures it calls; a table variable is visible only in its batch; a CTE only in one statement. So my default: a temp table when the set is more than a few hundred rows or gets joined or filtered; a table variable for small lookups, table-valued parameters, or when I want to avoid recompiles in a very hot procedure; a CTE when I just want readable SQL. The mistake I see is swapping a temp table for a table variable 'for performance' and getting a 1-row estimate."


Comparison

CTE Table variable @t Temp table #t
Storage None (inlined) tempdb tempdb
Column statistics n/a No Yes (auto-created)
Row estimate From base tables 1 row pre-2019; actual count at first compile with deferred compilation Histogram
Indexes No Inline PK, UNIQUE, INDEX in DECLARE Any, added any time
Recompiles n/a Rare When stats change (threshold based)
ROLLBACK undoes changes n/a No Yes
Scope One statement Batch/procedure Session; visible in nested procs
Parallel inserts n/a Insert into table variable is serial SELECT INTO / INSERT ... WITH (TABLOCK) can be parallel

Production example

A pricing procedure loaded around 300,000 candidate prices into a table variable and joined them to a promotions table. On an older compatibility level the plan estimated 1 row, chose nested loops, and ran for 95 seconds. Switching to a temp table with an index on ProductId (or raising compatibility to 160 for deferred compilation) gave a hash join and 2.1 seconds.

🔍 What the interviewer is checking

Checks whether the candidate understands the statistics and compilation differences rather than myths about memory.

Green flags

  • Says both live in tempdb and the key difference is statistics
  • Knows the 1-row estimate and SQL Server 2019 deferred compilation
  • Mentions recompiles for temp tables and the ROLLBACK behaviour of table variables
  • Chooses by data size and how the set is used

Red flags

  • "Table variables are in memory so they're faster"
  • Treats CTEs as materialised temporary results

📚 Learn in depth

1. Where they live

session
 ├─ #Orders      -> tempdb object, name suffixed per session, stats + indexes
 ├─ @Orders      -> tempdb object, no column stats, batch scope
 └─ WITH cte AS  -> nothing stored; text substituted into the query

Small objects in tempdb are often cached in memory pages, so I/O isn't the deciding factor. Statistics are.

2. Estimates before and after deferred compilation

DECLARE @ids TABLE (Id int PRIMARY KEY);
INSERT @ids SELECT Id FROM dbo.Big;   -- 500,000 rows
SELECT ... FROM @ids i JOIN dbo.Orders o ON o.CustomerId = i.Id;

Compat 140:  Estimated rows (@ids) = 1      -> Nested Loops, 500k seeks
Compat 150+: Estimated rows (@ids) = 500,000 -> Hash Match

Deferred compilation fixes the count but not the distribution, and the count is from the first execution of the cached plan. OPTION (RECOMPILE) also makes the optimiser see the current count.

3. Recompilation of temp tables

SQL Server tracks modifications on temp table statistics. Thresholds (roughly 6 rows, then 500, then a sliding threshold based on size) trigger a statistics update and a recompile of statements that reference the table. In a procedure executed thousands of times a second, these recompiles cost CPU. Temp table caching in procedures (reusing the object between calls) helps, but cached statistics can be stale: an explicit UPDATE STATISTICS #t fixes that.

4. Transactions

Table variable changes are logged only enough to roll back the statement, not the user transaction. That makes them good for capturing audit or error info inside a transaction you then roll back.

5. tempdb contention

Thousands of tiny temp objects per second can contend on allocation pages (PFS, GAM, SGAM). SQL Server 2019+ memory-optimised tempdb metadata and multiple data files help; memory-optimised table variables (MEMORY_OPTIMIZED = ON table types) avoid tempdb altogether.

Try it yourself

  1. Load 100,000 rows into a table variable at compatibility level 140 and 160; compare estimated rows in the actual plan.
  2. Repeat with a temp table and check the auto-created statistics with DBCC SHOW_STATISTICS in tempdb.
  3. Insert into a table variable inside a transaction, roll back, and select from it.
  4. Use Extended Events sql_statement_recompile to count recompiles caused by a temp table in a loop.

💻 Code

The same intermediate set as a table variable and as a temp table.

-- Table variable: fine for small sets; no column statistics
DECLARE @Promo TABLE (
    ProductId int NOT NULL PRIMARY KEY,
    Discount  decimal(5,2) NOT NULL
);
INSERT @Promo (ProductId, Discount)
SELECT ProductId, Discount FROM dbo.Promotions WHERE IsActive = 1; -- usually < 200 rows

-- Temp table: large set, joined; statistics and a post-load index
DROP TABLE IF EXISTS #Candidates;
CREATE TABLE #Candidates (
    ProductId int NOT NULL,
    StoreId   int NOT NULL,
    BasePrice decimal(19,4) NOT NULL
);

INSERT #Candidates WITH (TABLOCK) (ProductId, StoreId, BasePrice) -- can go parallel
SELECT p.ProductId, s.StoreId, p.ListPrice
FROM dbo.Products p
CROSS JOIN dbo.Stores s
WHERE p.IsActive = 1;

CREATE CLUSTERED INDEX CX_Candidates ON #Candidates (ProductId, StoreId); -- after loading

SELECT c.ProductId, c.StoreId, c.BasePrice * (1 - ISNULL(pr.Discount, 0)) AS Price
FROM #Candidates c
LEFT JOIN @Promo pr ON pr.ProductId = c.ProductId;

-- Table variables survive ROLLBACK: useful for error capture
DECLARE @Errors TABLE (Msg nvarchar(4000));
BEGIN TRY
    BEGIN TRAN;
        -- ... work that fails ...
        THROW 50001, N'Price below cost', 1;
    COMMIT;
END TRY
BEGIN CATCH
    INSERT @Errors VALUES (ERROR_MESSAGE());
    IF XACT_STATE() <> 0 ROLLBACK;
    SELECT Msg FROM @Errors; -- row is still there
END CATCH;

⚠ Common mistakes

  • Mistake: Believing table variables are in memory and temp tables are on disk. Why it is wrong: Both live in tempdb and both may be cached in memory. Instead: Choose by statistics, scope and recompile behaviour.
  • Mistake: Loading hundreds of thousands of rows into a table variable and joining it. Why it is wrong: No histogram, and 1-row estimates on older compatibility levels, give nested loops and huge run times. Instead: Use a temp table, or at least compatibility level 150+ and check the estimate.
  • Mistake: Creating indexes on a temp table before loading it. Why it is wrong: Every insert maintains the index and the load is slower. Instead: Load first (with TABLOCK), then create the index, unless you need the index to enforce uniqueness during load.
  • Mistake: Expecting ROLLBACK to clear a table variable. Why it is wrong: Table variables are not part of the user transaction. Instead: Use a temp table if the data must roll back.
  • Mistake: Assuming a CTE is a temporary result like a temp table. Why it is wrong: It is inlined and re-evaluated per reference. Instead: Materialise into a temp table when reused.
  • Mistake: Creating and dropping temp objects in a procedure called thousands of times per second without measuring. Why it is wrong: Recompiles and tempdb allocation contention. Instead: Measure recompiles and PAGELATCH waits; consider memory-optimised table variables.

🏛 Senior insight: trade-offs

The decision is about estimates. Every option is fine for 50 rows; at 500,000 rows only one of them gives the optimiser a histogram. When a procedure is slow and uses table variables, the first thing I check in the actual plan is estimated versus actual rows on the table variable scan.

Option Fits when Cost Not when
CTE Readable single statement Re-evaluated per reference Reused or expensive result
Table variable Small sets, TVPs, avoid recompiles, survive rollback No histogram Large sets joined to big tables
Temp table Large or joined sets, need indexes Recompiles, tempdb Ultra-hot tiny procedures
Memory-optimised table variable Very high call rates, small sets Memory, In-Memory OLTP setup Large sets

Measure with the actual plan (estimated vs actual rows), SET STATISTICS IO, the sql_statement_recompile Extended Event and tempdb PAGELATCH_* waits.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions CTEs as an option Why: Checks they know CTEs are inlined, not materialised.
    How to 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.

  2. When: Candidate says table variables have no statistics Why: Checks deeper knowledge of statistics, histograms and cardinality estimation.
    How to answer

    Statistics describe the distribution of values in one or more columns: a density vector (how many distinct values) and a histogram of up to 200 steps on the leading column. The cardinality estimator combines them with its model assumptions to predict how many rows each operator returns, and every plan choice depends on that number.

    Statistics are auto-created on indexes and filtered columns and auto-updated after enough modifications (since compat level 130, roughly SQRT(1000 × rows) for big tables). The CE version follows the database compatibility level.

    Stale or sampled statistics show up as big estimated vs actual row gaps, nested loops over huge inputs and spills. The trade-off: fuller, more frequent updates give better plans but cost I/O and trigger recompiles.

🛠 Real-world problems: how you handle them

Pricing procedure slow after a table variable refactor
Situation
A [retail pricing] procedure on SQL Server [2017 / compatibility level 140] was refactored to use a table variable instead of a temp table "for speed". It processed about [300,000] candidate prices per run.
Signals
Run time jumped from 3 seconds to over 90 seconds after the release; Query Store flagged a regressed plan; CPU on the instance rose during the pricing window.
Investigation
Compared plans in Query Store: the new plan estimated 1 row from the table variable and used nested loops with 300,000 index seeks; the old plan used a hash join. Confirmed with SET STATISTICS IO that logical reads went up about 40x.
Resolution
Immediately reverted to the temp table with a clustered index created after the load. Planned the compatibility level upgrade to 160 so deferred compilation protects other table variable code.
Prevention
Added a code review note that table variables are for small sets, a Query Store regression alert, and a performance test with production-sized data for the pricing run.

How to tell it (STAR)

**S:** At [company], a pricing procedure went from seconds to over a minute and a half after a refactor. **T:** I had to restore performance before the next pricing window. **A:** Query Store showed the new plan estimated a single row from a table variable holding 300,000 rows, causing nested loops. I switched back to an indexed temp table and planned the compatibility level upgrade for deferred compilation. **R:** The run returned to about [2 seconds], and we added a production-sized performance test so the same mistake would be caught in CI.

More in SQL Features

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me