Upsert Skips Unchanged Rows With WHERE
Guard upsert replay with DO UPDATE SET plus a WHERE that compares target values against EXCLUDED so unchanged rows are skipped and dead tuples avoided.
Code
-- A sync job replays the same prices every 5 minutes: unchanged values must not produce dead tuples,
-- otherwise autovacuum cannot keep up with the update rate and indexes keep ballooning
CREATE TABLE price_feed (
sku text PRIMARY KEY,
price_cents int NOT NULL,
currency text NOT NULL DEFAULT 'USD',
updated_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO price_feed (sku, price_cents) VALUES ('A-1', 1999), ('B-2', 450);
-- The upsert takes the DO UPDATE path, but a WHERE compares the target row with the proposed values:
-- unchanged rows skip the write and never appear in RETURNING
INSERT INTO price_feed AS target (sku, price_cents)
VALUES ('A-1', 1999), ('B-2', 500)
ON CONFLICT (sku) DO UPDATE
SET price_cents = EXCLUDED.price_cents,
updated_at = now()
WHERE target.price_cents IS DISTINCT FROM EXCLUDED.price_cents
RETURNING sku, price_cents;
-- Verify: updated_at refreshed only for B-2; A-1 keeps its original row version
SELECT sku, price_cents, updated_at FROM price_feed ORDER BY sku;Inside the snippet
The file runs SELECT / INSERT / UPDATE / CREATE statements, touching price_feed, set and excluded.price_cents.
Breaking the statements into their working parts: a WHERE clause constraining which rows the statement operates on; an ORDER BY that fixes the output order; an upsert guard (ON CONFLICT/MERGE) that turns insert-or-update into one atomic statement; a RETURNING clause that hands the affected rows back to the caller; a DISTINCT qualifier that collapses duplicate rows; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns.
Putting it to use
Run the statement against the price_feed table.
Core lines
INSERT INTO price_feed AS target (sku, price_cents)
VALUES ('A-1', 1999), ('B-2', 500)
ON CONFLICT (sku) DO UPDATE
SET price_cents = EXCLUDED.price_cents,
updated_at = now()
WHERE target.price_cents IS DISTINCT FROM EXCLUDED.price_cents
RETURNING sku, price_cents;
CREATE TABLE price_feed (
sku text PRIMARY KEY,
price_cents int NOT NULL,
currency text NOT NULL DEFAULT 'USD',
updated_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO price_feed (sku, price_cents) VALUES ('A-1', 1999), ('B-2', 450);
Interactive Tools for This Topic
FAQ
- Which objects does the SQL touch?
- `price_feed`, `set`, `excluded.price_cents`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.