Sub topic 5
Copying rows with INSERT ... SELECT
This chapter assumes you can write a SELECT with a WHERE clause, you know what a primary key is, and you have already used a column list in a basic INSERT. It uses the customers table from earlier chapters and adds an archive table.
What INSERT ... SELECT does
A plain INSERT ... VALUES takes literal values that you type. INSERT ... SELECT takes its rows from a query instead. The database runs the SELECT, then inserts every row it returns into the target table. One statement can copy zero rows, one row, or millions.
Typical uses:
- Archiving rows before you delete them.
- Building a summary or reporting table.
- Seeding a test table from production-shaped data.
- Moving rows between staging and live tables.
The general shape is:
INSERT INTO target_table (col_a, col_b, col_c)
SELECT expr_1, expr_2, expr_3
FROM source_table
WHERE condition;There is no VALUES keyword. The SELECT takes its place.
A worked example
Create an archive table with the same core columns as customers, then copy the inactive customers into it.
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 archive table has no status column and no UNIQUE constraint on email. It only holds what you chose to keep. The source table is not changed. INSERT ... SELECT copies rows. It does not move them.
After the statement, check the result:
SELECT COUNT(*) FROM customers_archive;Compare that count with SELECT COUNT(*) FROM customers WHERE status = 'inactive';. They should match.
Columns match by position, not by name
The database pairs the target column list with the select list by position. The first listed column receives the first selected expression, the second receives the second, and so on. Column names in the SELECT play no part.
This is the most common source of silent mistakes. The statement below runs without error if the types are compatible, but it puts emails into the name column and names into the email column:
INSERT INTO customers_archive (id, name, email)
SELECT id, email, name
FROM customers
WHERE status = 'inactive';The database cannot know that this is wrong. Two rules prevent the problem:
- Always write the target column list. Without it, the SELECT must supply every column in table order, and the statement breaks when someone adds a column.
- Write the select list in the same order as the target list, and read the two lists side by side before you run the statement.
The counts must also agree. If the target list has three columns and the SELECT returns two, the statement fails with an error.
Using expressions, literals, and joins in the SELECT
The select list can contain anything a normal SELECT allows. That includes literals, functions, and calculations:
CREATE TABLE customer_report (
id INTEGER PRIMARY KEY,
display_name VARCHAR(120) NOT NULL,
email_domain VARCHAR(255),
source VARCHAR(20) NOT NULL
);
INSERT INTO customer_report (id, display_name, email_domain, source)
SELECT id,
UPPER(name),
SUBSTRING(email FROM POSITION('@' IN email) + 1),
'migration'
FROM customers
WHERE email IS NOT NULL;The SUBSTRING ... FROM and POSITION ... IN forms are standard SQL and work in PostgreSQL. MySQL, SQL Server, and SQLite use other string functions, such as SUBSTR and INSTR in SQLite. Check your dialect for the string functions.
The literal 'migration' shows a useful trick: it fills a column with a constant for every copied row.
The SELECT can also join tables, filter with subqueries, group, and aggregate. Whatever rows it produces are what get inserted:
CREATE TABLE customer_order_totals (
customer_id INTEGER PRIMARY KEY,
order_count INTEGER NOT NULL,
total_spent NUMERIC(12, 2) NOT NULL
);
INSERT INTO customer_order_totals (customer_id, order_count, total_spent)
SELECT customer_id, COUNT(*), SUM(total)
FROM orders
GROUP BY customer_id;Defaults and omitted columns
Columns that you leave out of the target list behave as they do in a normal INSERT. They receive their DEFAULT value, or NULL if there is no default. If such a column is NOT NULL and has no default, the statement fails.
In the archive example, customers_archive has only three columns, so nothing is omitted. If you added a copied_at column with a default of the current timestamp, you could leave it out of both lists and every copied row would get the time of the copy.
Types and conversions
Each selected value must fit the type of its target column. Many databases convert compatible types for you, for example an integer into a NUMERIC column. Others reject mismatches, and some silently truncate. A VARCHAR(255) value inserted into a VARCHAR(100) column is an error in PostgreSQL if the text is too long. MySQL in a permissive SQL mode may truncate it with only a warning. When the source column is wider than the target column, check the longest value first or convert explicitly with CAST.
Constraints still apply
Every copied row is checked against the target's constraints, exactly like a row from VALUES.
- A duplicate primary key or UNIQUE value fails the statement.
- A NULL going into a NOT NULL column fails the statement.
- A foreign key value with no matching parent fails the statement.
The statement is all or nothing. If row 9,999 out of 10,000 violates a constraint, the database rejects the statement and none of the rows are inserted. This is useful, because you never end up with a half-copied table. It also means one bad row can block the whole copy.
A common cause is running the same archive statement twice. The second run tries to insert ids that already exist and fails on the primary key. You can avoid duplicates by excluding rows that are already in the target:
INSERT INTO customers_archive (id, name, email)
SELECT c.id, c.name, c.email
FROM customers AS c
WHERE c.status = 'inactive'
AND NOT EXISTS (
SELECT 1
FROM customers_archive AS a
WHERE a.id = c.id
);NOT EXISTS keeps only the source rows that have no match in the archive. This version is safe to repeat.
Reading and writing the same table
You can insert into a table and select from that same table, for example to duplicate rows with new keys. Behavior differs by dialect. PostgreSQL and SQL Server evaluate the SELECT against the table as it was before the statement. MySQL has restrictions on selecting from the target table in some forms of INSERT. If you hit an error, copy the rows into a separate staging table first.
Preview before you insert
The SELECT part of the statement works on its own. Run it first:
SELECT id, name, email
FROM customers
WHERE status = 'inactive';Check the row count and a few rows. Then add the INSERT INTO ... (columns) line above it. This is the same preview habit you use before UPDATE and DELETE. For a large copy, wrap the INSERT in a transaction so you can inspect the target and roll back if the counts are wrong.
Archiving with a copy and a delete
A common pattern is to copy rows to an archive and then delete them from the source. Do both in one transaction with the same WHERE condition, so you never lose rows if the second step fails:
BEGIN;
INSERT INTO customers_archive (id, name, email)
SELECT id, name, email
FROM customers
WHERE status = 'inactive';
DELETE FROM customers
WHERE status = 'inactive';
COMMIT;In SQL Server, write BEGIN TRANSACTION. Be aware that deleting a customer who still has orders fails because of the foreign key from orders, so this pattern needs the parent-row handling covered in a later chapter.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Column count mismatch error | Target list and select list differ in length | Make both lists the same length |
| Wrong data in the right columns | Select list order differs from the target list | Align the two lists by position |
| Duplicate key error | Rows already exist in the target, or the source has repeated keys | Filter with `NOT EXISTS`, or use an upsert |
| NOT NULL violation | The SELECT returns NULL for a required column | Use `COALESCE` or filter those rows out |
| Zero rows inserted, no error | The SELECT matched nothing | Run the SELECT alone and check the WHERE clause |
Exercise
You run INSERT INTO customers_archive (id, name, email) SELECT id, email, name FROM customers WHERE status = 'inactive'; The statement succeeds, but the archive looks wrong. What happened, and how do you prevent it?
Show answer
The database matches columns by position, so the email values went into the name column and the names went into the email column. Types were compatible, so no error was raised. Prevent it by writing the select list in the same order as the target column list and by running the SELECT alone first to check the output.
Exercise
The archive statement copies 5,000 inactive customers, but row 3,200 has an id that already exists in customers_archive. How many rows are inserted, and how can you make the statement safe to run again?
Show answer
None are inserted. The primary key violation makes the whole statement fail. To make it repeatable, add AND NOT EXISTS (SELECT 1 FROM customers_archive a WHERE a.id = customers.id) to the WHERE clause so rows already archived are skipped.