INSERT INTO SELECT in SQL: Copy Rows Between Tables Safely
INSERT INTO SELECT copies the result of a query straight into an existing table, with no loop and no export. Learn the syntax, copying chosen columns, filtering and joining, building summary tables, avoiding duplicates on a rerun, upserts, the silent column order bug, and why it was 18 times faster than inserting row by row in our test.
- INSERT INTO SELECT appends the rows returned by a query to a table that already exists.
- Always list the target columns. Without them, SQLite silently stored a customer name in an amount column in our test.
- Running the same copy twice failed on the primary key;
NOT EXISTSorINSERT OR IGNOREmake it safe to rerun. - Copying 200,000 rows took 35 ms as one statement versus 625 ms row by row from Python.
Archiving old orders, filling a reporting table, migrating data into a new schema, seeding a test database: all of these mean copying rows from one table to another. Pulling the rows into your application and inserting them one at a time works, but it is slow and fragile. INSERT INTO SELECT does the whole job inside the database in one statement.
We ran every query on SQLite 3.50.4 through Python. The syntax is standard SQL and works the same way in PostgreSQL, MySQL and SQL Server, apart from the dialect notes near the end, which we did not run on those databases.
The INSERT INTO SELECT syntax
INSERT INTO target_table (col1, col2, col3)
SELECT a, b, c
FROM source_table
WHERE condition;
The SELECT can be anything a normal query can be: filtered, joined, grouped, sorted, or built with a CTE. Its columns are matched to the target columns by position, not by name, and the target table must already exist. There is no VALUES keyword.
Our test tables
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer TEXT, amount REAL, status TEXT, created TEXT);
CREATE TABLE archive (id INTEGER PRIMARY KEY, customer TEXT, amount REAL, status TEXT, created TEXT);
CREATE TABLE summary (customer TEXT PRIMARY KEY, orders INT, total REAL);
CREATE TABLE customers (name TEXT PRIMARY KEY, country TEXT);
-- 1,000 random orders across five customers in 2026
Copy all columns
INSERT INTO archive
SELECT * FROM orders WHERE created < '2026-06-01';
-- archived rows 456
When the two tables have identical columns in identical order, SELECT * works. The cursor’s row count reported 456 rows copied, and SELECT COUNT(*) FROM archive agreed. This is convenient for archive tables that mirror the live one, but it breaks the moment someone adds a column to either table, so prefer explicit columns in anything that lives longer than a one-off script.
Copy chosen columns, with defaults
CREATE TABLE t3 (customer TEXT, amount REAL, note TEXT DEFAULT 'copied');
INSERT INTO t3 (customer, amount)
SELECT customer, amount FROM orders LIMIT 1;
-- [('Chen', 474.45, 'copied')]
Name the target columns, then select the same number of values in the same order. Columns you leave out get their DEFAULT, or NULL if they have none; a NOT NULL column without a default would make the insert fail. Our SQL constraints guide covers defaults and NOT NULL.
Copy rows with a JOIN
CREATE TABLE in_orders (id INTEGER, customer TEXT, amount REAL);
INSERT INTO in_orders
SELECT o.id, o.customer, o.amount
FROM orders o
JOIN customers c ON c.name = o.customer
WHERE c.country = 'IN';
-- join copy 399
The SELECT can combine tables, so you can copy only the orders from customers in India without first exporting customer lists. Any join type works; see our SQL joins guide for the differences.
Build a summary table from GROUP BY
INSERT INTO summary (customer, orders, total)
SELECT customer, COUNT(*), ROUND(SUM(amount), 2)
FROM orders WHERE status = 'paid'
GROUP BY customer;
-- [('Ben', 108, 27581.63), ('Dara', 109, 27291.61), ('Chen', 99, 24520.15),
-- ('Asha', 96, 24236.96), ('Eli', 93, 23611.36)]
Aggregated results can be stored, which is how many reporting and dashboard tables are built: run an expensive GROUP BY once at night, then read the small summary table all day.
The rerun problem
INSERT INTO archive SELECT * FROM orders WHERE created < '2026-06-01';
-- second run: UNIQUE constraint failed: archive.id
INSERT INTO SELECT always appends. Running the same archive job twice tried to insert the same 456 ids again, and the primary key stopped it. That error is the lucky case. If the archive table had no primary key, the second run would have silently doubled every row, and every report built on it would be wrong.
Skip rows that are already there
INSERT INTO archive
SELECT * FROM orders o
WHERE created < '2026-07-01'
AND NOT EXISTS (SELECT 1 FROM archive a WHERE a.id = o.id);
-- not exists added 93
INSERT OR IGNORE INTO archive
SELECT * FROM orders WHERE created < '2026-08-01';
-- or ignore added 97
Extending the archive to June added only the 93 new rows, because NOT EXISTS filtered out ids already archived. This works in every database and is easy to read. INSERT OR IGNORE is SQLite’s shortcut that skips any row violating a unique constraint; MySQL writes it INSERT IGNORE, and PostgreSQL uses ON CONFLICT DO NOTHING. Be careful: ignore-style options skip all constraint errors, not just the duplicate you expected. For the trade-offs between EXISTS and IN, see our EXISTS vs IN guide.
Upsert from a SELECT
INSERT INTO summary (customer, orders, total)
SELECT customer, COUNT(*), ROUND(SUM(amount), 2)
FROM orders WHERE true
GROUP BY customer
ON CONFLICT(customer) DO UPDATE SET
orders = excluded.orders, total = excluded.total;
-- upsert touched 5
To refresh a summary instead of failing, combine INSERT INTO SELECT with an upsert: new customers are inserted, existing ones updated, using excluded to refer to the incoming values. One SQLite quirk cost us a run: without the WHERE true, the parser read ON CONFLICT as part of the SELECT and reported near "do": syntax error. The SQLite documentation describes this ambiguity; adding any WHERE clause resolves it. More on this pattern in our SQL upsert guide.
The silent column order bug
CREATE TABLE t2 (amount REAL, customer TEXT);
INSERT INTO t2 SELECT customer, amount FROM orders LIMIT 2;
SELECT * FROM t2;
-- [('Chen', '474.45'), ('Asha', '412.42')]
Columns are matched by position, so selecting customer, amount into a table defined as amount, customer put names into the amount column and amounts into the customer column. SQLite’s flexible typing accepted it without a single warning. PostgreSQL and SQL Server would usually reject the text in a numeric column, but if both columns were the same type, every database would accept swapped data silently. The only reliable defence is to list the target columns every time.
Tip: write the target column list and the SELECT list on matching lines, one column per line, so a reviewer can check them side by side.
CREATE TABLE AS SELECT: when the table does not exist yet
CREATE TABLE copy_as AS SELECT * FROM orders WHERE 0;
-- CREATE TABLE copy_as(
-- id INT, customer TEXT, amount REAL, status TEXT, created TEXT )
If the target does not exist, CREATE TABLE ... AS SELECT (SQL Server: SELECT ... INTO new_table) creates it from the query. WHERE 0 copies the structure with no rows. Look closely at the result, though: the original id INTEGER PRIMARY KEY became plain id INT. The primary key, constraints, defaults and indexes were not copied. For a real table, create it properly first and then use INSERT INTO SELECT.
Moving rows safely
BEGIN;
INSERT INTO archive (id, customer, amount, status, created)
SELECT id, customer, amount, status, created FROM orders WHERE created < '2026-06-01';
DELETE FROM orders WHERE created < '2026-06-01';
COMMIT;
There is no MOVE statement. Copy, then delete with exactly the same condition, inside one transaction so a failure halfway leaves both tables unchanged. If new matching rows can arrive between the two statements, filter the DELETE by the ids you copied instead of repeating the date condition.
Speed: one statement vs a loop
| Method, 200,000 rows | Time |
|---|---|
One INSERT INTO dst SELECT * FROM src |
35 ms |
| Fetch all rows in Python, insert each one | 625 ms |
The single statement was about 18 times faster, and that was with an in-memory database on the same machine. With a network between the application and the database, a row-by-row loop pays a round trip for every insert and the gap grows much larger. Keep set-based work in SQL; our SQL query optimization guide has more examples.
Dialect notes
- MySQL:
INSERT IGNOREandON DUPLICATE KEY UPDATE; you can also copy across databases withdb_name.table. - PostgreSQL:
ON CONFLICT (col) DO NOTHING / DO UPDATE, plusRETURNINGto see inserted rows. - SQL Server:
SELECT ... INTO new_tablecreates a table; useMERGEorNOT EXISTSfor upserts. Large inserts fill the transaction log, so batch them. - SQLite:
INSERT OR IGNORE,ON CONFLICTwith theWHERErule above, andRETURNINGsince version 3.35.
Final thoughts
INSERT INTO SELECT is the fastest and simplest way to copy data inside a database. List the target columns every time, decide what a rerun should do before the first run, use NOT EXISTS or an upsert to make jobs repeatable, and wrap copy-then-delete in a transaction. Those habits prevent the swapped columns, doubled rows and half-moved data that turn a quick copy into a data-quality incident.
Frequently asked questions
What does INSERT INTO SELECT do?
It runs a SELECT query and inserts every row it returns into an existing table in one statement, matching columns by position. Existing rows in the target are kept.
Does the target table need to exist?
Yes. To create a new table from a query, use CREATE TABLE AS SELECT, or SELECT INTO in SQL Server, but note that keys, constraints and indexes are not copied.
How do I avoid inserting duplicate rows?
Add a NOT EXISTS condition that checks the target for each row, or rely on a unique key with an ignore or ON CONFLICT DO NOTHING option, depending on your database.
Do the column names have to match?
No. Columns are matched by position, not name. That is why you should always list the target columns explicitly, so swapped columns cannot slip through.
Is INSERT INTO SELECT faster than inserting rows in a loop?
Much faster. In our SQLite test, copying 200,000 rows took 35 ms as one statement and 625 ms when inserting each row from Python.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.