Data modification & MERGE
Concept  ·  SQL & Querying

A MERGE source with two rows for one target key is undefined territory — some engines error, some silently apply one; pre-aggregate the source to the target's grain, always.

MERGE matches source rows to target rows by key. Two source rows for one target key is an undefined match: the standard does not say which update wins, so engines differ.

See it break
stock
skuqty
A10
deltas
skudelta
A5
A3
The trap
MERGE INTO stock USING deltas
  ON stock.sku = deltas.sku WHEN MATCHED THEN
UPDATE
SET
  qty = stock.qty + deltas.delta;

SELECT
  sku,
  qty
FROM
  stock
ORDER BY
  sku;
The fix
MERGE INTO stock USING (
  SELECT
    sku,
    SUM(delta) AS delta
  FROM
    deltas
  GROUP BY
    sku
) d ON stock.sku = d.sku WHEN MATCHED THEN
UPDATE
SET
  qty = stock.qty + d.delta;

SELECT
  sku,
  qty
FROM
  stock
ORDER BY
  sku;
INPUTYour queryThe fix
A1518

Verification found the silent case is real — the engine applied one of two updates and reported success; loud failure (Postgres) is the good outcome.

The rule

Pre-aggregate the source, or dedupe it to one row per target key before the MERGE.

USING (SELECT key, SUM(val) AS val FROM src GROUP BY key) s
Shows up elsewhere
Idempotent upsert
Try one →Prove it in practice →