Practical technical guides / Core IT: databases

A Batch Upsert With a Repeated Key Fails: ON CONFLICT DO UPDATE Cannot Touch a Row Twice

On PostgreSQL 18.4 a batch that repeats a key fails with SQLSTATE 21000 in ON CONFLICT DO UPDATE and MERGE. Decide what duplicates mean, then sum or keep the last.

By Sandeep Belgavi · Published 2026-11-27

On PostgreSQL 18.4 a batch that repeats a key fails with SQLSTATE 21000 in ON CONFLICT DO UPDATE and MERGE. Decide what duplicates mean, then sum or keep the last.

The failure

A nightly feed for Belgavi's Book Store sends stock adjustments: ISBN, quantity received and which supplier feed it came from. The loader batches rows into one multi-row INSERT ... ON CONFLICT (isbn) DO UPDATE that adds the received quantity to the stored one. It works for weeks, then one night the whole batch fails:

ERROR:  ON CONFLICT DO UPDATE command cannot affect row a second time
HINT:  Ensure that no rows proposed for insertion within the same command have duplicate constrained values.
SQLSTATE: 21000

Two supplier feeds had reported the same ISBN in the same batch. Nothing is wrong with the table or the constraint. The statement asked PostgreSQL to update one row twice, and PostgreSQL refuses rather than guess an order. This guide reproduces the failure and its neighbours on PostgreSQL 18.4, explains the rule, and shows two deterministic ways to shape the batch so the database never has to guess.

The rule

The PostgreSQL 18 documentation for INSERT states the requirement for ON CONFLICT DO UPDATE: an INSERT with this clause is a deterministic statement, so the command is not allowed to affect any single existing row more than once, and a cardinality violation error is raised when that would happen. Rows proposed for insertion should not duplicate each other in terms of the attributes constrained by the arbiter index or constraint.

The reason is visible in the example. If the batch holds ('978-0001', 3) and ('978-0001', 4) and the update is qty = s.qty + excluded.qty, applying both gives one answer, but if the update were qty = excluded.qty, the result would depend on which proposed row was applied last. There is no ordering inside a VALUES list or a SELECT without ORDER BY that the statement could rely on, so the safe behaviour is to reject the statement. MERGE has the same rule. Its documentation asks you to ensure that the join produces at most one candidate change row for each target row, and adds that a repeated INSERT causes a uniqueness violation while a repeated UPDATE or DELETE causes a cardinality violation, the latter being required by the SQL standard.

Reproducing every shape on PostgreSQL 18.4

The companion probe postgres_batch_upsert_duplicates seeds a two-row table and runs eight statements against the same seed, recording the SQLSTATE or the resulting rows. The batch is:

-- Author: Sandeep Belgavi. Seed: ('978-0001', 5, 'seed'), ('978-0002', 1, 'seed').
insert into upsert_stock as s (isbn, qty, updated_by)
values ('978-0001', 3, 'feed-a'), ('978-0003', 7, 'feed-a'), ('978-0001', 4, 'feed-b')
on conflict (isbn) do update set qty = s.qty + excluded.qty, updated_by = excluded.updated_by;

Recorded on PostgreSQL 18.4 with a disposable local cluster:

StatementResultRows after
DO UPDATE, key repeated (existing row)SQLSTATE 21000seed unchanged
DO UPDATE, key repeated (new row)SQLSTATE 21000seed unchanged
DO NOTHING, key repeated (existing row)success, 1 row inserted978-0003 added, 978-0001 untouched
DO NOTHING, key repeated (new row)success, 1 row insertedfirst proposed row kept
MERGE, source key matches one target twiceSQLSTATE 21000seed unchanged
MERGE, source inserts the same new key twiceSQLSTATE 23505seed unchanged
Pre-aggregated with SUM, then DO UPDATEsuccess978-0001 qty 12
Last value per key by sequence, then DO UPDATEsuccess978-0001 qty 4 from feed-b

Several details are worth reading twice.

The error is not limited to rows that already exist. Two proposed rows for a key that is not yet in the table also fail with 21000: the first inserts the row, and the second would then update the row the same command just inserted.

DO NOTHING does not fail, but it is not a solution. With an existing key it skips both proposed rows. With a new key it keeps whichever proposed row it inserted first and silently drops the rest. If the loader switched to DO NOTHING to make the error go away, stock received from feed-b would vanish without a trace.

MERGE fails differently depending on the branch, exactly as its documentation describes. A repeated source key that matches an existing row raises 21000 with the hint "Ensure that not more than one source row matches any one target row". A repeated key that does not match goes down the insert branch twice and hits the primary key, raising 23505, a unique violation. A loader that catches only one of these codes will misclassify the other.

In every failing case the statement is atomic: the table holds exactly the seed rows afterwards. Nothing from the batch, not even the rows with unique keys, was applied.

Decide what a repeated key means, then say it in SQL

The fix is not a different statement; it is a decision about the data. When two rows in one batch describe the same key, which business rule combines them? There are two common answers, and each has a direct SQL form.

If the rows are increments, such as quantities received from different feeds, combine them by summing before the upsert:

insert into upsert_stock as s (isbn, qty, updated_by)
select isbn, sum(qty), string_agg(updated_by, '+' order by updated_by)
from (values ('978-0001', 3, 'feed-a'), ('978-0003', 7, 'feed-a'), ('978-0001', 4, 'feed-b'))
     as v(isbn, qty, updated_by)
group by isbn
on conflict (isbn) do update
  set qty = s.qty + excluded.qty, updated_by = excluded.updated_by;

The probe records 978-0001 at 12, the seed 5 plus 3 plus 4, with updated_by set to feed-a+feed-b, which keeps the provenance of both feeds.

If the rows are snapshots, where the newest value replaces older ones, you need an explicit order, because the batch has none of its own. Carry a sequence number or event time from the source and keep the last row per key with DISTINCT ON:

insert into upsert_stock as s (isbn, qty, updated_by)
select distinct on (isbn) isbn, qty, updated_by
from (values ('978-0001', 3, 'feed-a', 1), ('978-0003', 7, 'feed-a', 2), ('978-0001', 4, 'feed-b', 3))
     as v(isbn, qty, updated_by, seq)
order by isbn, seq desc
on conflict (isbn) do update set qty = excluded.qty, updated_by = excluded.updated_by;

The probe records 978-0001 at 4 from feed-b, the row with the highest sequence. The ORDER BY isbn, seq desc is what makes DISTINCT ON deterministic; without the seq term, PostgreSQL would keep an arbitrary row per key, which is precisely the guess the error was protecting you from.

The same shaping works for MERGE: use the aggregated or de-duplicated query as the USING source.

Doing it in the application instead

Loaders often build batches in application code, and it is reasonable to collapse duplicates there, before the SQL is built. The rule is the same: group by the constrained key and apply the business rule explicitly, sum or last-by-sequence, never "whichever came last in the list". Log how many rows were collapsed per batch. A sudden rise means a producer started sending duplicates, which is worth knowing even when the load succeeds.

Two traps are common in application-side de-duplication. Collapsing on a key that differs from the database's arbiter, for example trimming whitespace or ignoring case in the application while the unique index compares raw text, lets duplicates through or merges rows the database considers distinct. And collapsing per page of a paginated feed, rather than per database statement, misses duplicates that land in the same statement from two pages. The unit that matters is the single SQL statement.

Why splitting into single-row statements is not the answer

The quickest workaround is to send one INSERT ... ON CONFLICT per row. It never raises 21000, because no statement touches a row twice. But it hides the decision instead of making it: the order of application becomes the order in which the application happens to send the rows, and with several workers the order between them is not defined at all. It is also much slower for large batches. Use it only when the rows are increments and the update is commutative, like qty = s.qty + excluded.qty, and even then measure the cost.

Verification checklist

  • Add a test batch with a repeated key, both for an existing row and for a new row, and assert on the result you chose: summed, last by sequence, or rejected with a clear message.
  • If you use MERGE, test both the matched and the not-matched repeat and handle both 21000 and 23505.
  • Assert that no batch is silently shortened: compare the number of distinct keys in the input with the number of rows inserted or updated.
  • When a batch fails, remember it was atomic. Retrying the identical batch fails again; fix the shape, then retry.

Limits of this guide

The rule is quoted from the PostgreSQL 18 documentation for INSERT and MERGE. The results come from one session on PostgreSQL 18.4 with no concurrent writers; concurrency adds its own effects, which this probe does not test. Error message text can change between versions, so the probe compares SQLSTATE and rows rather than messages.

Primary references and authorship

Sources checked 2026-11-27. Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/sql/postgres_batch_upsert_duplicates. Views are my own and do not represent any employer, past or present.