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.
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.
"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."
| 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 |
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.
Checks whether the candidate understands the statistics and compilation differences rather than myths about memory.
Green flags
Red flags
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.
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.
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.
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.
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.
DBCC SHOW_STATISTICS in tempdb.sql_statement_recompile to count recompiles caused by a temp table in a loop.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;
TABLOCK), then create the index, unless you need the index to enforce uniqueness during load.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.PAGELATCH waits; consider memory-optimised table variables.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.
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.
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.
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.
Last updated 23 Nov 2026.