×

sql · level 3 · unit 5 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

turns a clashing insert into an update.

A delivery brings 6 eggs. If eggs are already in the pantry, add to them. If not, add a new row. Checking first takes two statements. An , short for update or insert, does it in one.

Add ON CONFLICT (item) DO UPDATE SET ... to the INSERT. When a new row clashes with an existing item, that row is updated instead. means the value you tried to insert. DO NOTHING skips the row quietly.

The conflict column must be a PRIMARY KEY or UNIQUE, so the database knows what counts as a clash.

INSERT INTO stock (item, qty) VALUES ('eggs', 6), ('butter', 2)
ON CONFLICT (item) DO UPDATE SET qty = qty + excluded.qty;

SELECT item, qty FROM stock ORDER BY item;

In qty + excluded.qty, plain qty is the old value already in the table.