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.
The most portable statement in SQL: copy rows from one table into another in a single statement.
Filed under Inserting & updating
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
One round trip, many rows: the VALUES list that is a one-liner everywhere except older Oracle.
Migrating data with its original ids: three engines make you ask first, two just accept the value.
Two ways to empty a table that differ in speed, triggers, identity counters and rollback.
SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.