// dialect comparison

Insert rows copied from another table

The most portable statement in SQL: copy rows from one table into another in a single statement.

Filed under Inserting & updating

The verdict

Use one INSERT ... SELECT per copy on every engine; row-by-row loops are slower by orders of magnitude. The one engine-specific lever worth knowing at scale is Oracle's APPEND hint.

Where they differ

INSERT ... SELECT is where the dialects agree most. The column lists and query shapes are identical; the differences are Oracle's direct-path hint for big copies, the upsert clauses that can follow the SELECT, and the date literal syntax.

How each engine writes it

SQL Server

INSERT INTO archive_orders (id, total)
SELECT id, total FROM orders
WHERE created_at < '2024-01-01';

No VALUES clause. INSERT … EXEC also lets a stored procedure's result set feed the insert.

PostgreSQL

INSERT INTO archive_orders (id, total)
SELECT id, total FROM orders
WHERE created_at < DATE '2024-01-01';

ON CONFLICT (id) DO NOTHING can follow the SELECT to skip rows already archived.

MySQL

INSERT INTO archive_orders (id, total)
SELECT id, total FROM orders
WHERE created_at < '2024-01-01';

Selecting from the target table itself is allowed; MySQL buffers the rows in a temporary table first. ON DUPLICATE KEY UPDATE can follow the SELECT.

SQLite

INSERT INTO archive_orders (id, total)
SELECT id, total FROM orders
WHERE created_at < '2024-01-01';

Identical shape. When copying in many statements, wrap them in one transaction: each separate commit waits for a disk sync.

Oracle

INSERT /*+ APPEND */ INTO archive_orders (id, total)
SELECT id, total FROM orders
WHERE created_at < DATE '2024-01-01';

APPEND loads direct-path above the high-water mark: much faster for big copies, but it locks the table against other DML, and the session can't read the table until it commits.

Questions that come up

Can the SELECT read the table being inserted into?

Yes, in all five engines. The statement sees the rows as they were before it started, so INSERT INTO t SELECT … FROM t copies each existing row once rather than looping.

What happens to generated ids in the copied rows?

If the target has an identity or serial column and you leave it out of the column list, the engine generates new ids. To keep the source ids, list the column; insert-into-identity covers the overrides SQL Server, PostgreSQL and Oracle need.

How do I copy rows across databases?

SQL Server: database.schema.table on the same instance. MySQL: database.table. SQLite: ATTACH the other file and use alias.table. PostgreSQL databases can't see each other directly; use postgres_fdw or dblink. Oracle uses a database link: table@link_name.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.