Sub topic 7
Avoiding Needless Writes with a WHERE Clause
This chapter assumes you can write INSERT ... ON CONFLICT DO UPDATE and use EXCLUDED, as covered in the previous chapters. You should also know what a row version (tuple) is in PostgreSQL, at least roughly. The examples use the product_stock table from earlier in this tutorial.
The problem: DO UPDATE always writes
A plain DO UPDATE rewrites the existing row whenever a conflict happens. That is true even when the new values equal the old ones. PostgreSQL does not check whether an UPDATE changes anything. Under its multiversion concurrency control (MVCC), every update writes a new row version and leaves the old one behind as a dead tuple.
An upsert that re-sends unchanged data therefore costs you the following:
- A new heap tuple, plus new index entries when HOT (heap-only tuple) updates are not possible.
- Write-ahead log (WAL) records, which are also shipped to replicas.
- Dead tuples that autovacuum must clean up later.
- Row-level
UPDATEtriggers firing, and logical replication or change-data-capture consumers seeing a change that is not one.
This matters for jobs that sync a full snapshot every few minutes, where most rows have not changed. You can add a WHERE clause to the DO UPDATE action so that unchanged rows are left alone.
The syntax
The WHERE clause goes after the SET list. The update happens only for rows where the condition is true.
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;The condition can see both rows involved in the conflict:
- The existing row, which you name with the table name (or the alias, if you gave the table one).
- The proposed row, which you name with
EXCLUDED.
Qualify every column in the condition. An unqualified quantity is ambiguous between the two rows, and PostgreSQL raises column reference "quantity" is ambiguous.
Why IS DISTINCT FROM and not <>
The usual "has it changed" test is a comparison. The ordinary <> operator returns NULL when either side is NULL, and a WHERE clause treats NULL as not true. A change from NULL to a value, or from a value to NULL, would be silently skipped.
IS DISTINCT FROM treats NULL as an ordinary value. Two NULLs are not distinct, and a NULL and a non-NULL are distinct.
| Existing value | Proposed value | `old <> new` | `old IS DISTINCT FROM new` |
|---|---|---|---|
| 5 | 6 | true | true |
| 5 | 5 | false | false |
| NULL | 5 | NULL (skipped) | true |
| 5 | NULL | NULL (skipped) | true |
| NULL | NULL | NULL (skipped) | false |
For quantity, which is NOT NULL, <> happens to work. Use IS DISTINCT FROM anyway, because the table definition may change later.
Comparing several columns at once
When an upsert sets several columns, compare them as row values. PostgreSQL supports IS DISTINCT FROM on row constructors, and NULLs are handled per column.
CREATE TABLE IF NOT EXISTS product_price (
sku text PRIMARY KEY,
price numeric(10,2) NOT NULL,
currency char(3) NOT NULL,
note text,
source_ts timestamptz NOT NULL
);
INSERT INTO product_price (sku, price, currency, note, source_ts)
VALUES ('A-100', 9.99, 'EUR', NULL, '2026-11-27 10:00+00')
ON CONFLICT (sku) DO UPDATE
SET price = EXCLUDED.price,
currency = EXCLUDED.currency,
note = EXCLUDED.note,
source_ts = EXCLUDED.source_ts
WHERE (product_price.price, product_price.currency, product_price.note)
IS DISTINCT FROM
(EXCLUDED.price, EXCLUDED.currency, EXCLUDED.note);Notice what the comparison leaves out. source_ts is assigned in SET but is not compared. If you included a column that changes on every run, such as updated_at = now(), the condition would always be true and the filter would do nothing. Compare only the columns whose change you care about.
Proving the write was avoided
You can observe the difference through the system columns ctid (the physical location of the row version) and xmin (the transaction that created it). Run the following in psql.
CREATE TABLE IF NOT EXISTS product_stock (
sku text PRIMARY KEY,
quantity integer NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
-- Make sure the row exists with quantity 5.
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku) DO UPDATE SET quantity = EXCLUDED.quantity;
SELECT ctid, xmin, quantity FROM product_stock WHERE sku = 'A-100';
-- Unconditional upsert with the same value.
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity, updated_at = now();
SELECT ctid, xmin, quantity FROM product_stock WHERE sku = 'A-100';
-- Conditional upsert with the same value.
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;
SELECT ctid, xmin, quantity FROM product_stock WHERE sku = 'A-100';After the unconditional upsert, xmin and usually ctid differ from the first query, even though quantity is still 5. After the conditional upsert, both are identical to the second query. The conditional statement reports INSERT 0 0 as its command tag, which means no row was inserted or updated.
What happens to a skipped row
When the condition is false, PostgreSQL does not update the row. Four consequences follow.
- No new version. No tuple is written, no UPDATE-related WAL is generated for it, and no dead tuple appears.
- No UPDATE triggers. Row-level
BEFORE UPDATEandAFTER UPDATEtriggers do not fire for that row.BEFORE INSERTtriggers do fire, because they run before the conflict is detected, and their changes are reflected inEXCLUDED. - The row is still locked. PostgreSQL locks the conflicting row before it evaluates the condition, so a skipped row is locked until your transaction ends. A long transaction that upserts many unchanged rows can still block other writers.
- No RETURNING output.
RETURNINGproduces rows only for inserted or updated rows. A skipped row is absent from the result.
The fourth point is a frequent source of bugs. Suppose application code upserts a row and expects the id back.
INSERT INTO app_user (email, name)
VALUES ('[email protected]', 'Ada')
ON CONFLICT (email) WHERE deleted_at IS NULL
DO UPDATE SET name = EXCLUDED.name
WHERE app_user.name IS DISTINCT FROM EXCLUDED.name
RETURNING id;On the second run with the same name, this returns zero rows, and code that reads id from the first result row fails. If you need the row either way, add a fallback lookup in the same statement.
WITH up AS (
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
)
SELECT sku, quantity FROM up
UNION ALL
SELECT sku, quantity FROM product_stock
WHERE sku = 'A-100'
AND NOT EXISTS (SELECT 1 FROM up);The second branch of the UNION ALL runs a plain SELECT when the upsert returned nothing. Under concurrency, that read can lag a competing writer, so treat it as a convenience for reading the current value, not as a lock.
Conditions that are not about equality
The WHERE clause can express any rule about when the existing row may be replaced. A common one is "last write wins, but only if the incoming data is newer". It protects you from messages that arrive out of order.
INSERT INTO product_price (sku, price, currency, source_ts)
VALUES ('A-100', 10.49, 'EUR', '2026-11-27 11:00+00')
ON CONFLICT (sku) DO UPDATE
SET price = EXCLUDED.price,
currency = EXCLUDED.currency,
source_ts = EXCLUDED.source_ts
WHERE EXCLUDED.source_ts > product_price.source_ts
RETURNING sku, price, source_ts;If a delayed message with an older source_ts arrives later, the condition is false and the newer price stays. Strict > also skips an exact tie. Use >= if a re-delivery with the same timestamp should still apply. To get both behaviors, combine the rules:
WHERE EXCLUDED.source_ts > product_price.source_ts
AND (product_price.price, product_price.currency)
IS DISTINCT FROM (EXCLUDED.price, EXCLUDED.currency)Other conditions follow the same pattern. Examples are "only raise the quantity" with EXCLUDED.quantity > product_stock.quantity, or "never touch rows flagged as locked" with NOT product_stock.is_frozen.
Two different WHERE clauses
An upsert can contain two WHERE clauses that do unrelated jobs. Keep them apart.
| Position | Example | Purpose |
|---|---|---|
| After the conflict target | `ON CONFLICT (email) WHERE deleted_at IS NULL` | Index inference: picks the partial unique index that arbitrates conflicts. |
| After `SET` | `DO UPDATE SET ... WHERE old IS DISTINCT FROM new` | Row filter: decides whether the conflicting row is updated. |
DO NOTHING has no row-filter WHERE, because it never updates anything. It would have nothing to filter.
An alternative: the redundant-update trigger
PostgreSQL ships a built-in trigger function, suppress_redundant_updates_trigger(), that cancels any UPDATE which would not change the row.
CREATE TRIGGER z_min_update
BEFORE UPDATE ON product_stock
FOR EACH ROW EXECUTE FUNCTION suppress_redundant_updates_trigger();It applies to every update on the table, not just upserts, so you do not have to remember a WHERE clause. The trade-offs are the following:
- It compares the whole row byte for byte, including
updated_at. If yourSETlist assignsupdated_at = now(), every row looks changed and nothing is suppressed. - It costs a trigger call per row, which is cheaper than a write but not free.
- The documentation recommends naming it so it sorts last among
BEFORE UPDATEtriggers. That is why the example name starts withz_.
For upserts, the explicit WHERE clause is usually clearer, because it states which columns count as a change.
Common mistakes
- Using
<>on nullable columns. Changes involving NULL are skipped silently. UseIS DISTINCT FROM. - Comparing a volatile column. Including
updated_ator a version counter that always changes makes the condition always true. - Forgetting that RETURNING can be empty. Handle zero rows, or use the fallback query shown above.
- Leaving columns unqualified.
WHERE quantity <> EXCLUDED.quantityfails with an ambiguity error. - Assuming skipped rows are unlocked. They are locked until the transaction ends.
Exercise
The table productprice has columns sku (primary key), price numeric NOT NULL and discount numeric (nullable). Write the WHERE clause for an ON CONFLICT (sku) DO UPDATE that updates price and discount only when at least one of them actually changes. Why would `productprice.discount <> EXCLUDED.discount` be a bug?
Show answer
WHERE (productprice.price, productprice.discount) IS DISTINCT FROM (EXCLUDED.price, EXCLUDED.discount). With <>, a change from NULL to 0.10 (or back) evaluates to NULL, which a WHERE clause treats as not true, so that update would be skipped silently. IS DISTINCT FROM treats NULL as a comparable value.
Exercise
A statement INSERT ... ON CONFLICT (sku) DO UPDATE SET ... WHERE <condition> RETURNING sku is run for an existing sku and the condition is false. What is the command tag, how many rows does RETURNING produce, and is the existing row locked?
Show answer
The command tag is INSERT 0 0, RETURNING produces zero rows, and the existing row is still locked until the transaction ends, even though it was not updated.