skip to content

In SQL Server, how does a table variable differ from a #temp table in statistics, scope, rollback and plan quality?

level: middleimportance: must knowfreq 64%

answer

  1. both live in tempdb
  2. statistics on one only
  3. batch scope versus session scope
  4. survives a ROLLBACK
  5. deferred compilation since 2019

basics

~20 s

Both live in tempdb. A table variable has no statistics, is scoped to its batch, ignores ROLLBACK and gets no parallel plan for modifications; a #temp table has statistics and full indexing and can last the whole session, at the cost of recompiles.

solid answer

~50 s

Neither is a memory-only structure: both are created in `tempdb`. A **table variable** (`DECLARE @t TABLE (...)`) is scoped to the batch, procedure or function that declares it, is invisible to nested procedures and dynamic SQL, keeps **no distribution statistics**, takes indexes only inline in its declaration, cannot be the target of `SELECT INTO`, and is **not affected by a transaction rollback**. Queries that modify it do not get parallel plans. A **#temp table** lives for the session, or until the procedure that created it ends, is visible to the procedures it calls, has statistics and `CREATE INDEX`, and joins the transaction, but it causes more recompilations. Before SQL Server 2019 the optimizer compiled table-variable queries with a fixed one-row guess; at compatibility level 150 and above, **table variable deferred compilation** uses the actual row count at first execution, though still without column statistics.

code

sql · 12 lines
sql
DECLARE @log TABLE (step varchar(50), logged_at datetime2 DEFAULT SYSDATETIME());
CREATE TABLE #work (order_id int PRIMARY KEY);

BEGIN TRANSACTION;
    INSERT INTO #work (order_id) VALUES (1), (2);
    INSERT INTO @log (step) VALUES ('staged two orders');
ROLLBACK TRANSACTION;

SELECT COUNT(*) AS work_rows FROM #work;  -- 0: the temp table rolled back
SELECT COUNT(*) AS log_rows  FROM @log;   -- 1: the table variable kept its row

DROP TABLE #work;

go deeper

for a junior

Recall the two syntaxes, DECLARE @t TABLE and CREATE TABLE #t, and that both are stored in tempdb rather than only in memory.

for a middle

Explain the differences in scope, statistics, indexing and rollback, and what deferred compilation at compatibility level 150 changed about row estimates.

for a senior

Diagnose bad plans from table variables holding thousands of rows, recompile storms from temp tables in hot procedures, and pick the right one with actual plans.

for a principal

Set team guidance by data size and reuse rather than folklore, and treat the compatibility level as part of how table-variable code will perform.

## Two kinds of scratch table T-SQL code stages intermediate rows in one of two objects: - a **table variable**, `DECLARE @recent TABLE (order_id int PRIMARY KEY, total decimal(12, 2));` - a **local temporary table**, `CREATE TABLE #recent (order_id int PRIMARY KEY, total decimal(12, 2));`, or one created by `SELECT ... INTO #recent`. The popular rule of thumb, "table variables are in memory, temp tables are on disk", is **false**. The documentation is explicit: a table variable is not a memory-only structure, it is created in `tempdb` just like a temporary table, and both are processed in memory when memory is available. The real differences are in scope, statistics, transactions and how the optimizer treats them. ## Scope and visibility | | Table variable | `#temp` table | |---|---|---| | Lives until | the end of its batch, procedure or function | the end of the creating procedure, or else the session | | Visible to procedures it calls | no | yes | | Visible to `EXEC` / `sp_executesql` run from the same scope | no | yes | | Created by `SELECT ... INTO` | not allowed | allowed | | Altered after creation | no | yes, `ALTER TABLE` and `CREATE INDEX` | A `##` prefix makes a **global** temporary table, visible to all sessions; that is a separate tool for cross-session staging. ## Statistics, estimates and plans This is where the choice usually matters. - A table variable has **no distribution statistics** and does **not trigger recompiles**. The optimizer cannot see how values are spread, so a join or filter on it is costed from a guess. - Before **SQL Server 2019**, statements referencing a table variable were compiled with a **fixed one-row guess**, because the variable was empty at compile time. A table variable holding 50,000 rows still got a plan sized for one, typically nested loops where a hash join was needed. - **Table variable deferred compilation**, enabled at **database compatibility level 150** (SQL Server 2019's default) and above, defers compiling the statement until its first execution and uses the **actual row count**, as a temporary table does. It can be switched off at database or statement scope without lowering the compatibility level. - Deferred compilation fixes the **row count**, not the distribution. The cached plan also reuses the row count seen at first compile, so a variable that holds 10 rows on one call and a million on the next still suffers. - A `#temp` table gets **automatic statistics** and **recompiles** when they change enough, which buys accurate plans at the cost of compile time in hot procedures. - **Modifying** a table variable never uses a parallel plan; large inserts into one are serial. The documentation's advice is to be cautious with table variables expected to hold more than about 100 rows and to prefer temporary tables when cost-based choices matter, while recommending you test both. ## Indexing - Table variables cannot be indexed with `CREATE INDEX` or altered after declaration. Since SQL Server 2014 you can declare `PRIMARY KEY`, `UNIQUE` and inline `INDEX` definitions in the `DECLARE` itself. - `#temp` tables support every index type, added at any point, plus statistics on any column. One documented limit remains: temporary tables cannot be partitioned. ## Transactions and rollback Table variables are **not affected by a rollback**, because they are not part of the persistent database. That is a feature in error handling: 1. Declare `@log TABLE (...)` before `BEGIN TRANSACTION`. 2. Insert progress or diagnostic rows into it during the work. 3. In the `CATCH` block, roll back, and the rows in `@log` are still there to be written to a permanent table. A `#temp` table participates in the transaction like any other table, so its changes roll back with the rest. ## Choosing 1. **Small, fixed-size sets** such as a list of IDs passed around a procedure, or rows that must survive a rollback: a table variable. 2. **Larger sets that are joined, filtered or reused** several times, or that need extra indexes added later: a `#temp` table. 3. When unsure, compare the actual plans with realistic row counts. The general trade-offs of staging data in temporary tables are covered with temporary tables as an engine-neutral topic.

  • Why can a query joining a large table variable still get a poor plan on SQL Server 2019 or later?
    Deferred compilation supplies the table variable's actual row count at first execution, but there are still no column statistics, so selectivity of a join or filter on its columns remains a guess. The plan is also cached with the first execution's row count, so later calls with very different counts reuse it. A `#temp` table with its own statistics avoids both problems.
  • Can dynamic SQL run with sp_executesql read a table variable declared in the calling batch?
    No. A table variable is visible only in the scope that declared it, and dynamic SQL runs in its own scope, so it cannot reference it. A `#temp` table created earlier in the session is visible to the dynamic batch, which runs nested inside that session, so stage the rows there instead, or declare and fill the table variable inside the dynamic batch itself.

  • Table variables are held in memory and never touch tempdb.
  • A ROLLBACK also removes the rows inserted into a table variable.
  • Table variables keep column statistics just like temporary tables.
  • Deferred compilation gives table variables full column statistics.
  • A procedure can read a table variable declared by its caller.
  • You can add an index to a table variable with CREATE INDEX.

Assumes SQL Server 2025; table variable deferred compilation, at compatibility level 150 and above since SQL Server 2019, replaced the fixed one-row guess used by earlier releases.