Predict the output
Two upserts for the same SKU. What does the SELECT print?
CREATE TABLE stock (sku text PRIMARY KEY, qty int NOT NULL);
INSERT INTO stock VALUES ('A1', 5)
ON CONFLICT (sku) DO UPDATE SET qty = stock.qty + EXCLUDED.qty;
INSERT INTO stock VALUES ('A1', 3)
ON CONFLICT (sku) DO UPDATE SET qty = stock.qty + EXCLUDED.qty;
SELECT sku, qty FROM stock;Hint 1 of 1
What does EXCLUDED hold?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A A1|8
Correct. The first inserts 5; the second conflicts and adds EXCLUDED.qty (3).
ON CONFLICT turns a duplicate-key insert into an update of the existing row. stock.qty is the stored value and EXCLUDED.qty is the value you tried to insert, so 5 + 3 = 8.
Why not the others?
- B
A1|3. That'sSET qty = EXCLUDED.qty, which overwrites instead of adding. - C
A1|5. That's DO NOTHING behaviour. - D A unique violation. ON CONFLICT turns the duplicate into an update.
| sku | qty |
|---|---|
| A1 | 8 |
(1 row)