Skip to content

SQL INSERT INTO SELECT Statement

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, column2
FROM source_table
WHERE 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.

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 Supplier
FROM Invoices
WHERE 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 WHERE clause skipped Hartwell Lighting and Kestrel Catering, which are already on the list.
  • DISTINCT made sure a supplier with several invoices was added once.
  • SupplierID filled itself in, because the table numbers its rows automatically.
  • Service and City, which the statement did not mention, were left NULL.

To save a query’s result as a new table rather than adding to an existing one, see SELECT INTO.