How-To Guide

How to Bulk Import Data into PostgreSQL

Stream rows through COPY, stage into an unlogged table, validate with SQL, then insert-select in chunks with resumable checkpoints.

On this page

  1. Introduction
  2. COPY versus batched inserts
  3. Stage, validate, promote
  4. Tune the session, not the server
  5. Chunk with checkpoints
  6. Handle constraints and errors deliberately
  7. Measure and verify the import
  8. Common pitfalls
  9. Conclusion

Introduction

Loading a million rows one INSERT at a time is a distributed systems problem disguised as a loop: every statement pays parse, round trip, WAL, and index maintenance, and the total is hours where minutes are possible. PostgreSQL’s COPY command was built for exactly this: a protocol-level stream that pushes rows as a continuous flow, avoiding per-statement overhead, typically several times faster than batched inserts and an order of magnitude faster than naive loops. But throughput is only one axis of a production import. The load must not corrupt the live table with bad rows, it must be resumable after failure at row 800,000 of a million, it should not hold locks or hammer WAL for the whole window, and it should be tunable for the maintenance window it runs in. This tutorial builds the full pipeline: COPY into an unlogged staging table, SQL validation, chunked promotion with checkpoints, session-scoped tuning, and the verification that the numbers landed.

COPY versus batched inserts

The mechanics explain the gap. A row-level INSERT is a parsed statement, a round trip, a WAL record, and index maintenance per row; a 5,000-row batched INSERT amortizes parse and round trip but still pays per-row WAL and index work in statement-sized chunks. COPY replaces the statement interface with a data stream: the client sends rows in the wire format, the server parses them in a tight loop with no statement overhead, and a single command covers the entire load. The practical guidance: use COPY whenever rows arrive loadable, from files, object storage, or a transformed stream written to a pipe; use batched INSERT, with unnest arrays or multi-row VALUES in the thousands, when application code must transform or enrich each row before the database sees it, because shipping the transformation into SQL just to use COPY is usually a loss. Drivers expose COPY natively, psycopg’s copy, pg-copy-streams, and the libpq underlying most clients, so the stream is available from every major language.

COPY staging_orders FROM STDIN WITH (FORMAT csv, HEADER true);

Stage, validate, promote

Loading directly into the live table couples ingestion speed to data quality: one malformed row aborts the transaction, and partial loads violate whatever consistency the table promises. The staging pattern decouples them. Load raw into an UNLOGGED staging table, which skips WAL for the load itself and is disposable by design, then validate with plain SQL, then promote with INSERT … SELECT.

CREATE UNLOGGED TABLE staging_orders (
 LIKE orders INCLUDING DEFAULTS
);

COPY staging_orders FROM STDIN WITH (FORMAT csv);

-- validation: quarantined rows leave the pipeline loudly
INSERT INTO import_rejects
SELECT * FROM staging_orders
WHERE external_id IS NULL OR total_cents < 0;

DELETE FROM staging_orders
WHERE external_id IS NULL OR total_cents < 0;

INSERT INTO orders (external_id, total_cents, created_at)
SELECT external_id, total_cents, created_at
FROM staging_orders
ON CONFLICT (external_id) DO UPDATE
SET total_cents = EXCLUDED.total_cents,
  created_at = EXCLUDED.created_at;

TRUNCATE staging_orders;

The upsert in the promotion makes the whole import re-runnable: a failed run that promoted half the chunks can restart and converge. The reject table turns bad data from an abort into an observable artifact with reasons, which downstream teams need more than they need the import’s raw speed.

Tune the session, not the server

Import tuning should be scoped to the import session so the server’s steady-state configuration stays untouched. Four knobs carry most of the win. synchronous_commit off: commits stop waiting for WAL flush, trading a small crash window for substantially higher commit rates, sound for re-runnable loads. maintenance_work_mem raised: index builds during promotion and post-import REINDEX use it, and the default is sized for interactive work. Index strategy: drop non-critical secondary indexes before a massive load and rebuild after, because every loaded row maintains every index, and rebuilding once at the end is cheaper than maintaining per row; keep the unique constraints you rely on, since the promotion upsert needs its conflict target. Autovacuum awareness: a bulk load leaves the table’s statistics stale, so ANALYZE the target after promotion, or the planner runs the next week of queries on fiction.

BEGIN;
SET LOCAL synchronous_commit = off;
SET LOCAL maintenance_work_mem = '512MB';
INSERT INTO orders SELECT * FROM staging_orders WHERE chunk_no = 42;
COMMIT;
ANALYZE orders;

Chunk with checkpoints

A single million-row promotion is one giant transaction: locks and snapshots held throughout, WAL spikes, and a failure at ninety percent rolls back everything. Chunked promotion with checkpoints makes the import resumable and bounds each transaction. Assign chunk numbers during staging, a serial or a computed row_number window, promote in numbered slices, and record each completed slice in an import_runs table inside the same transaction as the slice. A restart skips completed chunks and continues, and the upsert semantics make even an ambiguous chunk, one where the crash happened mid-commit, safe to re-run.

for chunk in range(total_chunks):
  if runs.is_done(import_id, chunk):
    continue
  with conn.transaction():
    conn.execute(PROMOTE_CHUNK, {'import_id': import_id, 'chunk': chunk})
    runs.mark_done(import_id, chunk)

Chunk size follows the same reasoning as batch upserts: thousands of rows, chosen by measuring lock duration, WAL volume per chunk, and recovery time against the import’s tolerance. The checkpoint table doubles as progress telemetry, so an import’s completion percentage is a query rather than a guess.

Handle constraints and errors deliberately

Constraint violations decide the import’s error philosophy. Unique violations are conflicts, not errors, and ON CONFLICT in the promotion resolves them by design, as covered. Foreign key violations are the expensive class: checking them per row during load is slow, and the two workable strategies are validating in staging with SQL joins against the referenced tables before promotion, or deferring the constraint, loading, and resolving violations after, which Postgres supports for deferrable constraints inside one transaction. CHECK and NOT NULL violations belong in staging validation, where the reject table captures rows with reasons. Type coercion, dates in surprising formats, numbers with thousands separators, deserves explicit staging columns in text form plus typed casts in the validation SQL, so a malformed value is a rejected row with a reason rather than a COPY abort mid-stream. The philosophy throughout: errors are data, handled by quarantine and reporting, not control flow that aborts a million good rows for one bad one.

Measure and verify the import

An import is not done when the command returns; it is done when the numbers agree. Row accounting: source count, staged count, promoted count, rejected count, and the identity source = promoted + rejected + skipped-must hold, exported by the job as its final act. Timing breakdown: load time, validation time, promotion time per chunk, index rebuild time, analyzed as a profile so the next import’s bottleneck is known rather than discovered. Post-load health: ANALYZE freshness, index validity for any that were rebuilt, and a smoke query against the promoted data with expected aggregates. For recurring imports, keep the profile history: a validation phase that doubles in duration month over month is telling you about source data quality drift, and a promotion phase that grows with target table size is telling you the upsert’s index maintenance now dominates, a different problem than the one the pipeline was built to solve.

SELECT (SELECT count(*) FROM staging_orders) AS staged,
    (SELECT count(*) FROM import_rejects WHERE run_id = $1) AS rejected,
    (SELECT count(*) FROM orders WHERE import_id = $1) AS promoted;

Common pitfalls

  • Loading straight into the live table. One bad row aborts or corrupts; staging decouples speed from quality.
  • Logged staging tables. UNLOGGED halves the load’s WAL cost and staging is disposable anyway.
  • Maintaining every index during load. Drop non-critical indexes, rebuild once; keep only the conflict target.
  • One giant promotion transaction. Locks and WAL for the whole window; chunk with checkpoints.
  • Forgetting ANALYZE. The planner runs on stale statistics and the next queries choose fiction.
  • Unaccounted rows. Without the source = promoted + rejected identity, silent loss goes unnoticed.

Conclusion

Bulk import performance is COPY, and bulk import correctness is staging. Stream rows with COPY into an UNLOGGED staging table, validate with SQL that quarantines bad rows with reasons, and promote with chunked, checkpointed INSERT … SELECT upserts that make the entire run atomic, re-runnable, and resumable at chunk granularity. Scope the tuning to the session, synchronous_commit off, raised maintenance memory, deferred secondary indexes, and finish with ANALYZE so the planner sees the new reality. Verify with row accounting, timing profiles, and post-load health checks, and keep the history so quality drift and growing index costs surface as numbers rather than incidents. The result is an import pipeline that is fast because of COPY and trustworthy because of everything around it.

Sources: PostgreSQL: COPY, PostgreSQL: populating a database, PostgreSQL: WAL configuration.

FAQ

Is COPY always faster than batched INSERT?
Yes for raw loading, usually by several times, because COPY is a single protocol-level stream that bypasses per-statement parsing and per-row round trips. Batched INSERT earns its place when rows need application-side transformation or validation per row.
Why load into a staging table first?
Staging isolates validation from loading: bad rows are rejected by SQL checks before promotion, the live table never sees partial data, and the whole import becomes atomic and re-runnable.
Is disabling synchronous_commit safe?
It trades a bounded crash window, at most a few hundred milliseconds of acknowledged commits, for much higher throughput. For re-runnable imports the trade is sound; set it per session and restore it after.

Related Examples