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 SELECTstatement, which is covered in the next chapter.
SELECT INTO SyntaxYou 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 INTOstatement 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 aCREATE TABLEfollowed by anINSERT INTO SELECT.
We will use the Customers table for our examples.
The following SQL statement creates a backup copy of the Customers table called CustomersBackup.
SELECT * INTO CustomersBackup FROM Customers;
The following SQL statement copies only the CustomerName and Country columns into a new table called CustomerContacts.
SELECT CustomerName, Country INTO CustomerContacts FROM Customers;
WHERE ClauseThe following SQL statement copies only the German customers into a new table called GermanCustomers.
SELECT * INTO GermanCustomers FROM Customers WHERE Country = 'Germany';