Memra

UPSERT: INSERT … ON CONFLICT

Insert, or update if it already exists — atomically.

Insert-or-update in one statement

You often want "add this row, but if it already exists, update it instead". Postgres does it atomically with ON CONFLICT:

INSERT INTO books (id, title, author_id, genre, price, stock)
VALUES (1, 'The Glass Forest', 1, 'fiction', 14.99, 20)
ON CONFLICT (id) DO UPDATE
  SET stock = EXCLUDED.stock
RETURNING id, stock;

Book 1 already exists, so the conflict on the id primary key fires the DO UPDATE. EXCLUDED refers to the row you *tried* to insert — so this restocks book 1 to 20. ON CONFLICT ... DO NOTHING is the other common form.

NORMAL ~/memra/learn/postgresql/upsert-on-conflict utf-8 LF