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:
- One transaction per large batch (tens of thousands of rows), so commits happen rarely.
- Multi-row
INSERT ... VALUES (...), (...), ...or prepared statements executed in batches. - PostgreSQL
COPY table FROM STDIN(or\copyin psql), which is designed for bulk loads. - Load into a table without secondary indexes, then
CREATE INDEXonce; building an index in one pass is faster than maintaining it row by row. - Add foreign keys after the load (or validate them later) if the data is trusted.
ANALYZEafterwards 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