SELECT INTO runs a query and saves the result as a brand-new table. The new table takes its columns, and their types, from the query.
SELECT column1, column2INTO new_tableFROM old_tableWHERE condition;The example uses the Invoices table from the example database.
Saving a result as a table
Section titled “Saving a result as a table”To keep a snapshot of the unpaid invoices:
SELECT InvoiceID, Supplier, AmountINTO UnpaidInvoicesFROM InvoicesWHERE PaidDate IS NULL;UnpaidInvoices is created with three columns and two rows:
| InvoiceID | Supplier | Amount |
|---|---|---|
| 1003 | Ashby Camera Hire | 41,250.00 |
| 1004 | Kestrel Catering | 2,940.00 |
The new table is a copy, not a live view. Paying an invoice later changes Invoices but not UnpaidInvoices; for a saved query that stays up to date, use a view.
The other spelling
Section titled “The other spelling”SELECT INTO is how SQL Server and Microsoft Access do this. PostgreSQL, MySQL, Oracle and SQLite use CREATE TABLE … AS instead:
CREATE TABLE UnpaidInvoices ASSELECT InvoiceID, Supplier, AmountFROM InvoicesWHERE PaidDate IS NULL;Useful variations
Section titled “Useful variations”- A full copy before risky work:
SELECT * INTO InvoicesBackup FROM Invoices; - An empty table with the same columns: add a condition that no row can meet, as in
SELECT * INTO InvoicesTemplate FROM Invoices WHERE 1 = 0; - A table built from a join: any query works, including one that joins several tables, and an alias names each new column.
To add rows to a table that already exists, use INSERT INTO SELECT instead.