Bulk insertion: batches, staging and transactions
Overview
Bulk insertion loads many rows efficiently by reducing per-row round trips and transaction overhead. Use multi-row VALUES or a driver batch API for moderate inputs; for larger files, consider native loading tools. A staging table is an intermediate landing area for checking rows before inserting into the destination. The V51 fixture is tiny for learning, not a benchmark. Run each example independently with foreign keys enabled.
First example
BEGIN;INSERT INTO ins_item(sku,price_cents,quantity) VALUES ('B1',10,1),('B2',20,2);INSERT INTO ins_item(sku,price_cents,quantity) VALUES ('B3',30,3),('B4',40,4);SELECT COUNT(*),SUM(quantity) FROM ins_item WHERE sku IN ('B1','B2','B3','B4');ROLLBACK;Observed SQLite result (rows in JSON):
[ [ 4, 10 ]]How it works
The first example groups two INSERT statements into a transaction; the second loads approved staged rows and reconciles the count and total quantity. In real work commit only after validation; these examples roll back deliberately. Use explicit error handling, prepared statements and bound parameters. Batch sizes depend on driver parameter limits, statement size, locks, memory and recovery needs. Committing after every batch permits partial loads; one transaction can make the whole load atomic if failures lead to rollback. PostgreSQL COPY FROM STDIN streams input from a client; SQLite does not implement that SQL command. Native file loaders require a verified client workflow and permissions. Do not disable integrity rules just to load faster.
Practical example
BEGIN;INSERT INTO ins_item(sku,price_cents,quantity)SELECT sku,price_cents,quantity FROM ins_stage WHERE approved=1;SELECT COUNT(*),SUM(quantity) FROM ins_item WHERE sku IN ('S1','S2','S3');ROLLBACK;Observed SQLite result (rows in JSON):
[ [ 2, 8 ]]Practice and mistakes
Practice: split four new products into two multi-row statements, then compare the expected count and sum against the destination before rollback. Next, deliberately repeat a SKU in the second batch; handle the error by rolling back the whole transaction. Verify no new rows remain. For repeated imports, define a duplicate policy and a load identifier; do not assume retries are automatically idempotent.