Bulk Inserts

Difficulty: Beginner

Question

How would you efficiently insert one million rows into a relational database?

Answer

Avoid one-row-per-statement, one-transaction-per-row inserts. Use the database's bulk loader (COPY in PostgreSQL, LOAD DATA INFILE in MySQL), or failing that, multi-row INSERT statements sent in batches inside a modest number of transactions. For very large initial loads, create secondary indexes and foreign keys after the data is in, then run ANALYZE.

Why naive inserts are slow

Inserting a million rows one at a time with autocommit means a million:

  • Network round trips between app and database.
  • Statement parses and plans, unless you use prepared statements.
  • Commits, each of which waits for the write-ahead log (WAL or redo log) to be flushed to disk.
  • Index updates, one per index per row.

The commit flushes are usually the worst part. Grouping rows into fewer transactions removes most of them.

Techniques, roughly from biggest to smallest win

  1. Bulk load command: PostgreSQL COPY table FROM STDIN (or \copy from psql for client-side files) streams rows with minimal per-row overhead. MySQL has LOAD DATA [LOCAL] INFILE. These are typically the fastest option by a wide margin.
  2. Multi-row INSERT: INSERT INTO t VALUES (...), (...), ... with a few hundred to a few thousand rows per statement. PostgreSQL limits a single statement to 65,535 bind parameters, so a 10-column table can carry at most about 6,500 rows per statement.
  3. Driver batching: JDBC addBatch()/executeBatch() with reWriteBatchedInserts=true (PostgreSQL) or rewriteBatchedStatements=true (MySQL) so the driver sends multi-row statements.
  4. Batch commits: commit every 10,000 to 100,000 rows rather than once per row or once for all million. One giant transaction works but holds locks longer, bloats if it fails, and makes retries all-or-nothing.
  5. Drop and recreate indexes and FKs on large initial loads. Building an index once over sorted data is cheaper than maintaining it row by row. Raise maintenance_work_mem during the rebuild.
  6. Run ANALYZE afterward so the planner has fresh statistics.

Optional speedups with trade-offs

OptionEffectRisk
UNLOGGED table (PostgreSQL)Skips WALTable truncated after a crash; not replicated
synchronous_commit = off for the sessionCommits do not wait for flushRecent commits can be lost on crash
SET foreign_key_checks = 0 (MySQL)Skips FK checksInvalid references can slip in
Load into a staging table, then INSERT ... SELECTClean and validate before touching live dataExtra disk space

Real-world practice

A nightly job loading bank settlement files or a UPI reconciliation report usually streams the CSV into a staging table with COPY, validates and deduplicates with SQL, then merges into the main table with INSERT ... ON CONFLICT. On a live production table, prefer batched inserts with indexes kept in place, and throttle so replicas do not lag.

Fast, safe bulk load pipeline. Stage, validate, then merge so the live table only sees clean data.
  1. COPY file into staging table: Streaming load with no indexes on staging.
  2. Validate and deduplicate: SQL checks on types, ranges and duplicates.
  3. Merge in batches: INSERT ... SELECT with ON CONFLICT handling.
  4. Build or refresh indexes: Create indexes after load for initial loads.
  5. Run ANALYZE: Give the planner fresh statistics.

Code examples

PostgreSQL COPY into a staging table

CREATE UNLOGGED TABLE settlements_stage (LIKE settlements INCLUDING DEFAULTS);

-- From psql on the client machine (reads a local file)
\copy settlements_stage FROM 'settlements_2026_10_11.csv' WITH (FORMAT csv, HEADER true)

-- Merge only clean, new rows into the real table
INSERT INTO settlements
SELECT * FROM settlements_stage
WHERE amount_paise > 0
ON CONFLICT (utr_number) DO NOTHING;

ANALYZE settlements;
DROP TABLE settlements_stage;

COPY loads the file quickly into an unlogged staging table, and the merge step enforces validation and idempotency.

Batched multi-row inserts from Python (psycopg 3)

import psycopg

rows = generate_rows()  # iterable of (user_id, event, ts) tuples

with psycopg.connect("dbname=app") as conn:
    with conn.cursor() as cur:
        # COPY from Python: fastest path without a file on disk
        with cur.copy("COPY events (user_id, event, ts) FROM STDIN") as copy:
            for row in rows:
                copy.write_row(row)
    # leaving the connection block commits once

psycopg 3 exposes COPY directly, so you stream rows from application code with far less overhead than individual INSERTs.

Key points

  • Use COPY (PostgreSQL) or LOAD DATA INFILE (MySQL) for bulk loads.
  • Otherwise use multi-row INSERTs with driver batching and prepared statements.
  • Commit in batches, not per row; per-row commits pay a log flush each time.
  • For initial loads, create indexes and FKs after loading, then ANALYZE.
  • UNLOGGED tables and synchronous_commit off trade durability for speed.

Common follow-up questions

  • Why is one transaction per row so much slower than batching?
  • What are the risks of disabling foreign key checks during a load?
  • How would you make a bulk import idempotent if it fails halfway?
  • How do you bulk load without causing replication lag on replicas?

Interview tips

  • Explain why naive inserts are slow (round trips, commits, index maintenance) before listing fixes.
  • Name the actual commands (COPY, LOAD DATA INFILE, reWriteBatchedInserts); specifics signal real experience.
  • Separate initial empty-table loads from loads into a live production table; the right approach differs.

Concepts covered

Bulk Loading, COPY, Batch Insert, Transaction Overhead, Index Rebuild

More Database Design questions