INSERT INTO SELECT: copy and transform rows
Overview
INSERT INTO SELECT copies rows produced by a query into an existing target. It can filter, join and transform source data without fetching each row into application code. Here, ins_stage contains incoming products and ins_item is the validated destination. Load the V51 fixture in a disposable database before each independent example.
First example
BEGIN;INSERT INTO ins_item(sku,price_cents,quantity)SELECT sku,price_cents,quantity FROM ins_stage WHERE approved=1;SELECT sku,quantity FROM ins_item WHERE sku IN ('S1','S2','S3') ORDER BY sku;ROLLBACK;Observed SQLite result (rows in JSON):
[ [ "S1", 3 ], [ "S2", 5 ]]How it works
The SELECT expressions map positionally to the explicit target columns, not by their aliases. Preview the exact SELECT first. The first example copies only approved staged records; the second groups a separate receipt table to create one summary row per SKU. Source duplicates or pre-existing target keys can still cause failure. NOT EXISTS can prefilter existing keys for a report or single-writer load, but does not by itself solve concurrent insert races. A SELECT producing zero rows inserts zero rows. The target schema and constraints remain authoritative; this differs from CREATE TABLE AS SELECT.
Practical example
BEGIN;INSERT INTO ins_summary(sku,total_qty)SELECT sku,SUM(quantity) FROM ins_receipt GROUP BY sku;SELECT sku,total_qty FROM ins_summary ORDER BY sku;ROLLBACK;Observed SQLite result (rows in JSON):
[ [ "A1", 5 ], [ "A2", 4 ]]Practice and mistakes
Practice: preview approved staged records whose price is at least 200 cents, then insert only those and check the new SKU list. Expect S2 only with the initial fixture. Roll back. Mistake: copying with SELECT * when source and target have different layouts. Name the source expressions and destination columns.