SQL SELECT INTO

The SQL SELECT INTO Statement

The SELECT INTO statement copies data from one table into a new table.

Warning: This command will create a new table. If you want to copy rows into an existing table, you should use the INSERT INTO SELECT statement, which is covered in the next chapter.


SELECT INTO Syntax

You can copy all columns into a new table:

SELECT *
INTO new_table_name
FROM old_table_name
WHERE condition;

Or you can copy only the columns you want into a new table:

SELECT column1, column2, ...
INTO new_table_name
FROM old_table_name
WHERE condition;

The new table will be created with the column names and types as defined in the SELECT statement.

Note: The SELECT INTO statement is not supported by all database systems. For example, Oracle uses a different syntax (CREATE TABLE new_table AS SELECT ...), and MySQL does not have a direct equivalent, often requiring a CREATE TABLE followed by an INSERT INTO SELECT.


Demo Database

We will use the Customers table for our examples.


Example 1: Create a Backup Copy

The following SQL statement creates a backup copy of the Customers table called CustomersBackup.

SELECT INTO Example

SELECT *
INTO CustomersBackup
FROM Customers;

Example 2: Copy Specific Columns

The following SQL statement copies only the CustomerName and Country columns into a new table called CustomerContacts.

SELECT INTO with Specific Columns

SELECT CustomerName, Country
INTO CustomerContacts
FROM Customers;

Example 3: Copy with a WHERE Clause

The following SQL statement copies only the German customers into a new table called GermanCustomers.

SELECT INTO with WHERE

SELECT *
INTO GermanCustomers
FROM Customers
WHERE Country = 'Germany';