INSERT ON CONFLICT (Upsert)
Last updated: 2026-11-04
INSERT ON CONFLICT (Upsert)
INSERT ... ON CONFLICT reroutes an insert that would violate a unique key: DO NOTHING skips the conflicting row, DO UPDATE modifies it instead. With RETURNING you also get the post-conflict row back, so a single statement can perform an idempotent write or accumulate a counter.
| Kind | command |
|---|---|
| Example Language | SQL |
📝 Syntax
INSERT INTO <table> [(<column>, ...)]
VALUES (<value>, ...), ...
[ON CONFLICT (<conflict target>) DO NOTHING]
[ON CONFLICT (<conflict target>) DO UPDATE SET <column> = <expression>, ...
[WHERE <condition>]]
[RETURNING <column or expression>]
⚙️ Parameters
| ON CONFLICT | Starts the conflict-handling clause |
|---|---|
| <conflict_target> | The conflicting column, or ON CONSTRAINT |
| DO NOTHING | Skips the conflicting row unchanged |
| DO UPDATE SET | Updates the existing row on conflict |
| EXCLUDED | The new values this statement wanted to insert |
Returns:The number of affected rows; with RETURNING, the inserted or updated rows are returned as well.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
DROP TABLE
CREATE TABLE
INSERT 0 2
INSERT 0 1
INSERT 0 0
id | name | visits
---+---------------+-------
3 | Carol updated | 6
📌 Key Points
- The conflict target must match a unique index or primary key, otherwise you get there is no unique or exclusion constraint matching the ON CONFLICT specification.
- Inside DO UPDATE SET, EXCLUDED.column is the value this statement wanted to insert, while table.column is the value already stored.
- The SET expressions read the conflicting row's old values, so a counter accumulates as visits = table.visits + EXCLUDED.visits.
- DO NOTHING returns no row for the conflicting case, so RETURNING will not surface the row that already existed.
- With several unique constraints, name the conflicting column explicitly or use ON CONFLICT ON CONSTRAINT
. - Rows inserted concurrently by other transactions can still trigger a unique violation, so pair this with retry logic.
💡 Related Cases
More case studies coming soon.
📚 Related Reference
❓ FAQ
QHow do I use an upsert to accumulate a counter?
AUse ON CONFLICT (id) DO UPDATE SET visits = table.visits + EXCLUDED.visits to add the incoming value to the stored one when a conflict occurs.
QHow do I overwrite the old value on conflict?
AUse DO UPDATE SET column = EXCLUDED.column; to assign the incoming value to the column.