Sub topic 5
Updating on conflict with `DO UPDATE`
This chapter assumes you know basic SELECT, INSERT, and UPDATE statements, primary keys, unique constraints, and how to run SQL in PostgreSQL.
An upsert with DO UPDATE inserts a row when its key is new. If the key already exists, PostgreSQL updates the existing row instead. The operation is one statement:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity,
updated_at = now();The sku column must have a primary key or unique constraint, or PostgreSQL must have a matching unique index. The conflict target, (sku), tells PostgreSQL which uniqueness rule controls this upsert.
What `DO UPDATE` changes
Suppose the table and an initial row already exist:
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', 2);The following statement proposes quantity 5:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity,
updated_at = now();Because A-100 already exists, PostgreSQL does not insert another row. It changes the existing row to quantity 5.
DO UPDATE requires a SET clause. You can assign constants, expressions, function results, or values from the proposed row.
The existing row and the proposed row
Inside the update action, PostgreSQL makes two values available:
- The target table, such as
product_stock, refers to the existing row. EXCLUDEDrefers to the row that theINSERTtried to add.
This lets you choose between replacement and combination.
Replacement uses the proposed quantity:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity;Combination adds the proposed quantity to the existing quantity:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 3)
ON CONFLICT (sku) DO UPDATE
SET quantity = product_stock.quantity + EXCLUDED.quantity;If the current quantity is 2, the second statement produces 5.
When an alias makes the two rows clearer, alias the target table:
INSERT INTO product_stock AS current (sku, quantity)
VALUES ('A-100', 3)
ON CONFLICT (sku) DO UPDATE
SET quantity = current.quantity + EXCLUDED.quantity;The name EXCLUDED does not mean that the row was permanently stored and then removed. It is PostgreSQL's name for the proposed INSERT row while it evaluates the conflict action.
Restricting the update
You can add a WHERE clause to the DO UPDATE action. PostgreSQL checks this condition after it finds the conflicting row. If the condition is false, PostgreSQL skips the update.
This avoids rewriting a row when the incoming value is unchanged:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity,
updated_at = now()
WHERE product_stock.quantity IS DISTINCT FROM EXCLUDED.quantity
RETURNING sku, quantity;IS DISTINCT FROM compares values safely even when NULL is possible. For the NOT NULL quantity column, product_stock.quantity <> EXCLUDED.quantity would also work.
A skipped update is different from an update that writes the same values. The WHERE condition prevents the row update entirely. This can reduce write activity, trigger executions, and dead tuples. PostgreSQL still checks the conflict and may lock the conflicting row while evaluating the action.
Choosing the conflict target
The target can name a constraint instead of repeating its columns:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT ON CONSTRAINT product_stock_pkey
DO UPDATE
SET quantity = EXCLUDED.quantity;For a partial unique index, include its predicate:
CREATE UNIQUE INDEX product_stock_active_sku_idx
ON product_stock (sku)
WHERE quantity > 0;
INSERT INTO product_stock (sku, quantity)
VALUES ('B-200', 4)
ON CONFLICT (sku) WHERE quantity > 0
DO UPDATE
SET quantity = EXCLUDED.quantity;The conflict target must match an existing unique or exclusion rule that PostgreSQL can use. It is not an arbitrary condition.
A single atomic decision
A common unsafe pattern is:
SELECTto check whether the key exists.INSERTif it does not.UPDATEif it does.
Two transactions can both observe that the key is absent and then race to insert it. ON CONFLICT DO UPDATE lets PostgreSQL perform conflict detection and the resulting action as one concurrency-safe operation. A transaction still needs appropriate isolation and error handling for other constraints or application rules, but the basic insert-versus-update race is handled by PostgreSQL.
MERGE can also express matched and unmatched actions, especially when several source rows or action types are involved. For a direct insert-or-update operation protected by a unique constraint, INSERT ... ON CONFLICT is usually the more focused choice. Its conflict handling is designed specifically for this race. MERGE uses a join condition and can still encounter a unique violation under concurrent writers.
Exercise
In an upsert, how do you set the stored quantity to the existing quantity plus the proposed quantity?
Show answer
Use SET quantity = product_stock.quantity + EXCLUDED.quantity in the DO UPDATE action.