Full answer
Where the time usually goes, and the fix for each:
- Per-row round trips: single INSERTs over the network are slow; COPY (or psycopg's copy support, or \copy from psql) streams rows in one operation and is typically an order of magnitude faster.
- Index maintenance: each index is updated for every row. Load into a staging table without indexes, or drop and recreate secondary indexes around a full reload; building an index once is much cheaper.
- Constraints and triggers: foreign key checks and triggers fire per row. Validate in bulk with set-based queries on the staging table, then insert into the target.
- WAL volume: an UNLOGGED staging table skips WAL (and is emptied after a crash, which is fine if the file can be reloaded). Loading into a table created or truncated in the same transaction with wal_level = minimal also avoids WAL, but that setting is unusual on servers with replicas.
- Memory: raise maintenance_work_mem for the session that builds indexes.
- Statistics: run ANALYZE after loading so the first queries plan well.
Example flow (not run here): COPY into staging, delete or flag invalid rows with reports, INSERT ... SELECT or MERGE into the target in batches, ANALYZE, then swap or refresh dependent summaries. Measure each step's time so the next optimisation targets the real bottleneck.
Key points
- COPY beats row-by-row inserts
- Load into staging, then merge
- Build indexes after the load
- Unlogged staging tables cut WAL
- ANALYZE afterwards
Common mistakes
- Inserting rows one at a time from application code
- Keeping every index and trigger active during a full reload
Follow-ups
- How would you load files in parallel safely?
- How do you handle bad rows without failing the whole load?
Tips
- Name COPY first