Sharon Ben-Moshe is the founder of sqlfmt, a browser-based SQL formatter and validator with misspelled-keyword suggestions across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery.
Compare SQL Server temporary tables (#temp) and table variables (@table). Understand execution plan statistics, recompilation, transaction scope, and tempdb.
Quick answer
SQL Server temporary tables (#temp) support column distribution statistics, non-clustered indexes, and parallel execution plans, making them ideal for intermediate datasets over 100 rows. Table variables (@table) have fixed 1-row cardinality estimates and ignore user transaction rollbacks, making them suitable only for small lookups.
FAQs
Do table variables in SQL Server stay entirely in RAM?
No. Table variables allocate space in tempdb just like temporary tables, and will write to disk if memory pressure occurs.
Can I create a non-clustered index on a table variable?
In modern SQL Server versions (2014+), you can define inline non-clustered indexes within the DECLARE statement, but you cannot run CREATE INDEX afterward.
Can a child stored procedure access a temporary table created by a parent?
Yes. Local temporary tables (#temp) are visible to all child stored procedures and triggers called within that same session.
Why does my query with a table variable run so slowly?
Prior to SQL Server 2019, the query optimizer assumed table variables always contained 1 row, causing it to choose inefficient Nested Loops join plans.
Build fast text search directly in PostgreSQL without external search engines. Master to_tsvector, to_tsquery, relevance ranking with ts_rank, and GIN indexes.
Paste your SQL Server (T-SQL) query into sqlfmt — format, validate against real SQL Server (T-SQL) grammar, and catch keyword typos free in your browser.
T-SQL developers frequently need intermediate storage when executing multi-step business logic or complex stored procedures. SQL Server provides two primary mechanisms: local temporary tables prefixed with # and table variables declared with @.
A persistent myth among database developers is that table variables exist purely in RAM while temporary tables write to disk. In reality, both structures reside in tempdb and write to disk when buffers fill. The critical difference lies in statistics, cardinality estimation, and transaction scope. Read our comparison of CTEs vs subqueries for other temporary data structures.
The tempdb myth: both write to disk
Both #temp tables and @table variables allocate pages inside the tempdb system database. If data fits within the SQL Server buffer cache, both reside in memory. If memory pressure increases, SQL Server flushes pages from both to disk.
The architectural difference between them is how the SQL Server query optimizer approaches planning, index creation, and transaction isolation.
Statistics and cardinality estimation: the 1-row trap
The most impactful performance difference between the two structures is column statistics:
Temporary tables (#temp): SQL Server creates and updates distribution statistics on columns in temporary tables, just like standard user tables.
Table variables (@table): In SQL Server versions prior to 2019, the optimizer creates zero statistics on table variables and assumes the table always contains exactly 1 row.
The cardinality estimation disaster with table variables
-- Declare table variableDECLARE @ActiveUserIds TABLE (UserId INT PRIMARY KEY);-- Insert 100,000 rows into the table variableINSERT INTO @ActiveUserIds (UserId)SELECT UserId FROM Users WHERE IsActive = 1;-- Query joining the table variable-- Prior to SQL Server 2019, the query optimizer estimates 1 ROW!-- Result: Optimizer chooses a Nested Loops join instead of a Hash Join,-- causing millions of random index lookups and freezing the query.SELECT u.UserName, o.TotalAmountFROM @ActiveUserIds aJOIN Users u ON u.UserId = a.UserIdJOIN Orders o ON o.UserId = a.UserId;
While SQL Server 2019 introduced Table Variable Deferred Compilation to improve row count estimation, temporary tables still provide full column distribution histograms, ensuring accurate execution plans for complex queries.
Transaction rollbacks and scope rules
Temporary tables respect transaction boundaries. If you insert rows into #temp inside an explicit transaction and execute ROLLBACK, the rows in #temp are rolled back.
Table variables are exempt from transaction rollbacks. If a transaction rolls back, rows inserted into a @table variable remain intact. This makes table variables ideal for logging error messages or tracking execution audit trails that must survive rolled-back transactions.
Transaction rollback comparison in T-SQL
CREATE TABLE #TempAudit (Id INT);DECLARE @VarAudit TABLE (Id INT);BEGIN TRANSACTION; INSERT INTO #TempAudit VALUES (1); INSERT INTO @VarAudit VALUES (1);ROLLBACK TRANSACTION;-- #TempAudit is empty (0 rows)SELECT COUNT(*) FROM #TempAudit;-- @VarAudit still holds the row (1 row)!SELECT COUNT(*) FROM @VarAudit;
Feature comparison: #temp vs @table
Review the structural differences before choosing an intermediate storage type:
Indexes: Temporary tables support clustered and multiple non-clustered indexes created via CREATE INDEX; table variables only support inline indexes declared during definition.
Scope: Temporary tables are visible to child stored procedures and dynamic SQL within the session; table variables are scoped strictly to the current batch or procedure.
Recompilation: Inserting into #temp can trigger statement recompilation; table variables do not cause stored procedure recompilations.
Parallel plans: Queries modifying temporary tables can use parallel execution plans; queries modifying table variables run single-threaded.
You join intermediate data against multiple large tables.
You need non-clustered indexes or column histograms for complex filters.
You need transaction rollback safety.
Use table variables (@table) when:
The dataset is tiny (fewer than 100 rows), such as a parameter list of IDs.
You want to capture error logs or audit records that survive a transaction rollback.
You want to avoid stored procedure recompilations in high-frequency execution loops.
Actionable checklist for SQL Server intermediate storage
Default to #temp: choose temporary tables as your default for analytical queries and reporting.
Add explicit primary keys: declare PRIMARY KEY constraints on temporary tables to create clustered indexes automatically.
Drop temporary tables: issue DROP TABLE IF EXISTS #temp at the conclusion of stored procedures to free metadata buffers.
Use table variables for audit capture: use @table to capture errors across TRY...CATCH blocks without rollback loss.
Avoid dynamic SQL scoping bugs: remember that table variables cannot be accessed inside EXEC('...') dynamic SQL strings.
Verify execution plans: check estimated vs actual row counts in SQL Server Management Studio to catch 1-row cardinality errors.
Wrapping up
Understanding the trade-offs between SQL Server temporary tables and table variables prevents costly query performance regressions. By relying on #temp tables for large datasets with proper indexing and reserving @table variables for small lookups, you keep execution plans stable and fast. Format your stored procedures and complex T-SQL scripts using sqlfmt for consistent formatting.