Temporary Tables and Table Variables
Temporary tables hold intermediate results while a query or procedure works. Picking the right kind makes complex reports simpler and faster.
On this page · 5 min · Intermediate
On this page
- Learning objectives
- Explanation
- Step-by-step screens
- Code example
- Step by step
- Real-world use
- Common mistakes
- Best practices
- Remember this
- Practice exercise
- Mini quiz
- Related topics
- My notes
- Reading time
- 5 min
- Difficulty
- Intermediate
- Updated
- Nov 26, 2026
Related tutorials
Learning objectives#
- Create #temp tables and @table variables
- Know the scope and lifetime of each
- Understand why statistics matter
- Choose the right one for the job
Explanation#
A local temporary table (#Name) lives in tempdb and is visible only to your session (and procedures it calls). It disappears when the session ends or the procedure that created it finishes. It can have indexes and SQL Server keeps statistics on it, so the optimizer knows how many rows it holds.
A table variable (@Name TABLE (...)) is scoped to the batch or procedure. It has no column statistics, so for many rows the optimizer can badly misjudge row counts. SQL Server 2019+ improves this with deferred compilation, but #temp tables remain the safer choice for thousands of rows.
A global temporary table (##Name) is visible to every session until the last one using it closes — rarely needed and easy to clash with other users.
Rule of thumb: table variables for a handful of rows (lookups, IDs to process), #temp tables for larger intermediate results you join or filter again. Often a CTE or a single well-written query needs neither.
Step-by-step screens#
Drawings of SQL Server 2022 Setup and SQL Server Management Studio (SSMS 20) with the ShopDB sample database. The red numbers match the numbered actions under each picture; names on your computer will differ.
Loading pictures…
Code example: Top customers this year with a #temp table#
-- 1. Collect this year's totals once
SELECT o.CustomerId, SUM(oi.Quantity * oi.UnitPrice) AS Total
INTO #CustomerTotals
FROM Orders AS o
JOIN OrderItems AS oi ON oi.OrderId = o.OrderId
WHERE o.OrderDate >= '2026-01-01'
GROUP BY o.CustomerId;
CREATE CLUSTERED INDEX IX_CT ON #CustomerTotals (Total DESC);
-- 2. Use it twice without recalculating
SELECT TOP (5) c.Name, t.Total
FROM #CustomerTotals AS t JOIN Customers AS c ON c.CustomerId = t.CustomerId
ORDER BY t.Total DESC;
SELECT COUNT(*) AS CustomersOver10k FROM #CustomerTotals WHERE Total > 10000;
-- A table variable for a short list
DECLARE @Vip TABLE (CustomerId INT PRIMARY KEY);
INSERT @Vip VALUES (1), (7), (42);
DROP TABLE #CustomerTotals;
Name Total ------------ --------- Asha Verma 84,210.00 Ravi Kumar 61,900.00 ... CustomersOver10k ---------------- 37
This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.
Step-by-step explanation#
- SELECT … INTO creates #CustomerTotals and fills it in one step.
- An index makes the next queries fast.
- Both reports reuse the totals instead of re-running the joins.
- @Vip holds three IDs — a table variable is ideal.
- DROP TABLE frees tempdb early (it would also go when the session ends).
Real-world use case#
A month-end report procedure calculates totals once into a #temp table and then produces five result sets from it, cutting the run time from minutes to seconds.
Common mistakes#
Without statistics the optimizer may assume very few rows and pick nested loops. Use a #temp table.
Copying data costs I/O in tempdb. If one query can do it, keep one query.
Best practices#
- #temp for larger intermediate results
- @table for a few rows
- Index temp tables you query repeatedly
- Drop them when done in long procedures
Remember this#
# = session, ## = everyone, @ = batch.
#temp has statistics; @table variables don’t.
Small → @table, big → #temp.
Practice exercise#
Your task: Create a table variable @Ids with an INT primary key column and insert the values 3 and 5.
Show solution
DECLARE @Ids TABLE (Id INT PRIMARY KEY);
INSERT @Ids VALUES (3), (5);
Mini quiz#
Which object has column statistics?
Want more? Practise all SQL Server MCQs · SQL Server interview questions
My notes#
Saved in this browser.