Changing Data · Problem 113 of 118

Load a Price List with an Upsert

HardChanging DataShop data

A supplier sends two price-list lines:

sku name category_id supplier_id price cost added_on
SKU-0001 Steel pan 2 1 8.25 3.96 2026-10-05
SKU-9001 Bamboo tray 2 1 12.00 5.00 2026-10-05

SKU-0001 already exists: update only its price (keep its stock and everything else). SKU-9001 is new: insert it. Do it in one INSERT statement.

Check query. After your statements run, this query is run on the changed data and its result is compared with the expected one:

SELECT sku, name, price, cost, stock
FROM products
WHERE sku IN ('SKU-0001', 'SKU-9001')
ORDER BY sku;
Hint 1

INSERT ... ON CONFLICT (sku) DO UPDATE SET price = excluded.price. excluded is the row you tried to insert.

Reference solution

INSERT INTO products (sku, name, category_id, supplier_id, price, cost, added_on)
VALUES ('SKU-0001', 'Steel pan', 2, 1, 8.25, 3.96, '2026-10-05'),
       ('SKU-9001', 'Bamboo tray', 2, 1, 12.00, 5.00, '2026-10-05')
ON CONFLICT (sku) DO UPDATE SET price = excluded.price;

An upsert is "insert, or update if the row exists". It needs a unique rule to detect the conflict (sku is unique). ON CONFLICT ... DO UPDATE SET price = excluded.price changes only the columns you name. INSERT OR REPLACE deletes the old row and inserts the new one, so every column you did not list falls back to its default: the stock of SKU-0001 silently becomes 0. Different databases spell the upsert differently (ON DUPLICATE KEY UPDATE, MERGE), but the idea is the same.