To get hands-on practice with SQL, try building a Hotel Reservation System with an ASP. NET Core 6 and Angular project.
Handling complex SQL queries can often be challenging, especially when multiple steps or intermediate results are involved. Temporary tables in SQL offer an effective solution for managing such scenarios. SQL temporary tables store temporary data, typically during a database session or transaction. They are invaluable for holding intermediate results generated during complex queries and calculations. For this reason, they simplify multistep queries, making data processing easier to manage and organize. Like regular tables, you can perform CRUD (create, read, update, delete) operations and join operations on temporary tables. These are automatically dropped when the session ends, but users can also drop them explicitly if needed.
Temporary tables are supported across various database systems, including MySQL, Oracle, and SQL Server. However, the features and syntax for temporary tables can vary depending on the database server.
In this blog, we’ll focus on SQL Server’s implementation of temporary tables, including the two types it supports:
Local temporary tables
Global temporary tables
A local temporary table in SQL Server is created for a single session and is automatically dropped when the session ends. It is identified by a single hash (#
) before the table name and is available only to the session that created it. These tables are automatically deleted when the session ends.
Local temporary tables are created using the CREATE TABLE
statement with a single hash sign (#
) before the table name. Here’s how:
CREATE TABLE #TempTable (ID INT, Name VARCHAR(50));
In this example, the statement creates a local temporary table named #TempTable
with two columns: ID
(of type INT
) and Name
(of type VARCHAR(50)
).
Once the local temporary table is created, we can insert data using regular INSERT
statements. Here’s an example:
INSERT INTO #TempTable (ID, Name) VALUES (1, 'Educative'), (2, 'DevPath');
We inserted two rows using the INSERT
statement into the temporary table.
Once we’ve created and inserted data into a temporary table, we can use it in queries like a regular table. For example, to get the data from a temporary table, we can use the SELECT
statement as follows:
SELECT * FROM #TempTable;
The output of the above commands is shown below:
The above illustration shows the data stored in the temporary table.
Another way to create and insert data into a temporary table is by using the INTO
statement.
To understand this method, let’s suppose we have a Sales
table with columns SaleID
, ProductID
, SalesAmount
, and SaleDate
, as displayed below:
SaleID (PK) | ProductID | SalesAmount | SaleDate |
1 | 1 | 1000 | 19-06-2023 |
2 | 1 | 500 | 21-06-2023 |
3 | 2 | 300 | 22-06-2023 |
4 | 2 | 200 | 23-06-2023 |
5 | 1 | 700 | 23-06-2023 |
You can use the following queries to create the Sales
table:
CREATE TABLE [dbo].[Sales]([SaleID] [int] PRIMARY KEY,[ProductID] [int] ,[SalesAmount] [decimal](18, 0) ,[SaleDate] [date] ,);INSERT [Sales] ([SaleID], [ProductID], [SalesAmount], [SaleDate]) VALUES (1, 1, 1000 , '2023-06-19' )INSERT [Sales] ([SaleID], [ProductID], [SalesAmount], [SaleDate]) VALUES (2, 1, 500 , '2023-06-21' )INSERT [Sales] ([SaleID], [ProductID], [SalesAmount], [SaleDate]) VALUES (3, 2, 300 , '2023-06-22' )INSERT [Sales] ([SaleID], [ProductID], [SalesAmount], [SaleDate]) VALUES (4, 2, 200 , '2023-06-23' )INSERT [Sales] ([SaleID], [ProductID], [SalesAmount], [SaleDate]) VALUES (5, 1, 700 , '2023-06-23' )
To create a temporary table containing only ProductID
and SalesAmount
from the Sales
table using the INTO
statement, you can use the following syntax:
SELECT ProductID, SalesAmountINTO #TempTableFROM Sales
This query creates a temporary table #TempTable
with the columns ProductID
and SalesAmount
, and populates it with the data from the Sales
table.
To explicitly drop a local temporary table when it’s no longer needed, you can use the following command:
DROP TABLE #TempTable;
In this example, we will create a local temporary table to hold total sales by product. The table will contain two columns: ProductID
and TotalSales
.
First, let’s create a temporary table to store the product ID and total sales:
CREATE TABLE #TempResults (ProductID INT, TotalSales DECIMAL(10, 2));
Once the temporary table #TempResults
is created, we then use a query like the following to populate it with the Sales
table:
INSERT INTO #TempResults (ProductID, TotalSales)SELECT ProductID, SUM(SalesAmount)FROM SalesGROUP BY ProductID;
This query will insert the total sales per product into the #TempResults
table.
Once data is inserted into the temporary table, we can use this table in further calculations or queries. For example, to retrieve products where the sale amount is greater than 1000, we can use the following query:
SELECT ProductID, TotalSalesFROM #TempResultsWHERE TotalSales > 1000;
This query will return the products that meet the criteria of having sales amounts greater than
Till now, we have seen how local temporary tables are created, populated, and used within a session. These tables simplify complex queries by breaking them into smaller, more manageable steps. Now that we’ve explored local temporary tables, let’s look at their global counterparts.
Global temporary tables are created using the CREATE TABLE
statement with the double hash sign (##
) before the table name. They are available to all user sessions within a given database and are dropped when the last session using them is closed.
An example of creating a global temporary table is as follows:
CREATE TABLE ##TempTable (ID INT, Name VARCHAR(50));
The above statement creates a global temporary table called ##TempTable
with two columns, ID
and Name
. The ID
column is of type INT
, and the Name
column is of type VARCHAR
, with a limit of 50 characters.
We can use the regular insert statements to insert the data into the global temporary table. An example is given below:
INSERT INTO ##TempTable (ID, Name) VALUES (1, 'Educative'), (2, 'DevPath');
Once we create and insert data into a temporary table, we can use it in queries like a regular table. For example, to get the data from a temporary table, we can use the SELECT
statement as follows:
SELECT * FROM ##TempTable;
The following is the syntax to explicitly drop the local temporary table:
DROP TABLE ##TempTable;
CREATE TABLE ##GlobalTempResults (ProductID INT, TotalSales DECIMAL(10, 2));
This creates a table named ##GlobalTempResults
with two columns: ProductID
and TotalSales
.
The next step is to populate the table using data from the Sales
table. Assume the Sales
table is already created and contains the following data:
Sales Table:
SaleID (PK) | ProductID | SalesAmount | SaleDate |
1 | 1 | 1000 | 19-06-2023 |
2 | 1 | 500 | 21-06-2023 |
3 | 2 | 300 | 22-06-2023 |
4 | 2 | 200 | 23-06-2023 |
5 | 1 | 700 | 23-06-2023 |
Populate the global temporary table with total sales per product:
INSERT INTO ##GlobalTempResults (ProductID, TotalSales)SELECT ProductID, SUM(SalesAmount)FROM SalesGROUP BY ProductID;
This query calculates the total sales for each product and stores the results in ##GlobalTempResults
.
As global temporary tables are accessible across sessions, another user session can now query the data. For example, retrieve products where total sales exceed 1000:
SELECT ProductID, TotalSalesFROM ##GlobalTempResultsWHERE TotalSales > 1000;
Output:
ProductID | TotalSales |
1 | 2200 |
When the table is no longer needed, you can drop it explicitly:
DROP TABLE ##GlobalTempResults;
This ensures that the global temporary table is removed from the database.
The usage of global temporary tables is similar to the local temporary table. However, there are slight differences in both, which are presented in the following table:
Local Temporary Table | Global Temporary Table |
Available to the current session | Available to all sessions |
Starts with a single | Starts with a double |
Persists until the session ends | Persists until all sessions referencing it are closed |
Not visible to other sessions | Visible to all sessions within the same database |
Often used for intermediate results or temporary calculations | Suitable for sharing temporary data across sessions |
Temporary tables are a powerful tool for managing large datasets and simplifying complex queries. They allow for storing intermediate results within a session or transaction, making data manipulation more efficient.
Here’s a quick recap of what you’ve learned:
SQL temporary tables store short-term data needed within a session or transaction. They help break down complex queries into manageable steps.
There are two types of SQL temporary tables:
Local temporary tables: Used only within the session that created them and deleted automatically when the session ends.
Global temporary tables: Shared across all sessions and deleted when the last session using them closes.
Database support: SQL Server, MySQL, and Oracle support temporary tables, though syntax and features vary.
Creation methods in SQL Server: Temporary tables can be created in two ways in SQL Server:
Using CREATE TABLE
with a single #
for local or ##
for global tables.
Using the SELECT INTO
statement to create a local temporary table and copy data directly into it.
Usage: Temporary tables function like regular tables for CRUD operations and joins.
Cleanup: Local tables are automatically removed when the session ends, but both types can be explicitly dropped with DROP TABLE
.
Want to level up your SQL skills? Learn how to design and manipulate databases, write advanced queries, and confidently prepare for SQL interviews with the course below.
The ability to work SQL is becoming an increasingly in-demand skill, both for software developers and people in less technical roles. If you’re interested in learning SQL and have no prior experience with it, then this course will be your light in a dark tunnel. You’ll start by covering the basics of SQL such as how to create a database, how to insert, query, and update data. You’ll also learn fundamental concepts that developers and data scientists use everyday such as multi-table operations, nested queries, and how to set up views. Throughout, you’ll get to execute SQL queries in your browser and see results in real-time - you won’t need to worry about set-up. At the end of this course, you’ll also get some hands-on practice with common SQL interview questions, so when the time comes, you’ll be ready and confident to answer any question that comes your way. Let’s get started!
Can I create indexes on temporary tables?
Are temporary tables faster than regular tables?
Can I use a temporary table in a stored procedure?
Do temporary tables support constraints like primary keys or foreign keys?
Can temporary tables store large data sets?
When to use a temporary table
Free Resources