100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Programming

Temp Tables and Table Variables

Compare local temp tables, global temp tables, and table variables in SQL Server, and learn when each is the right tool for intermediate result sets.

Data ManagementIntermediate10 min readJul 10, 2026
Analogies

Local and Global Temp Tables

A local temp table, created with CREATE TABLE #Name, lives in tempdb and is visible only to the session that created it (and to nested procedure calls within that session), automatically dropped when the session disconnects or, if created inside a stored procedure, when that procedure ends. A global temp table, prefixed ##Name, is visible to every session on the instance and persists until the creating session disconnects and any other session currently referencing it finishes — useful for sharing intermediate data across connections, but rare in practice because it reintroduces the kind of shared mutable state that session-scoped temp tables were designed to avoid.

🏏

Cricket analogy: A local temp table is like a scorer's personal scratch pad used only during their own shift, discarded at end of play, while a global temp table is like a shared whiteboard in the media box that every commentator can see and edit until the last person leaves the room.

sql
-- Local temp table: visible only to this session
CREATE TABLE #RecentOrders (
    OrderId INT PRIMARY KEY,
    CustomerId INT,
    OrderTotal DECIMAL(10,2)
);

INSERT INTO #RecentOrders (OrderId, CustomerId, OrderTotal)
SELECT OrderId, CustomerId, TotalAmount
FROM dbo.Orders
WHERE OrderDate >= DATEADD(DAY, -30, GETDATE());

CREATE INDEX IX_RecentOrders_CustomerId ON #RecentOrders (CustomerId);

SELECT CustomerId, SUM(OrderTotal) AS Last30DayTotal
FROM #RecentOrders
GROUP BY CustomerId;

DROP TABLE #RecentOrders; -- optional, auto-dropped at session end anyway

Table Variables

A table variable, declared with DECLARE @Name TABLE (...), behaves like a local variable rather than a persistent object: it is scoped strictly to the current batch or procedure (not visible to nested calls the way temp tables are), is not affected by an enclosing transaction's ROLLBACK for its data changes in older compatibility levels, and historically was assumed by the optimizer to contain exactly one row regardless of actual size, making it a poor choice for large intermediate result sets — though modern SQL Server (compatibility level 150+) added deferred compilation for table variables, which improves cardinality estimation for many cases. Table variables also cannot have nonclustered indexes created after declaration (only inline PRIMARY KEY/UNIQUE constraints defined at DECLARE time), and cannot have statistics manually updated, which further limits the optimizer's ability to pick a good plan for large ones.

🏏

Cricket analogy: A table variable is like a single over's ball-by-ball scratch tally a scorer keeps mentally rather than writing in the official book — fast and lightweight for six deliveries, but useless as a substitute for the full scorebook if you tried to track an entire innings that way.

Choosing Between Them

As a rule of thumb, use a local temp table for anything holding more than a few hundred rows, anything you need to index explicitly or gather statistics on, or anything that needs to be visible to a nested stored procedure call; use a table variable for small, short-lived row sets inside a single batch where its narrower transactional footprint (in older compatibility modes, DML on a table variable is not rolled back by an outer transaction rollback, since it behaves more like a variable than a durable object) and lower overhead for tiny sizes are actually beneficial. Both live physically in tempdb, so heavy use of either under high concurrency can contend for tempdb resources (allocation pages, log throughput), which is why production systems with heavy temp object usage often provision multiple tempdb data files to spread that contention.

🏏

Cricket analogy: Choosing a table variable for a tiny three-row scratch calc versus a temp table for a full innings-by-innings breakdown is like a scorer deciding between a sticky note for one quick sum versus opening the full scorebook for detailed ball-by-ball analysis.

Since SQL Server 2019 (compatibility level 150), table variable deferred compilation lets the optimizer compile the statement using the table variable's actual row count observed at first execution rather than always assuming one row, closing much of the historical cardinality-estimation gap versus temp tables for moderate sizes.

Do not assume table variable changes are immune to ROLLBACK in all cases — this old belief is only true for DML statements inside an explicit user transaction under certain compatibility levels; relying on it as a deliberate 'audit trail that survives rollback' technique is fragile and discouraged. Test the actual behavior on your target compatibility level rather than assuming legacy documentation applies unchanged.

  • Local temp tables (#Name) are session-scoped and visible to nested procedure calls; they are dropped automatically at session or procedure end.
  • Global temp tables (##Name) are visible instance-wide until the creating session ends and no other session still references them.
  • Table variables (@Name) are scoped to the current batch/procedure and behave more like variables than durable objects.
  • Historically the optimizer assumed one row for table variables; deferred compilation (compat level 150+) improves this significantly.
  • Table variables cannot have nonclustered indexes added after declaration, only inline PRIMARY KEY/UNIQUE constraints at DECLARE time.
  • Both temp tables and table variables live physically in tempdb and can contend for tempdb resources under heavy concurrency.
  • Prefer temp tables for larger or indexed intermediate result sets; prefer table variables for small, short-lived row sets.

Practice what you learned

Was this page helpful?

Topics covered

#Programming#SQLServerTSQLStudyNotes#TempTablesAndTableVariables#Temp#Tables#Table#Variables#StudyNotes#SkillVeris#ExamPrep