Sub topic 7
Avoiding Needless Writes with a `WHERE` Clause
This chapter assumes you know basic INSERT and UPDATE statements, primary keys, and unique constraints. It also assumes a product_stock table like this:
CREATE TABLE product_stock (
sku text PRIMARY KEY,
quantity integer NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);An upsert with ON CONFLICT DO UPDATE normally updates the conflicting row every time. Sometimes the incoming value is identical to the stored value. Updating anyway can create unnecessary work.
Add `WHERE` to `DO UPDATE`
The WHERE clause belongs after the SET list:
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;PostgreSQL first finds a conflict on sku. It then evaluates the WHERE condition for the existing row. If the condition is true, PostgreSQL performs the update. If it is false, PostgreSQL skips the update for that row.
Here, the update happens only when the stored quantity differs from the proposed quantity.
The two row versions have different names:
product_stockrefers to the existing row.EXCLUDEDrefers to the row proposed byINSERT.
The word EXCLUDED means the proposed row was excluded from insertion because it conflicted with an existing row. It does not mean that the row was deleted.
Compare values safely
For non-nullable columns such as quantity, this comparison also works:
WHERE product_stock.quantity <> EXCLUDED.quantityIS DISTINCT FROM is usually safer because it treats NULL as a comparable value. Ordinary comparisons with NULL produce an unknown result rather than true or false.
| Condition | Result when both values are `NULL` | Result when one value is `NULL` |
|---|---|---|
| `old_value <> new_value` | unknown | unknown |
| `old_value IS DISTINCT FROM new_value` | false | true |
For example, suppose a table stores an optional status:
CREATE TABLE inventory_note (
sku text PRIMARY KEY,
note text
);
INSERT INTO inventory_note (sku, note)
VALUES ('A-100', 'Backordered')
ON CONFLICT (sku) DO UPDATE
SET note = EXCLUDED.note
WHERE inventory_note.note IS DISTINCT FROM EXCLUDED.note;This updates the row when the note changes, when a note is added, or when a note is removed. It skips the update when both notes have the same value, including when both are NULL.
What happens when the condition is false?
A conflicting row that fails the WHERE condition is locked for the statement, but it is not updated. PostgreSQL does not return that row from the RETURNING clause.
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;If A-100 already has quantity 5, this statement returns no row. If A-100 has quantity 2, it updates the row and returns A-100 | 5.
This behavior lets an application distinguish between a row that was inserted or changed and a conflicting row that required no change.
Choose the columns that define a change
Do not compare only the columns that appear important at first glance. Include every column whose change should trigger the update.
For example, this condition checks both values:
WHERE product_stock.quantity IS DISTINCT FROM EXCLUDED.quantity
OR product_stock.updated_at IS DISTINCT FROM EXCLUDED.updated_atHowever, setting updated_at = now() means it will always differ from the old timestamp. In that case, including updated_at in the comparison would defeat the purpose of skipping unchanged quantities. Compare the source data columns first, then update bookkeeping columns only when a real change occurs.
Exercise
The existing row has quantity 8, and the proposed row has quantity 8. What does this statement do? INSERT INTO product_stock (sku, quantity) VALUES ('A-100', 8) ON CONFLICT (sku) DO UPDATE SET quantity = EXCLUDED.quantity WHERE product_stock.quantity IS DISTINCT FROM EXCLUDED.quantity RETURNING sku;
Show answer
It detects the conflict, finds that the quantities are not distinct, skips the update, and returns no row.