How to Batch Upsert Rows in PostgreSQL
Use INSERT ON CONFLICT with a real unique target, chunk large ingest batches, return actual outcomes, and distinguish inserts from updates.
On this page
Introduction
Synchronization jobs, event ingest, periodic exports from upstream systems: all of them arrive with rows that must be inserted if new and updated if changed, without knowing which is which up front. The naive implementation, SELECT to check existence then INSERT or UPDATE per row, is two round trips per row and racy under concurrency. PostgreSQL consolidates the entire decision into one statement: INSERT … ON CONFLICT (target) DO UPDATE, the upsert, which attempts the insert and resolves any uniqueness violation by applying the update path instead. Done well it handles millions of rows per minute in a single scan. Done carelessly it produces silent data loss through DO NOTHING, partial batch failures that abort a whole ingest, or unbounded statements that exhaust work_mem and hold locks for minutes. This tutorial builds the statement correctly, defines the conflict target from business identity, uses RETURNING to report what actually happened, and chunks the work so large ingest stays fast and recoverable.
The conflict target is business identity
ON CONFLICT routes a failing row to its resolution path using a conflict target: a unique constraint or unique index on specific columns. The target must exist and must express what the business means by same row. An events table keyed by (source, external_id) needs a unique index on exactly those columns, and the ON CONFLICT clause must name them, or a different unique constraint, say the primary key, intercepts the failure instead and the update path fires against the wrong identity. Verify the target exists before writing the statement, because ON CONFLICT with an arbitrary column list errors at parse time in a way that is easy to miss in generated SQL. Composite business keys deserve attention: if the source system’s identity is (tenant_id, external_id) but rows also carry a surrogate primary key, the unique index must cover the business pair, and the surrogate key must be left to the sequence, never supplied by the ingest, or updates create duplicate surrogates instead of updating.
CREATE UNIQUE INDEX CONCURRENTLY idx_events_source_external
ON events (source, external_id);
Write the statement
The core statement passes all rows in one VALUES list or, better for parameterized drivers, through unnest over arrays, and resolves conflicts with DO UPDATE using the excluded pseudo-relation, which refers to the row that failed to insert.
INSERT INTO events (source, external_id, payload, updated_at)
SELECT * FROM unnest($1::text[], $2::text[], $3::jsonb[], $4::timestamptz[])
ON CONFLICT (source, external_id) DO UPDATE
SET payload = EXCLUDED.payload,
updated_at = EXCLUDED.updated_at
WHERE events.updated_at < EXCLUDED.updated_at
RETURNING id, source, external_id, (xmax = 0) AS inserted;
Three details carry the correctness. EXCLUDED refers to the would-be inserted row, so the update path merges arriving data, not stale data. The WHERE clause on the update makes the whole operation idempotent under re-delivery: a replayed older event fails the updated_at comparison and updates nothing, which turns at-least-once delivery into exactly-once state. And xmax = 0 in RETURNING distinguishes genuine inserts from updates, because inserted rows carry xmax zero while updated rows carry the transaction id of the replacing transaction, giving observability for free.
Report what actually happened
The RETURNING clause is the reporting surface, and ingest jobs should use it rather than counting statements sent. Returning the business key plus the inserted flag lets the job export per-row outcomes: rows inserted, rows updated, rows skipped by the staleness guard. The skipped class is the one that matters most and the one invisible without RETURNING, because a stale row simply does not appear as changed, and a job that assumes everything it sent was written drifts silently out of sync with reality. Where the job needs per-row audit, a CTE can tag outcomes before they disappear into the table.
WITH input AS (
SELECT * FROM unnest($1::text[], $2::text[], $3::jsonb[], $4::timestamptz[])
),
upserted AS (
INSERT INTO events (source, external_id, payload, updated_at)
SELECT * FROM input
ON CONFLICT (source, external_id) DO UPDATE
SET payload = EXCLUDED.payload, updated_at = EXCLUDED.updated_at
WHERE events.updated_at < EXCLUDED.updated_at
RETURNING id, (xmax = 0) AS inserted
)
SELECT count(*) FILTER (WHERE inserted) AS inserts,
count(*) FILTER (WHERE NOT inserted) AS updates
FROM upserted;
This shape returns one summary row, which is what schedulers and dashboards want, while the per-row form feeds audit logs. Both are the same statement with different projections.
Chunk for speed and recoverability
Batch size is a tuning variable with real edges. Statement parse time grows with VALUES length, though unnest keeps the statement text constant regardless of row count. Index maintenance during the insert is the heavier cost: every row touches every index on the table, and the work spills beyond work_mem into per-row lock churn as batches grow. Lock duration grows too: a single ten-million-row statement holds its locks and its snapshot for the full duration, blocking autovacuum and replication lag. The practical range is one thousand to ten thousand rows per statement, chosen by measuring throughput at several sizes against the target table. Chunking also gives recoverability: a job that processes numbered chunks, recording the last completed chunk, resumes after a failure from a known point instead of restarting the ingest, and a bad chunk, one containing a malformed row, fails alone, so the job can quarantine it and continue rather than aborting the entire run.
for chunk in chunks(rows, 5000):
cur.execute(SQL, [c.source, c.external_id, c.payload, c.updated_at])
outcomes = cur.fetchall()
mark_done(chunk.index, len(outcomes))
Failure semantics per row
A single statement is atomic: one bad row aborts the whole batch. That is usually what you want for correctness, but ingest pipelines carrying third-party data need a quarantine path, and there are two designs. The staging-table design loads the raw batch into an UNLOGGED staging table first, validates it with plain SQL, and upserts only the passing rows, moving failures to a dead-letter table with reasons. The per-row fallback design catches the batch failure and re-runs rows individually to isolate the offender, which is simple but slow and should be reserved for the rare failure, not the common path. Note what ON CONFLICT does not catch: it resolves uniqueness violations only. A row violating a CHECK constraint, a foreign key, or a NOT NULL still aborts the statement, because those are not conflicts with existing rows but invalid input. The staleness guard WHERE clause handles a third class silently, older-but-valid rows, by design, which is why the skipped count belongs in the job’s telemetry: a silently-skipping sync that nobody notices is how a year of data drift begins.
Measure the throughput
The performance story of a bulk upsert has three contributors worth measuring separately. Index maintenance: each inserted row writes to every index; dropping non-critical indexes during a massive backfill and rebuilding afterward can double throughput, at the cost of the rebuild. WAL volume: every change is logged, and synchronous_commit off for the duration of a bulk job trades a bounded crash window for substantially higher commit rates, appropriate for re-runnable ingest. Contention: concurrent upserts to the same conflict targets serialize on the same index pages; spreading arrival order, or sorting input by conflict key so the same pages hit sequentially rather than randomly, reduces page-level lock churn. Measure with EXPLAIN ANALYZE on a representative batch and with statement-level metrics in production, and record the chosen chunk size in the job configuration so the next engineer inherits a number with provenance rather than a mystery.
SET LOCAL synchronous_commit = off;
INSERT ... ON CONFLICT ... ;
RESET synchronous_commit;
Common pitfalls
- DO NOTHING on sync flows. Arriving newer rows are silently dropped; synchronization almost always wants DO UPDATE with a staleness guard.
- Conflict target mismatch. The statement routes on whatever unique constraint matches the columns; naming the wrong pair sends updates to the wrong identity.
- Supplying surrogate keys. Ingest-provided primary keys collide with the business key and create duplicates instead of updates.
- Million-row single statements. Locks, snapshots, and index work grow unbounded; chunk to thousands.
- Assuming ON CONFLICT catches bad data. CHECK and foreign-key violations still abort the batch; they are not conflicts.
- No outcome telemetry. Without RETURNING counts, a sync that silently skips stale rows drifts for months unnoticed.
Conclusion
The batch upsert is the correct primitive for every arriving-with-unknown-status flow. Ground it in a unique index that expresses business identity, name that exact conflict target in ON CONFLICT, and use DO UPDATE with EXCLUDED and a staleness guard so re-delivery and out-of-order arrival are both idempotent. Report reality with RETURNING, using xmax to separate inserts from updates and counting the silently skipped stale rows that indicate sync health. Chunk to thousands of rows for lock, memory, and recoverability reasons, quarantine bad batches through a staging design rather than per-row fallbacks, and measure index maintenance, WAL, and contention separately before tuning. A pipeline built this way survives third-party data, retries, and scale, and its telemetry tells the truth about what it wrote.
Sources: PostgreSQL: INSERT with ON CONFLICT, SQLite: UPSERT syntax, PostgreSQL: queries with WITH.
FAQ
- What is the difference between ON CONFLICT DO NOTHING and DO UPDATE?
- DO NOTHING skips conflicting rows entirely, which silently drops newer data if the arriving row is the fresher version. DO UPDATE overwrites or merges, which is what synchronization jobs almost always want; choose per flow, not by habit.
- How do I tell inserts from updates in the result?
- Return xmax from the UPDATE branch: a non-zero xmax indicates the row version was created by an update rather than an insert, because inserted rows carry xmax 0 in the current transaction. Filter on it in RETURNING.
- How large should one batch be?
- Thousands of rows, not millions. Statement parse time, work_mem for index maintenance, and lock duration all grow with batch size; 1,000 to 10,000 rows per statement is the usual sweet spot, verified by measurement.
Report a problem with this articleOpens a pre-filled issue on GitHub.