SQL SELECT INTO Statement
With SQL, you can copy information from one table to another.
The SELECT INTO statement copies data from one table and inserts it into another new table.
SQL SELECT INTO Statement
The SELECT INTO statement copies data from one table and inserts it into another new table.
Note:
The MySQL database does not support the SELECT ... INTO statement, but supports INSERT INTO ... SELECT 。
Of course, you can use the following statement to copy the table structure and data:
CREATE TABLE new_table AS SELECT * FROM old_table
SQL SELECT INTO Syntax
Assume there is a table named employees with the following data:
| EmployeeID | FirstName | LastName | Age | Department |
|---|---|---|---|---|
| 1 | John | Doe | 30 | Sales |
| 2 | Jane | Smith | 25 | HR |
| 3 | Sam | Brown | 28 | IT |
To create a new table named employees_backup and insert all employees data from the table into the new table, you can use the following SQL statement:
SELECT *
INTO employees_backup
FROM employees;
After executing this statement, the new employees_backup table will contain only data for employees older than 25.
SELECT EmployeeID, FirstName, LastName, Age, Department
INTO employees_backup
FROM employees
WHERE Age > 25;
Usage notes
Table Structure:
SELECT INTOcreates a new table, and the structure of the new table is based on the selected columns and data types.- If the new table already exists,
SELECT INTOthe statement will fail. In this case, you can useINSERT INTO ... SELECTif statement.
database supports:
SELECT INTOThe statement is very common in SQL Server, but in MySQL and PostgreSQL,CREATE TABLE ... AS SELECTif statement.
Alternatives in Other Databases
MySQL and PostgreSQL
In MySQL and PostgreSQL, you can use CREATE TABLE ... AS SELECT to achieve similar functionality:
CREATE TABLE employees_backup AS
SELECT EmployeeID, FirstName, LastName, Age, Department
FROM employees
WHERE Age > 25;