Select into and temporary tables in MS SQL Server
Last Updated :
10 Sep, 2024
In SQL Server, the SELECT INTO TEMP TABLE
statement is used to select data from one or more source tables and insert it into a temporary table.
Temporary tables are extremely useful when dealing with intermediate results, or when working with subsets of data within a session without modifying or affecting the original tables.
In this article, We will learn about SELECT INTO TEMP TABLE
is a SQL Server in detail by understanding various examples and so on.
SELECT INTO TEMP TABLE
is a SQL Server
SELECT
INTO TEMP TABLE
is a SQL statement used to select data from one or more tables and insert it into a temporary table?
- Temporary tables are useful when we need to store intermediate results or work with subsets of data within a session without affecting the main tables in the database.
The general syntax of this statement is:
SELECT columns
INTO TEMPORARY TABLE temp_table_name
FROM source_table
WHERE condition;
Key Points:
- Temporary Tables: These are created in a database session and are automatically dropped at the end of the session.
- INTO Clause: The
INTO TEMPORARY TABLE
clause is used to create the temporary table and populate it with the selected data.
- No Pre-existing Table: The temporary table does not need to pre-exist, as this command both creates the table and inserts data into it.
Examples of SELECT INTO TEMP TABLE
is a SQL Server
EmployeeID |
FirstName |
LastName |
Department |
Salary |
1 |
John |
Doe |
IT |
60000.00 |
2 |
Jane |
Smith |
HR |
50000.00 |
3 |
Mike |
Brown |
IT |
70000.00 |
4 |
Linda |
Green |
Marketing |
55000.00 |
This table contains four columns: EmployeeID
, FirstName
, LastName
, Department
, and Salary
, with the corresponding data that was inserted.
Example 1:
Create a Temporary Table with IT Department Employees
We want to create a temporary table with the employees who belong to the IT department from the Employees
table.
Query:
SELECT EmployeeID, FirstName, LastName, Salary
INTO #IT_Employees
FROM Employees
WHERE Department = 'IT';
-- View data from the temporary table
SELECT * FROM #IT_Employees;
Output:
EmployeeID |
FirstName |
LastName |
Salary |
1 |
John |
Doe |
60000 |
3 |
Mike |
Brown |
70000 |
Explanation:
This query selects employees from the IT department and inserts the data into a temporary table #IT_Employees
. The table is created dynamically and holds the data only for the duration of the session.
Example 2:
Create a Temporary Table with High-Salary Employees
We want to create a temporary table that holds data for employees with a salary greater than 55,000 from the Employees
table.
Query:
SELECT EmployeeID, FirstName, LastName, Department, Salary
INTO #HighSalaryEmployees
FROM Employees
WHERE Salary > 55000;
-- View data from the temporary table
SELECT * FROM #HighSalaryEmployees;
Output:
EmployeeID |
FirstName |
LastName |
Department |
Salary |
1 |
John |
Doe |
IT |
60000 |
3 |
Mike |
Brown |
IT |
70000 |
Explanation:
This query filters employees who earn more than 55,000 and inserts the result into a temporary table #HighSalaryEmployees
, which is session-specific
Example 3:
Create a Temporary Table and Calculate Average Salary by Department
We want to calculate the average salary by department from the Employees
table and store the result in a temporary table.
Query:
SELECT Department, AVG(Salary) AS AvgSalary
INTO #AvgSalaryByDept
FROM Employees
GROUP BY Department;
-- View data from the temporary table
SELECT * FROM #AvgSalaryByDept;
Output:
Department |
AvgSalary |
HR |
50000 |
IT |
65000 |
Marketing |
55000 |
Explanation:
This query groups employees by department and calculates the average salary. The result is inserted into a temporary table #AvgSalaryByDept
, which stores the department and average salary.
INSERT INTO SELECT
vs SELECT INTO TEMP TABLE
Feature |
INSERT INTO SELECT |
SELECT INTO TEMP TABLE |
Purpose |
Inserts data into an existing table |
Creates a new temporary table and inserts data |
Table Creation |
Target table must already exist |
Automatically creates the temporary table |
Use Case |
Used for inserting data into permanent or temp tables |
Ideal for quick, temporary storage of query results |
Syntax |
INSERT INTO table_name SELECT columns FROM ... |
SELECT columns INTO #temp_table_name FROM ... |
Performance |
Slightly slower due to pre-existing table structure |
Faster as the table is created and populated together |
Flexibility |
Can insert into existing tables (permanent or temporary) |
Limited to creating new tables on the fly |
Conclusion
The SELECT INTO TEMP TABLE
statement in SQL Server is a powerful tool for efficiently handling temporary data without affecting the main database. It simplifies the process by dynamically creating and populating temporary tables in one step, making it ideal for intermediate data operations.
Similar Reads
Insert Into Select statement in MS SQL Server
The INSERT INTO SELECT statement in SQL Server is a versatile feature that enables you to efficiently copy data from one or more tables into another table. This functionality is essential for tasks such as data transfer, backup creation, and data merging. In this article, We will learn to Insert Int
4 min read
Dynamic SQL and Temporary Tables in SQL Server
In SQL Server, creating and using Temp Tables using dynamic SQL is a good feature when we need to temporarily create tables at run time and delete automatically all within a session. They can be very useful when we need to store temporary data in a structured format and do data manipulation using Da
6 min read
Select Statement in MS SQL Server
The SELECT statement in SQL Server is a foundational SQL command used for querying and retrieving data from one or more tables within a database. This command allows users to specify which columns and rows to retrieve and apply filters to focus on specific data and perform various operations to mani
4 min read
How to Select the nth Row in a SQL Server Database Table?
In SQL Server databases, it's common to encounter scenarios where we need to retrieve a specific row, such as the nth row, from a table efficiently. Whether you're building a pagination feature for a web application or analyzing data, having the ability to select a particular row based on its positi
3 min read
SQL Server TEMPORARY TABLE
A temporary SQL table also known as a temp table is created in the database only for a specific session to store the data temporarily which is needed for a short duration of time. In this article, we are going to learn about SQL Server temporary tables, their types, how to use them, and why they are
5 min read
SQL Server SELECT INTO Statement
SQL Server is a relational database management system. SQL Server offers robust security features to protect data integrity and confidentiality. It includes authentication, authorization, encryption, and various mechanisms to secure the database environment. It is designed to scale from small applic
6 min read
SQL Server SELECT INTO @Variable
In the world of SQL Server, the SELECT INTO statement is a powerful syntax for retrieving data from one or more tables and inserting it into a new table. However, what if you want to store the result set of a SELECT query into a variable rather than a table? This is where the SELECT INTO @Variable s
6 min read
Select top in MS SQL Server
Prerequisite - Select in MS SQL Server Suppose that a user wants to extract the top students from the whole institution but has to use some complex queries to extract the data. To avoid complexity, the user can use 'Select Top'. 'Select Top' extracts the limited number of rows. This results in accur
2 min read
What is Nested Select Statement in SQL Server
SQL Server is a powerful relational database management system. Sql Server is very good with its robustness and scalability. SQL Server operates as a client-server structure, imparting centralized management and scalability for huge-scale applications and enterprise-stage solutions. It offers advanc
3 min read
PostgreSQL - Temporary Table
A PostgreSQL temporary table is a powerful tool for managing session-specific data that only needs to exist for a short duration. Temporary tables are created within a database session or transaction and are automatically dropped when the session ends, making them ideal for intermediate data storage
4 min read