Sub topic 2
Updating on conflict with DO UPDATE
This chapter assumes you know basic SQL (SELECT, INSERT, UPDATE), understand primary keys and unique constraints, and can run statements in psql. It builds on ON CONFLICT DO NOTHING.
Updating on conflict with DO UPDATE
DO NOTHING skips a conflicting row. DO UPDATE changes the existing row instead. Use it when a repeated insert should overwrite stored data.
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);
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity,
updated_at = now();The conflict target (sku) must match a unique constraint or unique index. Without one, PostgreSQL raises an error.
Using EXCLUDED to reference the proposed row
Inside DO UPDATE, the name EXCLUDED refers to the row that the INSERT tried to add. The table name refers to the row already stored. Combine the two to add stock instead of replacing it:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 3)
ON CONFLICT (sku) DO UPDATE
SET quantity = product_stock.quantity + EXCLUDED.quantity;After this runs, A-100 holds 8 units.
Avoiding needless writes with a WHERE clause
DO UPDATE rewrites the row even when the new values match the stored ones. A WHERE clause skips the write in that case:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 8)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity,
updated_at = now()
WHERE product_stock.quantity IS DISTINCT FROM EXCLUDED.quantity;The stored quantity is already 8, so the condition is false. The row stays untouched, including its updated_at value. Use IS DISTINCT FROM rather than <>, because <> returns NULL when either side is NULL, and NULL is not treated as true.
| Clause | Existing row | Use when |
|---|---|---|
| DO NOTHING | Left unchanged | Duplicates can be ignored |
| DO UPDATE | Changed | The newest value should win |
| DO UPDATE ... WHERE | Changed only if the condition is true | Unchanged rows should not be rewritten |
Exercise
Change the stock-adding upsert so that a proposed quantity of 0 does not rewrite an existing row. Describe the change.
Show answer
Add WHERE EXCLUDED.quantity <> 0 after the SET clause. A zero proposal then leaves the stored row unchanged, though a brand-new sku with quantity 0 is still inserted.