INSERT INTO SELECT adds rows to a table that already exists, taking them from a query instead of typing them out. The rows already in the table stay as they are.
INSERT INTO target_table (column1, column2)SELECT column1, column2FROM source_tableWHERE condition;The query must return as many columns as the list names, in the same order and of compatible types.
The example uses the Invoices and Suppliers tables from the example database.
Adding missing suppliers
Section titled “Adding missing suppliers”Ashby Camera Hire has invoiced the company but is not on the approved supplier list. To add every invoicing supplier that is missing from the list:
INSERT INTO Suppliers (Name)SELECT DISTINCT SupplierFROM InvoicesWHERE Supplier NOT IN (SELECT Name FROM Suppliers);Suppliers gains one row:
| SupplierID | Name | Service | City |
|---|---|---|---|
| 1 | Hartwell Lighting | Lighting | Manchester |
| 2 | Kestrel Catering | Catering | Bristol |
| 3 | Northgate Transport | Transport | Leeds |
| 4 | Ashby Camera Hire |
Several things happened here:
- The
WHEREclause skipped Hartwell Lighting and Kestrel Catering, which are already on the list. DISTINCTmade sure a supplier with several invoices was added once.SupplierIDfilled itself in, because the table numbers its rows automatically.ServiceandCity, which the statement did not mention, were leftNULL.
To save a query’s result as a new table rather than adding to an existing one, see SELECT INTO.