Home/Blog/Programming/What is a temporary table in SQL?
Home/Blog/Programming/What is a temporary table in SQL?

What is a temporary table in SQL?

7 min read
Mar 06, 2025
content
Local temporary tables
Creating a local temporary table
Inserting data into a local temporary table
Querying data from the local temporary table
Creating temporary tables with the INTO statement
Dropping a local temporary table
Example: Using local temporary tables for the Sales data
Step 1: Create the temporary table
Step 2: Populate the temporary table
Step 3: Query the data
Global temporary tables
Creating a global temporary table
Inserting data into a global temporary table
Querying data from the global temporary table
Dropping a global temporary table
Example: Using global temporary tables for the Sales data
Step 1: Create the global temporary table
Step 2: Populate the global temporary table
Step 3: Query the global temporary table
Step 4: Drop the global temporary table
Comparison of local and global temporary tables
What you’ve learned

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

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

Local 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.

Creating a local temporary table#

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)).

Inserting data into a local temporary table#

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.

Querying data from the local 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:

SQL querying command
SQL querying command

The above illustration shows the data stored in the temporary table.

Creating temporary tables with the INTO statement#

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, SalesAmount
INTO #TempTable
FROM Sales

This query creates a temporary table #TempTable with the columns ProductID and SalesAmount, and populates it with the data from the Sales table.

Dropping a local temporary table#

To explicitly drop a local temporary table when it’s no longer needed, you can use the following command:

DROP TABLE #TempTable;

Example: Using local temporary tables for the Sales data#

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.

Step 1: Create the temporary table#

First, let’s create a temporary table to store the product ID and total sales:

CREATE TABLE #TempResults (ProductID INT, TotalSales DECIMAL(10, 2));

Step 2: Populate the temporary table#

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 Sales
GROUP BY ProductID;

This query will insert the total sales per product into the #TempResults table.

Data population into the temporary table
Data population into the temporary table

Step 3: Query the data#

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, TotalSales
FROM #TempResults
WHERE TotalSales > 1000;

This query will return the products that meet the criteria of having sales amounts greater than 10001000, as displayed in the output given below:

Output of the SQL query
Output of the SQL query

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.

Build a Hotel Reservation System

Build a Hotel Reservation System

To get hands-on practice with SQL, try building a Hotel Reservation System with an ASP. NET Core 6 and Angular project.

To get hands-on practice with SQL, try building a Hotel Reservation System with an ASP. NET Core 6 and Angular project.

Global temporary tables#

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.

Creating a global temporary table#

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.

Inserting data into a global temporary table#

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');

Querying data from the global temporary table#

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;

Dropping a global temporary table#

The following is the syntax to explicitly drop the local temporary table:

DROP TABLE ##TempTable;

Example: Using global temporary tables for the Sales data#

Global temporary tables are useful when multiple sessions or users need to access the same temporary data.

Step 1: Create the global temporary table#

First, we create a global temporary table to hold the total sales by product:

CREATE TABLE ##GlobalTempResults (ProductID INT, TotalSales DECIMAL(10, 2));

This creates a table named ##GlobalTempResults with two columns: ProductID and TotalSales.

Step 2: Populate the global temporary table#

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 Sales
GROUP BY ProductID;

This query calculates the total sales for each product and stores the results in ##GlobalTempResults.

Step 3: Query the global temporary table#

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, TotalSales
FROM ##GlobalTempResults
WHERE TotalSales > 1000;

Output:

ProductID

TotalSales

1

2200

Step 4: Drop the global temporary table#

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.

Comparison of local and global temporary tables#

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 # sign

Starts with a double ## sign

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

What you’ve learned#

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.

Cover
An Introductory Guide to SQL

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!

13hrs
Beginner
73 Playgrounds
73 Quizzes


Frequently Asked Questions

Can I create indexes on temporary tables?

Yes, indexes can be created on local and global temporary tables using the same syntax as regular tables. For example:

CREATE CLUSTERED INDEX idx_ProductID ON #TempTable(ProductID);

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


Written By:
Hamna Waseem
Join 2.5 million developers at
Explore the catalog

Free Resources