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;| sku | qty |
|---|---|
| pen | 13 |
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;| sku | qty |
|---|---|
| pen | 10 |
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;| sku | qty |
|---|---|
| pen | 13 |
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