← Back to SQL, page 20

sql-0390 · Medium mid

Loading ten million rows with individual INSERT statements takes hours. How would you speed it up?

Batch the work: in PostgreSQL use COPY, which streams rows with far less overhead than separate INSERTs; otherwise use multi-row INSERTs inside large transactions. Drop or defer secondary indexes and foreign key checks during the load and rebuild them afterwards, then run ANALYZE. In SQLite, one transaction around many inserts is the biggest single gain.

Full answer

Where the time goes with row-by-row inserts: a network round trip per row, a parse per statement and, in autocommit mode, a commit (and disk flush) per row.

Improvements, roughly in order of impact:

  1. One transaction per large batch (tens of thousands of rows), so commits happen rarely.
  2. Multi-row INSERT ... VALUES (...), (...), ... or prepared statements executed in batches.
  3. PostgreSQL COPY table FROM STDIN (or \copy in psql), which is designed for bulk loads.
  4. Load into a table without secondary indexes, then CREATE INDEX once; building an index in one pass is faster than maintaining it row by row.
  5. Add foreign keys after the load (or validate them later) if the data is trusted.
  6. ANALYZE afterwards so the planner knows the new data.

For SQLite, wrapping inserts in BEGIN ... COMMIT and using executemany with one prepared statement typically turns hours into seconds. These figures are typical experience, not measured here.

Key points

  • Per-row commits dominate load time
  • Batch rows inside transactions
  • COPY is the fast path in PostgreSQL
  • Build indexes after loading
  • ANALYZE after bulk loads

Common mistakes

  • Autocommit for each row
  • Loading into a heavily indexed table

Follow-ups

  • How would you load data while the table stays online?
  • How do you handle bad rows during COPY?

Tips

  • Start with transaction batching