Skip to content

Lesson 11 of 13 · 14m

COPY, Staging, and Bulk Loads

COPY into an UNLOGGED staging table, validate, merge with ON CONFLICT in one transaction — the bulk-load pattern that survives reruns.

Load a 5-million-row CSV with INSERT and you're asking the database to parse, plan, and execute five million statements — each row its own round of executor overhead, its own WAL record, and if the caller is an ORM in a loop with autocommit on, its own transaction and fsync. COPY exists because this is a solved problem: one command, one parse, one transaction, rows streamed straight into the heap. The same five million rows that take an hour of row-by-row inserts land in under a minute.

The wrong model: insert in a loop is a load job

The ORM-shaped model — instantiate an object per row, .save(), repeat — scales linearly in the worst way: N statements, N transactions, N fsyncs. Batching helps (INSERT INTO t VALUES (...), (...), ... a few hundred rows per statement in explicit transactions) and gets you maybe a 10x improvement. COPY gets you the whole thing because it skips the statement machinery entirely — a dedicated streaming protocol, COPY table FROM STDIN, that every real driver exposes: psql's \copy, psycopg's copy_expert, pg's native COPY over the wire.

The \copy versus COPY distinction matters operationally. Server-side COPY t FROM '/path/file.csv' reads the file as the postgres OS user on the server's filesystem, and wants superuser or pg_read_server_files. Client-side \copy reads your local file and streams it over the connection — what you actually use against RDS, Supabase, or anything remote. Mixing them up is the classic "Permission denied" confusion: the path resolves on different machines. The same trap runs in reverse on export — COPY t TO '/tmp/out.csv' writes as postgres on the server's disk, which on a managed service is a host you can't reach. The client-side form is the only one that puts bytes where you can read them.

UNLOGGED staging: skip the WAL you're about to discard

CREATE UNLOGGED TABLE staging_orders (LIKE orders INCLUDING ALL) builds a table that writes no WAL: bulk loads run noticeably faster, nothing replicates, and on crash recovery the table is simply truncated. That last property sounds like a defect until you realize staging data is transient by definition — if the box dies mid-load you were going to rerun the load anyway. The durability you skip is durability you never needed, and it's where most of the speedup lives.

The staging pattern that survives contact with production:

BEGIN;
TRUNCATE staging_orders;                       -- idempotent rerun
COPY staging_orders FROM STDIN WITH (FORMAT csv, HEADER true);
-- validate: row count, constraint violations, null business keys
INSERT INTO orders SELECT * FROM staging_orders
ON CONFLICT (order_id) DO UPDATE SET amount = EXCLUDED.amount;  -- idempotent merge
COMMIT;
ANALYZE orders;                                -- planner stats before prod reads

Three properties make it a pattern rather than a script: TRUNCATE first means a rerun after a partial failure reloads cleanly; validation happens before prod sees the data; and the merge is ON CONFLICT idempotent, so a replayed batch upserts rather than duplicating or failing.

The failure modes worth designing around

COPY aborts the whole load on the first bad row — a malformed date on line 4,000,001 undoes four million inserts, and in one transaction that's four million dead tuples for vacuum. Defenses: validate the file upstream, load through a staging table whose permissive types (text columns) absorb bad values so you can reject them in SQL, or use COPY's ON_ERROR ignore on PG17+ to skip bad rows instead of aborting.

Also: the lock story is two different locks — TRUNCATE takes ACCESS EXCLUSIVE on the staging table, the strongest Postgres has, which is fine against a table only the loader touches; COPY itself runs under ROW EXCLUSIVE, the same lock a plain INSERT holds. The contention lives in the prod merge — keep that transaction short. And ANALYZE afterward isn't optional housekeeping: you just changed the table's shape; every plan built on old statistics is now a lie.

What to actually do

  • Bulk loads: COPY (via \copy/driver COPY FROM STDIN), never row-per-statement INSERT.
  • Stage in UNLOGGED tables; TRUNCATE before reload for idempotency.
  • Validate in staging, merge to prod with ON CONFLICT DO UPDATE, all inside one transaction.
  • Always ANALYZE the target after a load — before anything reads it.
  • Dirty files: permissive staging types + SQL-side rejection, or ON_ERROR ignore on PG17.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.