How to Use Temp Tables in SQL Server
Last updated July 25, 2026 · By the SaturnSQL team
Prefix a table name with # to create a temp table scoped to your session, via CREATE TABLE #name or SELECT ... INTO #name. Table variables (DECLARE @name TABLE) are lighter but have no statistics, so plans degrade beyond a few hundred rows.
SELECT customer_id, SUM(amount) AS total
INTO #customer_totals
FROM orders
GROUP BY customer_id;
SELECT TOP (10) *
FROM #customer_totals
ORDER BY total DESC;Table variable
DECLARE @ids TABLE (id INT PRIMARY KEY);
INSERT INTO @ids VALUES (101), (102);
SELECT o.*
FROM orders o
JOIN @ids i ON i.id = o.customer_id;#temp tables live in tempdb, support indexes and statistics, and drop automatically when the session ends (or with DROP TABLE #name). A ##global prefix makes the table visible to every session.
Run this in SaturnSQL
SaturnSQL is a browser-based SQL editor for teams: shared query library, schema-aware autocomplete, and scheduled exports to Google Sheets and Slack.
Try it free