SQL Dojo
Keyword

MERGE and upsert

MERGE updates the rows a table already has and inserts the new ones in one statement: the standard way to load a batch into a table.

You need it to load a batch into a table: the rows already there are updated, the new ones are inserted, and a second run changes nothing.

MERGE INTO prices p
USING price_file f ON p.sku = f.sku
WHEN MATCHED AND p.price <> f.price THEN UPDATE SET price = f.price
WHEN NOT MATCHED THEN INSERT (sku, price) VALUES (f.sku, f.price);

The branches are tried in order, and the first whose condition holds wins. A WHEN MATCHED AND … THEN DELETE branch removes rows; a source row that fits no branch changes nothing.

The trap. Two source rows for the same key. On a key the table already has, the MERGE stops with an error, or on some engines keeps whichever row comes last; on a new key, both rows are inserted and the table now holds a duplicate. Reduce the source to one row per key first, the latest one (ROW_NUMBER() … = 1).

On your warehouse. Snowflake, BigQuery and Databricks write it as above. Postgres has MERGE since version 15; its upsert, INSERT … ON CONFLICT (sku) DO UPDATE SET price = EXCLUDED.price, needs a primary or unique key on sku, which the other three do not enforce. DuckDB has both, and INSERT OR REPLACE INTO prices … as a shortcut.

The trap

WITH price_file(sku, unit_price, sent_at) AS (VALUES
  ('CAF-001', 32.90, TIMESTAMP '2026-03-01 09:00:00'),
  ('CAF-001', 33.50, TIMESTAMP '2026-03-02 09:00:00'),
  ('CAF-099', 21.00, TIMESTAMP '2026-03-01 09:00:00'))
SELECT f.sku, p.unit_price AS old_price, f.unit_price AS new_price,
       CASE WHEN p.sku IS NULL THEN 'insert' ELSE 'update' END AS action
FROM price_file f
LEFT JOIN products p ON p.sku = f.sku
ORDER BY f.sku, f.sent_at;
skuold_pricenew_priceaction
CAF-00131.9032.90update
CAF-00131.9033.50update
CAF-099NULL21.00insert
Try it in Randori

The fix

WITH price_file(sku, unit_price, sent_at) AS (VALUES
  ('CAF-001', 32.90, TIMESTAMP '2026-03-01 09:00:00'),
  ('CAF-001', 33.50, TIMESTAMP '2026-03-02 09:00:00'),
  ('CAF-099', 21.00, TIMESTAMP '2026-03-01 09:00:00')),
latest AS (
  SELECT sku, unit_price,
         ROW_NUMBER() OVER (PARTITION BY sku ORDER BY sent_at DESC) AS rn
  FROM price_file
)
SELECT l.sku, p.unit_price AS old_price, l.unit_price AS new_price,
       CASE WHEN p.sku IS NULL THEN 'insert' ELSE 'update' END AS action
FROM latest l
LEFT JOIN products p ON p.sku = l.sku
WHERE l.rn = 1
ORDER BY l.sku;
skuold_pricenew_priceaction
CAF-00131.9033.50update
CAF-099NULL21.00insert
Try it in Randori