Temporary tables (often called temp tables) are one of the most useful—but underused—features in SQL. They help you store intermediate results, simplify complex queries, and improve performance in many real-world scenarios.
If you’re working with reporting, batch processing, or large datasets, understanding temp tables can significantly improve your database design.
What is a Temporary Table?
A temporary table is a table that exists only for a short duration—typically within a session or a specific scope. Once the session ends or the scope is completed, the table is automatically dropped.
In simple terms:
A temporary table is a short-lived table used to store intermediate data during query execution.
Types of Temporary Tables (SQL Server)
In SQL Server, there are mainly two types:
1. Local Temporary Table (#TempTable)
- Visible only within the current session
- Automatically dropped when the session ends
CREATE TABLE #EmployeeTemp (
Id INT,
Name NVARCHAR(100),
Salary DECIMAL(10,2)
);
2. Global Temporary Table (##TempTable)
- Visible to all sessions
- Dropped when all sessions using it are closed
CREATE TABLE ##GlobalEmployeeTemp (
Id INT,
Name NVARCHAR(100)
);
Where Are Temporary Tables Stored?
Temporary tables are stored in the system database:
- tempdb
Even though they behave like normal tables, they are managed internally and optimized for temporary usage.
Why Use Temporary Tables?
1. Simplify Complex Queries
Instead of writing one massive query, break it into steps:
SELECT * INTO #TempOrders
FROM Orders
WHERE OrderDate > GETDATE() - 30;
SELECT CustomerId, COUNT(*) AS TotalOrders
FROM #TempOrders
GROUP BY CustomerId;
2. Improve Performance
- Avoid recalculating expensive joins
- Store intermediate results
- Reduce repeated computation
3. Data Transformation
- Useful in ETL (Extract, Transform, Load):
- Clean data
- Filter data
- Aggregate data
4. Debugging & Testing
You can inspect intermediate data easily:
SELECT * FROM #TempOrders;
Temporary Tables vs Table Variables
| Feature | Temp Table (#) |
Table Variable (@) |
|---|---|---|
| Scope | Session | Batch/Procedure |
| Indexing | Yes | Limited |
| Statistics | Yes | No |
| Performance | Better for large data | Better for small data |
Indexing Temporary Tables
You can create indexes on temp tables just like normal tables:
CREATE INDEX IX_Temp_Id ON #EmployeeTemp(Id);
This can greatly improve query performance when working with large datasets.
Common Use Cases
- Reporting Systems
- Store filtered datasets before generating reports
- Stored Procedures
- Handle complex logic in multiple steps
- Batch Processing
- Process data in chunks
- Joins Optimization
- Pre-filter data before joining large tables
Best Practices
1. Drop When Not Needed
Although auto-dropped, explicitly dropping is a good practice:
DROP TABLE #EmployeeTemp;
2. Use Indexes Wisely
Add indexes only when needed—too many indexes can slow inserts.
3. Avoid Overuse
Don’t use temp tables for very small datasets—table variables may be better.
4. Monitor tempdb Usage
Heavy use of temp tables can impact performance because everything runs in
tempdb.
Real-World Example
Let’s say you are building a leaderboard system:
- Fetch top scores
- Store them in temp table
- Rank users
SELECT UserId, Score
INTO #TopScores
FROM Scores
WHERE Score > 1000;
SELECT UserId,
RANK() OVER (ORDER BY Score DESC) AS Rank
FROM #TopScores;
Limitations
- Scope-bound (not persistent)
- Heavy usage can slow down
tempdb - Not suitable for permanent storage
Conclusion
Temporary tables are a powerful tool for:
- Breaking down complex queries
- Improving performance
- Managing intermediate data
If used correctly, temp tables can make your SQL code cleaner, faster, and easier to maintain.
One-Line Summary
Temporary tables = short-lived storage for intermediate SQL operations