SQL SELECT INTO Statement
Learn how to use the SQL SELECT INTO
statement to create new tables and copy data from existing tables.
Overview
The SELECT INTO
statement is used to create a new table and populate it with data selected from an existing table. This is useful for creating backups, generating reports, or transforming data for analysis.
Syntax
SELECT column1, column2, ...
INTO new_table
FROM existing_table
WHERE condition;
Example 1: Basic Usage
To create a new table called EmployeesBackup
with data from the Employees
table:
SELECT *
INTO EmployeesBackup
FROM Employees;
This statement creates a new table EmployeesBackup
containing all columns and rows from the Employees
table.
Example 2: With Conditions
You can also filter the data being copied into the new table. For example, to create a backup of only the employees in the Sales
department:
SELECT *
INTO SalesEmployeesBackup
FROM Employees
WHERE Department = 'Sales';
This creates a new table SalesEmployeesBackup
containing only the records of employees in the Sales
department.
Example 3: Selecting Specific Columns
You can also choose specific columns to copy. For instance, if you want to create a table with just the employee names and email addresses:
SELECT EmployeeName, Email
INTO EmployeesContactInfo
FROM Employees;
This will create a new table called EmployeesContactInfo
with only the EmployeeName
and Email
columns.
Important Notes
- The new table is created with the same structure as the selected columns.
- If the new table already exists, an error will occur.
- In some SQL databases, you may need additional permissions to create new tables.
Conclusion
The SELECT INTO
statement is a powerful SQL feature that allows you to create new tables and copy data from existing tables efficiently. It’s particularly useful for data backup, transformation, and reporting tasks.