Sub topic 5
Copying rows with `INSERT ... SELECT`
Assume you know basic SELECT queries, WHERE clauses, tables, columns, primary keys, and foreign keys. INSERT ... SELECT uses the rows returned by a query as the new rows for another table. It is useful for archiving, importing, and transforming existing data.
The basic pattern
The statement names the destination table and its columns first. The SELECT query then supplies values in the same order.
INSERT INTO destination_table (column_a, column_b)
SELECT source_column, another_source_column
FROM source_table
WHERE condition;The destination and source columns do not need the same names. Their values match by position:
| Destination column | Value from the query |
|---|---|
| `archive_id` | `customers.id` |
| `customer_name` | `customers.name` |
The number of selected expressions must match the number of destination columns. The data types must also be compatible.
Archiving selected rows
Suppose customers already contains customer data. Create an archive table with a compatible structure, then copy only inactive customers.
CREATE TABLE customers_archive (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255)
);
INSERT INTO customers_archive (id, name, email)
SELECT id, name, email
FROM customers
WHERE status = 'inactive';The SELECT runs first conceptually. Every row it returns becomes one row in customers_archive. The WHERE clause controls which source rows are copied.
A destination table can have columns that the query does not provide if those columns have a default value or allow NULL. For example:
CREATE TABLE customer_notes_archive (
customer_id INTEGER,
note TEXT,
archived_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO customer_notes_archive (customer_id, note)
SELECT id, 'Customer archived'
FROM customers
WHERE status = 'inactive';Here, archived_at is omitted. The database supplies its default value for each inserted row.
Transforming data while copying
The query can calculate values, rename expressions with aliases, and join other tables. It does not have to copy columns unchanged.
INSERT INTO customer_labels (customer_id, label)
SELECT id, UPPER(status)
FROM customers
WHERE status IS NOT NULL;This copies each customer ID and stores an uppercase version of its status. The destination table must already exist, and its constraints still apply to every new row.
Common errors
- A missing
WHEREclause copies every source row. - Duplicate primary keys cause the insert to fail.
- A
NOT NULLdestination column must receive a value or a default. - A foreign key value must refer to an existing parent row.
- Selecting columns in the wrong order can insert valid-looking but incorrect data.
Exercise
How would you copy only inactive customers into an archive table with columns (id, name)?
Show answer
Use INSERT INTO archive (id, name) SELECT id, name FROM customers WHERE status = 'inactive';