Advertisement
Intermediate SQL Server, Temporary Tables & Table Variables

How do statistics and query optimization differ between temporary tables and table variables, and how does this affect performance for larger data sets?

Short answer

SQL Server maintains statistics for temporary tables, similar to regular tables, allowing the optimizer to make reasonably accurate estimates about the amount of data they contain, while table variables historically have had very limited or no statistics, causing the optimizer…

Save SQL Server mock interview
Advertisement
AModel answer
SQL Server maintains statistics for temporary tables, similar to regular tables, allowing the optimizer to make reasonably accurate estimates about the amount of data they contain, while table variables historically have had very limited or no statistics, causing the optimizer to often assume they contain only a single row, which can lead to poor execution plans when a table variable actually holds a large amount of data.
-- Temporary table: benefits from statistics for larger data sets
CREATE TABLE #LargeTempData (Id INT, Value VARCHAR(100));

-- Table variable: may perform worse for large amounts of data
DECLARE @LargeTableVar TABLE (Id INT, Value VARCHAR(100));
Real-world example
A developer notices a stored procedure using a table variable performing poorly once it started holding tens of thousands of rows, and switches to a temporary table instead, letting the optimizer generate a much more efficient execution plan based on accurate statistics.
Likely follow-ups
  • At what data size does this statistics difference typically start to matter in practice?
  • Have recent versions of SQL Server improved statistics support for table variables?
Related topics