← Back to SQL, page 10

sql-0188 · Medium mid

How do you insert a row, or update it if the key already exists, in one statement?

Use INSERT ... ON CONFLICT (key) DO UPDATE SET col = excluded.col in PostgreSQL and SQLite 3.24+. excluded refers to the row that was proposed for insertion, and DO NOTHING skips the row instead. The conflict target must match a unique constraint or index.

Full answer
sql
CREATE TABLE stock (sku TEXT PRIMARY KEY, qty INTEGER NOT NULL);
INSERT INTO stock VALUES ('pen', 10);
INSERT INTO stock VALUES ('pen', 3)
  ON CONFLICT (sku) DO UPDATE SET qty = stock.qty + excluded.qty;
SELECT * FROM stock;
skuqty
pen13

The second insert for 'pen' hit the primary key, so the DO UPDATE ran and added the new quantity to the existing one. excluded.qty is the 3 from the failed insert; stock.qty is the stored 10.

DO NOTHING ignores the duplicate:

sql
CREATE TABLE stock2 (sku TEXT PRIMARY KEY, qty INTEGER NOT NULL);
INSERT INTO stock2 VALUES ('pen', 10);
INSERT INTO stock2 VALUES ('pen', 3) ON CONFLICT (sku) DO NOTHING;
SELECT * FROM stock2;
skuqty
pen10

PostgreSQL uses identical syntax:

sql
CREATE TABLE stock (sku text PRIMARY KEY, qty int NOT NULL);
INSERT INTO stock VALUES ('pen', 10);
INSERT INTO stock VALUES ('pen', 3)
  ON CONFLICT (sku) DO UPDATE SET qty = stock.qty + excluded.qty;
SELECT * FROM stock;
skuqty
pen13

An upsert is atomic: unlike "select, then insert or update", two concurrent requests cannot both decide to insert.

sql
CREATE TABLE stock (sku TEXT PRIMARY KEY, qty INTEGER NOT NULL);
INSERT INTO stock VALUES ('pen', 10);
INSERT INTO stock VALUES ('pen', 3)
  ON CONFLICT (sku) DO UPDATE SET qty = stock.qty + excluded.qty;
SELECT * FROM stock;

CREATE TABLE stock2 (sku TEXT PRIMARY KEY, qty INTEGER NOT NULL);
INSERT INTO stock2 VALUES ('pen', 10);
INSERT INTO stock2 VALUES ('pen', 3) ON CONFLICT (sku) DO NOTHING;
SELECT * FROM stock2;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • INSERT ... ON CONFLICT (key) DO UPDATE performs an upsert
  • excluded holds the proposed row
  • DO NOTHING skips conflicting rows
  • The conflict target needs a unique constraint

Common mistakes

  • Writing check-then-insert logic that races
  • Overwriting a counter instead of adding excluded's value

Follow-ups

  • How does INSERT OR REPLACE differ in SQLite?
  • How would you upsert many rows from a staging table?

Tips

  • Explain excluded clearly