Difficulty: Beginner
How would you efficiently insert one million rows into a relational database?
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.
Inserting a million rows one at a time with autocommit means a million:
The commit flushes are usually the worst part. Grouping rows into fewer transactions removes most of them.
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.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.addBatch()/executeBatch() with reWriteBatchedInserts=true (PostgreSQL) or rewriteBatchedStatements=true (MySQL) so the driver sends multi-row statements.maintenance_work_mem during the rebuild.ANALYZE afterward so the planner has fresh statistics.| Option | Effect | Risk |
|---|---|---|
UNLOGGED table (PostgreSQL) | Skips WAL | Table truncated after a crash; not replicated |
synchronous_commit = off for the session | Commits do not wait for flush | Recent commits can be lost on crash |
SET foreign_key_checks = 0 (MySQL) | Skips FK checks | Invalid references can slip in |
Load into a staging table, then INSERT ... SELECT | Clean and validate before touching live data | Extra disk space |
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.
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.
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.
Bulk Loading, COPY, Batch Insert, Transaction Overhead, Index Rebuild