Temp Table vs Table Variable vs Global Temp Table: A Decision Framework for SQL Server
Three temp object types, three genuinely different jobs. Now that you’ve built all three, here’s how to choose without guessing — and why this exact question shows up so often in interviews.
The Decision Tree
Situational Cheat Sheet
| Situation | Right tool |
|---|---|
| Staging a large intermediate result in a complex report | Local temp table (#) |
| Small lookup list of a few rows inside a procedure | Table variable (@) |
| Error/audit log that must survive a transaction rollback | Table variable (@) |
| Sharing a snapshot between two active debugging sessions | Global temp table (##) |
| Data needs real statistics for the optimizer to make good join choices | Local temp table (#) |
| You need to add an index only after seeing the shape of the data | Local temp table (#) — table variables can’t be altered post-declaration |
This Is a Genuinely Common Interview Question
“What’s the difference between a temp table and a table variable?” comes up constantly, precisely because the shallow answer (“table variables are smaller/faster”) is folklore, not fact — in practice, on non-trivial row counts, a table variable’s lack of real statistics can make it slower, not faster, exactly because the optimizer’s row estimate is wrong. The strongest interview answer isn’t a definition — it’s the rollback behavior from the previous lesson, because it’s the one difference that actually changes what your code does, not just how fast it runs.
-- A one-line answer worth having ready: "table variables don't roll back with the
-- surrounding transaction, and historically carry no real statistics for the optimizer"
SELECT 'Table variable' AS type, 'Survives rollback, weak statistics' AS behavior
UNION ALL
SELECT 'Temp table', 'Rolls back with transaction, real statistics';
Enjoyed this?
Subscribe to get every new SQL Server lesson as soon as it’s published, and share it with a developer who’d find it useful.
📡 Subscribe via RSS |
Share on X |
Share on LinkedIn |
Share on Facebook
Want the full structured course with quizzes, projects, and 10+ exercises per chapter? Check out SQL Server for Developers & DBAs, coming soon on this site.