SQL Temp Table: How to Create a Temporary Table in SQL with Examples

By Cristian G. Guasch • Updated: 04/13/24 • 15 min read

SQL Temp Table: How to Create a Temporary Table in SQL with Examples

Temp tables provide a practical solution for storing intermediate results, and they play a crucial role in optimizing query performance.

By understanding when and how to create temp tables, you can:

  • Simplify complex SQL queries
  • Analyze data more efficiently:
    • Holding intermediate results
    • Allowing the processing of complex queries in a more manageable way
  • Improve the overall performance of their database operations

In this article I will guide you through the process of constructing a temp table in SQL by employing simple yet powerful techniques.

To create a temp table in SQL, you can use the CREATE TEMPORARY TABLE statement, specifying the table’s structure and data types for each column. These tables are utilized for an assortment of purposes, such as optimizing performance, breaking down intricate queries into comprehensible pieces, or handling results not stored in the main tables of a database.

Important: Remember that temp tables are session-specific, meaning they’ll be discarded when the given session ends. Be mindful of the potential drawbacks, especially in high-traffic environments, and employ temp tables judiciously.

Temp tables offer intriguing advantages over traditional tables, as they’re more resource-efficient and provide better query optimization.

These are common temp table use cases in SQL:

  • Processing large datasets
  • Combining data from multiple sources
  • Storing calculations or aggregates
  • Performing recursive operations
  • Testing and development

So, a well-designed temp table can significantly improve performance and maintainability in SQL database operations.

Let’s dive deeper into the process of creating one and explore the potential benefits it can bring to your database management tasks.

Temporary tables can be used in MySQL, PostgreSQL, Oracle, SQL Server, and other database systems, although the syntax and features may vary slightly between implementations.

Creating Temp Tables in SQL

Temp tables also known as temporary tables, they’re created and populated on-the-fly and automatically cleaned up when the session or connection ends. This section aims to highlight some key aspects of temp tables and their role in SQL.

To create a temp table in SQL, the typical syntax involves using the CREATE TEMPORARY TABLE statement, followed by the desired table structure. However, SQL Server users need to use CREATE TABLE along with the # prefix for the table name – a unique feature of SQL Server. Here’s an example for SQL Server:

CREATE TABLE #ExampleTempTable (
    Name NVARCHAR(50),
    Age INT

One noteworthy advantage of temp tables is their support of all DDL (Data Definition Language) and DML (Data Manipulation Language) operations, just like regular tables. This means that you can Insert, Update, Delete, and Select data, as well as create indexes, constraints, and apply modifications to the table structure.

A potential downside of temp tables is that they’re created in the tempdb database, shared by all users in a server. This can cause resource contention and performance issues on busy servers. It’s essential to only use temp tables when required, and utilize other optimization techniques when possible.

Temp tables can be either local or global, depending on their intended use:

  • Local Temp Tables are only visible to the session that created them, and they’re automatically deleted when the session ends. In SQL Server, local temp tables’ names start with a single hash (#).
  • Global Temp Tables are visible to all active sessions and connections. A global temp table remains accessible until the last connection using it terminates. In SQL Server, global temp tables’ names start with two hashes (##).

More about Local and Global Temp tables in the followin section.

It’s crucial to understand that temp tables are created in the tempdb database. They exist solely for the duration of a session or until the connection is terminated. Once the session ends, the temp table is automatically deleted.

Here’s an outline of the process to create a temp table in SQL:

  1. Define a table name prefixed with # or ##.
    • Use a single # for locally-accessible tables.
    • Use double ## for globally-accessible tables.
  2. Specify the column names and data types of the table.
  3. Use an optional PRIMARY KEY and INDEX clause for indexing.

Now, let’s look at an example of creating a temp table. You can follow these simple steps:

-- Create a temp table
CREATE TABLE #TempStudents
    FirstName NVARCHAR(50),
    LastName NVARCHAR(50),
    Age INT

In the above example, a temp table named #TempStudents is defined with four columns: StudentID, FirstName, LastName, and Age. The StudentID column serves as the PRIMARY KEY.

To work with the newly created temp table, you can execute standard SQL operations, like INSERT, UPDATE, SELECT, and DELETE. For instance, to insert data into the #TempStudents table, run the following command:

-- Insert data into the temp table
INSERT INTO #TempStudents (StudentID, FirstName, LastName, Age)
VALUES (1, 'John', 'Doe', 20);

In some cases, you may want to create a temp table by selecting data from an existing table. To do this, use the SELECT INTO command:

-- Create a temp table from an existing table
INTO #TempStudents
FROM Students
WHERE Age >= 18;

The above query generates a #TempStudents table by extracting records from the Students table where the Age is greater than or equal to 18.

In summary, creating a temp table in SQL is a straightforward process that involves defining the table structure, specifying columns and data types, and optionally defining a PRIMARY KEY. Utilizing temp tables in your queries can greatly improve the efficiency and readability of your SQL scripts.

Choosing Between Local and Global Temp Tables

Temp tables come in two types – local and global. Understanding the difference between these two types can help you make a well-informed decision on which one to use in your SQL queries.

First, let’s dive into local temp tables. These tables are specific to the current user session, meaning they’re automatically destroyed once that session ends. An excellent use case for local temp tables would be when you need to perform calculations in a stored procedure or during a specific user’s transaction. The syntax for creating a local temp table in SQL is straightforward:

CREATE TABLE #LocalTempTable (Column1 DataType, Column2 DataType);

Local temp tables have a couple of notable characteristics:

  • The table name must start with a single hash symbol (#)
  • They provide isolation, which is ideal for avoiding conflicts with other users
  • They’re limited in scope and get dropped automatically once the session is over

On the other hand, global temp tables have a broader scope. These tables are accessible to multiple users simultaneously, making them useful when you need to share your temporary data among several users or sessions. Here’s the syntax for creating a global temp table in SQL:

CREATE TABLE ##GlobalTempTable (Column1 DataType, Column2 DataType);

Global temp tables also come with specific attributes:

  • The table name must begin with two hash symbols (##)
  • They allow for data sharing across user sessions
  • They’re not destroyed until the last user accessing the temp table disconnects

When choosing between local and global temp tables, it’s essential to consider the following:

  • Data scope: If the temporary data is user-specific or confined to a single session, pick a local temp table. Conversely, if you must share the data among multiple users, opt for a global temp table.
  • Resource management: Local temp tables offer better resource management as they’re destroyed automatically once the session ends. Global temp tables, on the other hand, require closer monitoring to prevent them from consuming unnecessary resources.

In short: the choice between local and global temp tables depends on your project’s requirements. Always weigh the data scope and resource management aspects for each situation to ensure a well-optimized SQL environment.

Defining Columns and Data Types

When working with temp tables in SQL, it’s crucial to define columns and their data types accurately. This section will cover the essentials of defining columns and data types when you create temp table sql.

Before diving into the specifics, let’s first understand the concept of data types in SQL. In a relational database, data types are used to define the kind of data that a particular column can hold. Common data types include:

  • INT: Represents an integer value
  • VARCHAR: Represents varying-length character data
  • DATE: Represents a date in the format YYYY-MM-DD
  • FLOAT: Represents a floating-point number

When creating a temp table, it’s essential to specify each column’s name and data type. If necessary, you can also define constraints, such as NOT NULL, to ensure data integrity.

To demonstrate how to define columns and data types when creating a temp table in SQL, let’s consider a practical example. Suppose we want to create a temporary table to store information about employees, including their employee ID, first name, last name, hire date, and salary.

Here’s a sample SQL script to create the temp table:

CREATE TEMP TABLE employees_temp (
  employee_id INT PRIMARY KEY,
  first_name VARCHAR(50) NOT NULL,
  last_name VARCHAR(50) NOT NULL,
  hire_date DATE NOT NULL,
  salary FLOAT

In this example, we’ve created a temporary table called employees_temp with five columns:

  • employee_id (integer data type and serves as a primary key)
  • first_name (varchar data type, with a maximum length of 50 characters, and the NOT NULL constraint)
  • last_name (varchar data type, with a maximum length of 50 characters, and the NOT NULL constraint)
  • hire_date (date data type, with the NOT NULL constraint)
  • salary (float data type)

By specifying the data types and constraints as shown in the example, we can ensure that the temp table will only accept data that meets the defined criteria. This helps maintain data consistency and makes it easier to work with the temporary table in subsequent queries.

In summary, defining columns and their data types is an essential step when creating temporary tables in SQL. It helps maintain data integrity, ensures consistent data storage, and simplifies querying the temporary table for further analysis.

Indexing Temp Tables for Improved Performance

When working with temp tables in SQL, optimizing their performance is crucial for the efficiency of your database queries. One effective method to achieve this is by indexing temp tables. Indexing can dramatically speed up your queries by reducing the time it takes to search and sort data, making it an invaluable tool in the world of SQL.

Creating a temp table in SQL typically begins with the CREATE TABLE statement. When building these temp tables, it’s essential to determine which columns will be most frequently accessed or searched upon, as these columns should be indexed for improved performance.

There are a few key reasons why indexing temp tables can significantly improve your query speed:

  • Reduced table scans: Indexes help minimize full table scans by enabling the SQL engine to quickly locate specific rows in the table.
  • Improved sorting: Indexing temp tables accelerates sorting processes, especially when dealing with large amounts of data.
  • Faster joins: When joining multiple tables, indexes play a pivotal role in enhancing performance and shortening query execution times.

To create an index on a temp table, follow these basic steps:

  1. Create the temp table using the CREATE TABLE statement.
  2. Use the CREATE INDEX statement to build an index on one or more columns of the temp table.
  3. Run your queries.

It’s important to note that while indexing temp tables offers numerous benefits, there are some drawbacks to be aware of:

  • Increased overhead: Indexing adds overhead to INSERT, UPDATE, and DELETE operations, requiring more time and resources for maintaining the indexes.
  • Disk space usage: When creating an index in SQL, the database engine needs to consume additional disk space. This can impact system performance if disk space is limited.

To achieve the best results, consider these best practices for indexing temp tables:

  • Analyze your queries and determine the columns most frequently used in your WHERE, GROUP BY, ORDER BY, and JOIN clauses.
  • Opt for covering indexes when possible, as they can hold all the required data for a particular query, minimizing visits to the base table.
  • Continuously monitor and assess index usage to ensure optimal performance.

Optimizing the performance of temp tables in SQL is a crucial component of effective database management. By employing indexing strategies and best practices, you’ll be able to enhance your queries and significantly improve the overall efficiency of your SQL operations.

Joining Temp Tables and Permanent Tables

When working with SQL databases, you may often need to create temp tables and join them with existing permanent tables. Combining temp tables and permanent ones can streamline queries, improve performance, and enable complex data operations to be more manageable.

To create a temp table in SQL, use the CREATE TEMPORARY TABLE statement. Once created, it’s possible to use standard SQL JOIN statements to combine these temp tables with permanent tables. There are four types of joins available in SQL:


Each type of join determines how the tables are combined based on matching, or non-matching, data in the specified columns. Here’s a brief explanation of each type:

  • INNER JOIN: Retrieves rows from both tables when there is a match between the columns specified.
  • LEFT JOIN: Returns all rows from the left table and the matching rows from the right table.
  • RIGHT JOIN: Shows all rows from the right table and the matching rows from the left table.
  • FULL OUTER JOIN: Includes all rows from both tables, matching or not.

Below are examples of how to create temp tables in SQL and join them with a permanent table. Suppose you have a permanent table named employees and a temporary table named temp_salaries:

-- Create a temp table for salaries
  employee_id INT PRIMARY KEY,
  salary DECIMAL(10, 2)

-- Insert sample data into the temp table
INSERT INTO temp_salaries (employee_id, salary)
VALUES (1, 5000.00), (2, 6000.00), (3, 5500.00);

-- INNER JOIN example: Retrieve employee information with matching salaries
SELECT employees.*, temp_salaries.salary
FROM employees
INNER JOIN temp_salaries ON employees.id = temp_salaries.employee_id;

-- LEFT JOIN example: Get all employee data and matching salary data if available
SELECT employees.*, temp_salaries.salary
FROM employees
LEFT JOIN temp_salaries ON employees.id = temp_salaries.employee_id;

-- RIGHT JOIN example: Get all available salary data and matching employee information
SELECT employees.*, temp_salaries.salary
FROM employees
RIGHT JOIN temp_salaries ON employees.id = temp_salaries.employee_id;

-- FULL OUTER JOIN example: Combine all employee data with corresponding salary data
SELECT employees.*, temp_salaries.salary
FROM employees
FULL OUTER JOIN temp_salaries ON employees.id = temp_salaries.employee_id;

These examples showcase how to create temp tables in SQL and join them with permanent tables. By understanding the available join types and their appropriate use, you can optimize queries and perform complex data analysis more effectively.

Modifying Temp Tables

To modify a temp table, SQL offers the ALTER TABLE statement. This command allows users to make changes to the table’s structure, including adding and deleting columns. The syntax for adding a new column is as follows:

ALTER TABLE #TempTableName
ADD ColumnName DataType;

For instance, let’s say we have a temp table named #Orders and we want to add a new column called OrderStatus with varchar data type. The code would look like this:

ADD OrderStatus VARCHAR(50);

In case the user needs to remove a column, they can use the DROP COLUMN statement. The syntax for this command is:

ALTER TABLE #TempTableName

For example, to remove the OrderStatus column from the #Orders temp table, the code will be:

DROP COLUMN OrderStatus;

On occasion, users may need to update data within the temp table before retrieving the final result. The UPDATE command allows for precisely that:

UPDATE #TempTableName
SET ColumnName = NewValue
WHERE Conditions;

Assume we want to change the status of a specific order in the #Orders temp table. The following code changes the OrderStatus of the order with OrderID equal to 101:

UPDATE #Orders
SET OrderStatus = 'Complete'
WHERE OrderID = 101;

Deleting Temp Tables

Temporary tables can be removed from the database either automatically or manually. Let’s examine these two options:

  1. Automatic Deletion: SQL Server automatically removes temp tables when the user disconnects or the session ends. Depending on the method used to create the temp table, the clean-up process might differ. Here’s an overview of how it works:
    • Local Temp Table: Created using a single ‘#’ (hash) symbol in the table name, local temp tables are deleted as soon as the session disconnects from the database.
    • Global Temp Table: Identified by using two ‘##’ (hash) symbols in their table names, global temp tables are deleted when the last session referencing them is closed.
  2. Manual Deletion: Instances might arise where a user prefers to delete a temp table before disconnecting or the session ending. To do this, the DROP TABLE command is used. Here’s how to manually delete a temp table in SQL:
    • Local/Global Temp Table: To delete them manually, execute the following command: DROP TABLE #TempTableName; -- for local temp table DROP TABLE ##TempTableName; -- for global temp table

It’s essential to delete temp tables as they consume memory resources, and having many unused tables can lead to wasted storage space and inefficient querying. Properly managing temp tables ensures an optimized database environment, enabling faster query execution and better performance. Keeping temp tables around for longer periods might also cause conflicts with other tables, create maintenance difficulties, or run the risk of mistakenly including outdated data in new queries.

Related articles