SQL SELECT INTO Statement
The SELECT INTO
statement is used to create a new table from an existing one by copying the existing table's columns and data.
When creating a table using the SELECT INTO
statement, the new table will be populated with data from the existing table.
Syntax
The syntax for the SELECT INTO
statement can be given as follows:
To copy all columns into a new table, use the following syntax:
SELECT * INTO new_table_name [ IN external_database ] FROM old_table_name WHERE condition
To copy only some columns into a new table, use the following syntax:
SELECT column1, column2, ... columnN FROM new_table_name [ IN external_database ] FROM old_table_name WHERE condition;
Parameters:
colmun1, column2, ...columnN
: The name of columns that you want to select.new_table_name
: The name of the new table that will be created with theSELECT INTO
statement (new_table_name must not already exist).old_table_name
: The name of the existing table you want to retrieve data from.IN external_database
: Optional. If you want to create the new table in another database.
Demo Table
Let us suppose that we have a table called "Employee" with the following data:
emp_no | name | birth_date | hire_date | salary | dept_name |
---|---|---|---|---|---|
1001 | James Smith | 1991-10-23 | 2010-05-13 | 6600 | Customer Service |
1002 | Maria Martinez | 1993-06-13 | 2018-10-08 | 9000 | Development |
1003 | Andrew Rodriguez | 1994-10-25 | 2019-01-23 | 9500 | Finance |
1004 | Robert Hernandez | 1995-09-07 | 2019-09-08 | 9600 | Development |
1005 | Donna Williams | 1996-03-15 | 2012-06-06 | 7400 | Finance |
1006 | James Johnson | 2001-04-30 | 2014-02-18 | 8000 | Marketing |
1007 | Stephanie Miller | 1998-01-17 | 2009-12-12 | 8500 | Human Resources |
1008 | Nelson Lopez | 1999-05-26 | 2010-10-06 | 7300 | Marketing |
SQL SELECT INTO Examples
The following SQL statement will create a new backup copy of the "Employee" table:
SELECT *
INTO employee_backup_01
FROM employee;
If you want to copy a table into a new table in another database, you can use the IN
clause with the SELECT INTO
statement as follows:
SELECT *
INTO employee_backup_01 IN 'another_database.db'
FROM employee;
The following SQL statement will copy just a few columns (first_name, last_name, salary) of the "Employee" table:
SELECT first_name, last_name, salary
INTO employee_backup_01
FROM employee;
The following SQL statement will copy only employees whose working in the "Development" department:
SELECT *
INTO employee_development_dept
FROM employee
WHERE dept_name = 'Development';
The following SQL statement will create a new empty table using the structure of an already existing table:
SELECT *
INTO employee_empty
FROM employee
WHERE 2 = 3;
Note: The
SELECT INTO
statement can also be used to create a new empty table using the structure of an already existing table by adding a WHERE with the condition that will always be FALSE to return no data.