Sub topic 5
Writing the upsert with INSERT ... ON CONFLICT
This chapter assumes you know basic SQL (INSERT, UPDATE, SELECT) and understand primary keys and unique constraints. The earlier chapters gave the customers table a unique constraint on (source_system, external_id). Here you use that constraint to write the upsert in PostgreSQL.
Why not select first, then insert or update?
A common first attempt looks like this:
- Run
SELECT id FROM customers WHERE source_system = 'crm' AND external_id = 'C-1001'. - If a row came back, run
UPDATE. - If not, run
INSERT.
This needs two or three round trips. It also has a race. Two sessions can both run the SELECT, both see no row, and both try to INSERT. One of them fails with a unique violation, or, without the constraint, you get a duplicate.
INSERT ... ON CONFLICT moves the decision into one statement. The database checks the unique index, and the check and the write happen together. No other session can slip in between them.
The base table
The table keeps its own primary key and enforces uniqueness of the external ID, scoped by the system it came from.
CREATE TABLE customers (
id bigserial PRIMARY KEY,
source_system text NOT NULL,
external_id text NOT NULL,
name text NOT NULL,
email text,
UNIQUE (source_system, external_id)
);Anatomy of the statement
If no row has this external ID, the statement inserts one. Otherwise it updates the name and email of the existing row. Either way it returns the internal id.
INSERT INTO customers (source_system, external_id, name, email)
VALUES ('crm', 'C-1001', 'Ada Lovelace', '[email protected]')
ON CONFLICT (source_system, external_id)
DO UPDATE SET name = EXCLUDED.name, email = EXCLUDED.email
RETURNING id;Each part has a job:
| Part | Role |
|---|---|
| `INSERT INTO ... VALUES ...` | The row you want to exist. It is tried first. |
| `ON CONFLICT (source_system, external_id)` | The conflict target. It names the columns of the unique index that decides whether a row "already exists". |
| `DO UPDATE SET ...` | The action when the insert would violate that index. |
| `EXCLUDED` | A pseudo-table holding the row you tried to insert. |
| `RETURNING id` | Returns the internal key of the row that was inserted or updated. |
The flow looks like this:
The conflict target must match a unique index
The columns in ON CONFLICT (...) must match a unique index or constraint exactly. Column order does not matter, but the set of columns does. If you write ON CONFLICT (external_id) while the only unique constraint is on (source_system, external_id), PostgreSQL rejects the statement with an error like "there is no unique or exclusion constraint matching the ON CONFLICT specification".
This is why the constraint chapter came first. Without the constraint, the upsert has nothing to match against. You can also name the constraint instead of listing columns:
ON CONFLICT ON CONSTRAINT customers_source_system_external_id_keyListing columns is usually clearer. It survives a rename of the constraint.
EXCLUDED versus the table name
Inside DO UPDATE, two row versions are visible:
EXCLUDED.nameis the value you tried to insert.customers.nameis the value currently stored. If you gave the table an alias, use the alias.
Writing SET name = EXCLUDED.name means "take the incoming value". You can also compute from both, for example SET login_count = customers.login_count + 1.
DO UPDATE versus DO NOTHING
DO NOTHING skips the conflicting row without touching it:
INSERT INTO customers (source_system, external_id, name, email)
VALUES ('crm', 'C-1001', 'Ada Lovelace', '[email protected]')
ON CONFLICT (source_system, external_id)
DO NOTHING
RETURNING id;Use it when the first write should win and later copies are noise. There is a catch. When the row conflicts, nothing is inserted, so RETURNING returns zero rows. Code that expects an id back on every call will break on the second run.
If you need the id in both cases, you have two options. The first is to use DO UPDATE with a harmless assignment. The second is to fall back to a SELECT in the same statement:
WITH ins AS (
INSERT INTO customers (source_system, external_id, name, email)
VALUES ('crm', 'C-1001', 'Ada Lovelace', '[email protected]')
ON CONFLICT (source_system, external_id) DO NOTHING
RETURNING id
)
SELECT id FROM ins
UNION ALL
SELECT id FROM customers
WHERE source_system = 'crm' AND external_id = 'C-1001'
LIMIT 1;The first branch is empty when the row already existed, so the second branch supplies the id. Under heavy concurrency this fallback can still miss a row that another transaction has not yet committed. The DO UPDATE form is simpler and avoids that gap.
Skipping updates that change nothing
A plain DO UPDATE rewrites the row even when every incoming value equals the stored one. PostgreSQL still creates a new row version. That adds table bloat, fires update triggers, and bumps any updated_at column your triggers maintain. A WHERE clause on DO UPDATE avoids this:
INSERT INTO customers (source_system, external_id, name, email)
VALUES ('crm', 'C-1001', 'Ada Lovelace', '[email protected]')
ON CONFLICT (source_system, external_id)
DO UPDATE SET name = EXCLUDED.name, email = EXCLUDED.email
WHERE (customers.name, customers.email)
IS DISTINCT FROM (EXCLUDED.name, EXCLUDED.email)
RETURNING id;IS DISTINCT FROM treats NULL as a comparable value. A plain <> would return NULL when email is NULL on either side, and the update would be skipped by mistake.
When the WHERE is false, the row is left alone and RETURNING produces no row for it, just as with DO NOTHING. Keep that in mind if your code reads the returned id.
A later chapter uses the same WHERE mechanism for a different purpose, which is to reject stale source data. The decision about which columns to list in SET gets its own chapter. For now, list only the columns the source system owns.
Seeing both outcomes
You can confirm the behaviour in psql. Run the first upsert twice with different names:
INSERT INTO customers (source_system, external_id, name, email)
VALUES ('crm', 'C-1001', 'Ada Lovelace', '[email protected]')
ON CONFLICT (source_system, external_id)
DO UPDATE SET name = EXCLUDED.name, email = EXCLUDED.email
RETURNING id;
INSERT INTO customers (source_system, external_id, name, email)
VALUES ('crm', 'C-1001', 'Ada King', '[email protected]')
ON CONFLICT (source_system, external_id)
DO UPDATE SET name = EXCLUDED.name, email = EXCLUDED.email
RETURNING id;
SELECT id, name FROM customers WHERE external_id = 'C-1001';Both statements return the same id. The final SELECT shows one row with the name Ada King. The second statement hit the conflict path and changed the name in place, without creating a new row.
Common errors and gotchas
- NULLs never conflict. In a unique index, two
NULLvalues are considered different. Ifexternal_idwere nullable, every row with aNULLwould insert as new. That is why the table declaresexternal_id text NOT NULL. - Case and whitespace differences are different keys.
'c-1001'and'C-1001 'do not conflict with'C-1001'. Clean the value before matching. The normalization chapter covers this. - One row, one touch. If a single
INSERTstatement contains two rows with the same external ID, PostgreSQL raises "ON CONFLICT DO UPDATE command cannot affect row a second time". The batch chapters show how to remove duplicates first. - Sequences advance on conflicts.
bigserialtakes a value for each attempted insert, including ones that end up as updates. Youridvalues will have gaps. This is harmless, but do not rely on ids being consecutive. - Do not update the match key. Putting
external_idorsource_systemin theSETlist is almost always a mistake. It changes the identity of the row you just matched. - Unique indexes with a
WHEREclause (partial indexes). If your unique index is partial, the conflict target needs a matchingWHEREpredicate, written asON CONFLICT (cols) WHERE predicate.
Telling an insert from an update
Sometimes the caller needs to know which happened. PostgreSQL has no documented flag for it. A widely used trick returns the internal system column xmax:
INSERT INTO customers (source_system, external_id, name, email)
VALUES ('crm', 'C-1001', 'Ada Lovelace', '[email protected]')
ON CONFLICT (source_system, external_id)
DO UPDATE SET name = EXCLUDED.name, email = EXCLUDED.email
RETURNING id, (xmax = 0) AS inserted;inserted is true for a fresh row and false for an updated one. This relies on undocumented internals, so treat it as a diagnostic aid and not as a contract your application logic depends on. If you need a reliable answer, compare row counts before and after, or keep a separate audit column.
Exercise
A teammate's upsert uses ON CONFLICT (external_id) DO UPDATE ... on the customers table above, where the only unique constraint is UNIQUE (source_system, external_id). What happens when it runs, and how do you fix it? Also, after fixing it, the code reads RETURNING id and fails on reruns where nothing changed because the statement has DO UPDATE ... WHERE (customers.name, customers.email) IS DISTINCT FROM (EXCLUDED.name, EXCLUDED.email). Why does it fail?
Show answer
PostgreSQL rejects the statement with an error saying there is no unique or exclusion constraint matching the ON CONFLICT specification, because the conflict target must match a unique index exactly. Change the target to ON CONFLICT (source_system, external_id). The rerun failure happens because the WHERE condition is false when the incoming values equal the stored ones, so no row is written and RETURNING produces no row. The code must handle an empty result, for example by falling back to a SELECT of the id, or by dropping the WHERE guard if it needs an id every time.