Sub topic 5
Updating on conflict with DO UPDATE
This chapter assumes you can write basic SELECT, INSERT and UPDATE statements, know what primary keys and unique constraints are, and can run statements in psql or another PostgreSQL client. Earlier chapters covered conflict targets and DO NOTHING. Here you will learn what DO UPDATE does, how PostgreSQL runs it, and which errors it raises.
What DO UPDATE does
ON CONFLICT DO NOTHING skips a row that collides with an existing one. ON CONFLICT DO UPDATE instead turns the INSERT into an UPDATE of the row it collided with. The statement either inserts a new row or updates the existing one, and it does this atomically.
Use this setup for the examples:
CREATE TABLE product_stock (
sku text PRIMARY KEY,
quantity integer NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO product_stock (sku, quantity) VALUES ('A-100', 5);Now run the upsert:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 8)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity,
updated_at = now();
SELECT sku, quantity FROM product_stock;
-- sku | quantity
-- A-100 | 8The INSERT proposed a row for A-100. The primary key already had one, so PostgreSQL ran the SET list against the existing row. The row now holds quantity 8, and psql reports INSERT 0 1. The command tag is the same whether the row was inserted or updated, so it cannot tell you which happened.
If the key had not existed, PostgreSQL would have inserted the row and ignored the DO UPDATE branch.
The anatomy of the clause
INSERT INTO table_name (columns)
VALUES (...)
ON CONFLICT conflict_target DO UPDATE
SET column = expression [, ...]
[WHERE condition]Three parts matter:
- The conflict target names the unique index or constraint that defines a conflict. You can give a column list such as
(sku), a constraint name withON CONSTRAINT product_stock_pkey, or a column list with a partial-index predicate. - The
SETlist works like theSETlist of anUPDATE. Columns you leave out keep their current values. - The optional
WHEREfilters which conflicting rows get updated. A later chapter covers it.
The conflict target is mandatory
DO NOTHING lets you omit the target. DO UPDATE does not:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 8)
ON CONFLICT DO UPDATE SET quantity = EXCLUDED.quantity;
-- ERROR: ON CONFLICT DO UPDATE requires inference specification or constraint name
-- HINT: For example, ON CONFLICT (column_name).PostgreSQL requires the target because the update must be deterministic. It has to know which unique index decides which existing row to update. With several unique indexes on a table, a vague "any conflict" could match different rows.
Two row references: the table and EXCLUDED
Inside DO UPDATE, two rows are in scope:
| Reference | Meaning |
|---|---|
| `product_stock.quantity` | The value in the existing row, the one that caused the conflict |
| `EXCLUDED.quantity` | The value the `INSERT` proposed, which was "excluded" from insertion |
The next chapter covers EXCLUDED in detail. The key point here is that you choose how the two rows combine. Overwriting with the new value uses EXCLUDED alone. Accumulating uses both:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 3)
ON CONFLICT (sku) DO UPDATE
SET quantity = product_stock.quantity + EXCLUDED.quantity;With the existing quantity at 8, the row ends at 11. This pattern is the usual way to build counters, running totals and "last seen" values in one statement.
Ambiguous column names
An unqualified column on the right side of SET can refer to either row, so PostgreSQL rejects it:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 3)
ON CONFLICT (sku) DO UPDATE
SET quantity = quantity + 3;
-- ERROR: column reference "quantity" is ambiguousQualify the column with the table name or with EXCLUDED.
If you give the target table an alias, the alias replaces the table name. You must then use the alias to refer to the existing row:
INSERT INTO product_stock AS ps (sku, quantity)
VALUES ('A-100', 3)
ON CONFLICT (sku) DO UPDATE
SET quantity = ps.quantity + EXCLUDED.quantity;Writing product_stock.quantity here would fail with invalid reference to FROM-clause entry for table "product_stock". Column names on the left side of SET are never qualified, as in a normal UPDATE.
Defaults do not apply to the update
The column default DEFAULT now() on updated_at fires only when PostgreSQL inserts a row. When the statement takes the update branch, defaults are not used, and updated_at keeps its old value unless the SET list changes it. That is why the examples set updated_at = now() explicitly. Forgetting this is a common source of stale timestamps.
Columns you do not list in SET are untouched. In a table with a created_at column, an upsert that does not mention created_at preserves the original creation time, which is usually what you want.
How the statement runs
The following diagram shows the decision PostgreSQL makes for each proposed row.
Several consequences follow from this flow.
- The existing row is locked. Between detecting the conflict and writing the update, PostgreSQL takes a row-level lock. Another transaction cannot change that row in the meantime. This is the basis for the concurrency guarantees covered in a later chapter.
- The update is a normal
UPDATE. PostgreSQL writes a new row version and marks the old one dead. EveryDO UPDATEthat fires costs a full row rewrite, even if the values are identical. - Only the arbiter index handles conflicts. The conflict target selects the arbiter. A collision on any other unique index is not handled and raises an error, as the next section shows.
Conflicts on a different unique index
Consider a table with two unique columns:
CREATE TABLE account (
id integer PRIMARY KEY,
email text UNIQUE NOT NULL,
plan text NOT NULL
);
INSERT INTO account (id, email, plan) VALUES (1, '[email protected]', 'free');An upsert keyed on id works as expected when the id already exists:
INSERT INTO account (id, email, plan)
VALUES (1, '[email protected]', 'pro')
ON CONFLICT (id) DO UPDATE SET plan = EXCLUDED.plan;
-- INSERT 0 1Now propose a new id with an email that is already taken:
INSERT INTO account (id, email, plan)
VALUES (2, '[email protected]', 'pro')
ON CONFLICT (id) DO UPDATE SET plan = EXCLUDED.plan;
-- ERROR: duplicate key value violates unique constraint "account_email_key"The arbiter is the primary key on id. No row has id = 2, so there is no conflict on the arbiter. The insert then runs into the unique constraint on email, which is not covered by ON CONFLICT, and the statement fails.
If you want to handle an email collision, name the email column as the target: ON CONFLICT (email) DO UPDATE .... A single ON CONFLICT DO UPDATE clause can only handle one arbiter. You cannot list two targets, so decide which key defines "the same row" for your data.
Updating the key columns
The SET list may include the conflict columns, but this is rarely useful. Setting sku = EXCLUDED.sku does nothing, because the values are equal by definition of the conflict. Setting the key to something else moves the row, and it can fail if the new value collides with a different existing row. In practice, leave key columns out of SET.
Triggers and side effects
Upserts run triggers in a specific order:
- Row-level
BEFORE INSERTtriggers fire for the proposed row first, even if the row ends up taking the update branch. A trigger that modifies the proposed row changes whatEXCLUDEDcontains. - If the conflict occurs, row-level
BEFORE UPDATEtriggers fire for the existing row, and thenAFTER UPDATEtriggers. - If there is no conflict, the
AFTER INSERTtriggers fire. - Statement-level triggers for both
INSERTandUPDATEfire, whichever branch each row takes.
So an audit trigger on AFTER UPDATE will record upserts that update rows, and an AFTER INSERT trigger will not fire for them. If you maintain derived data in triggers, check that both paths are covered.
A related side effect is that identity and serial columns consume a value for every proposed row, even when the row is updated instead of inserted. This leaves gaps in the sequence. A later chapter on pitfalls covers this.
Reading the outcome
Because the command tag is the same for inserts and updates, use RETURNING when you need data back. You can also tell which branch ran with the system column xmax: it is 0 for a freshly inserted row and non-zero for an updated one.
INSERT INTO product_stock (sku, quantity)
VALUES ('C-300', 1)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity
RETURNING sku, quantity, (xmax = 0) AS inserted;The first run returns inserted = true. A second run returns inserted = false. This relies on PostgreSQL internals and works in practice, but xmax is not a documented contract for this purpose. The next chapters cover RETURNING properly.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `requires inference specification or constraint name` | No conflict target given | Add `(column)` or `ON CONSTRAINT name` |
| `column reference "x" is ambiguous` | Unqualified column in `SET` expression | Use `table.x` or `EXCLUDED.x` |
| `invalid reference to FROM-clause entry` | Used the table name after aliasing it | Use the alias |
| `there is no unique or exclusion constraint matching the ON CONFLICT specification` | Target columns have no matching unique index | Create the index or fix the target |
| Unique violation on another constraint | Collision on an index that is not the arbiter | Pick the correct target or clean the data |
| `cannot affect row a second time` | The same key appears twice in one statement | Merge duplicates before inserting |
| Stale `updated_at` | Relied on a column default | Set the column in `SET` |
Summary
DO UPDATE converts a conflicting insert into an update of the existing row. It requires an explicit conflict target, which selects the single arbiter index. In the SET list, the table name (or alias) refers to the existing row and EXCLUDED refers to the proposed row. Defaults do not apply to the update branch. Every update writes a new row version, and any collision on a non-arbiter unique index still fails.
Exercise
A table account(id integer PRIMARY KEY, email text UNIQUE NOT NULL, plan text NOT NULL) contains the row (1, '[email protected]', 'free'). You run INSERT INTO account (id, email, plan) VALUES (2, '[email protected]', 'pro') ON CONFLICT (id) DO UPDATE SET plan = EXCLUDED.plan;. What happens, and how would you change the statement so that row 1 is updated to the 'pro' plan?
Show answer
The statement fails with a unique violation on account_email_key. The arbiter is the primary key on id, and no row has id 2, so the update branch never runs. The insert then collides with the unique constraint on email, which ON CONFLICT (id) does not handle. To update row 1, use the email as the conflict target: ON CONFLICT (email) DO UPDATE SET plan = EXCLUDED.plan.
Exercise
Write an upsert on product_stock that adds 4 to the quantity of sku 'D-400' if it exists and inserts it with quantity 4 otherwise, and that also refreshes updated_at. Why is SET updated_at = now() needed in the statement?
Show answer
INSERT INTO productstock (sku, quantity) VALUES ('D-400', 4) ON CONFLICT (sku) DO UPDATE SET quantity = productstock.quantity + EXCLUDED.quantity, updatedat = now(); The column default DEFAULT now() applies only when a row is inserted. On the update branch, `updatedat keeps its old value unless the SET` list assigns it.
Exercise
Why does SET quantity = quantity + 1 fail in an upsert, and what are two ways to write it correctly?
Show answer
The unqualified quantity could refer to the existing row or to EXCLUDED, so PostgreSQL raises "column reference "quantity" is ambiguous". Qualify it: SET quantity = product_stock.quantity + 1. Or give the table an alias in the INSERT (INSERT INTO product_stock AS ps ...) and write SET quantity = ps.quantity + 1.