Sub topic 12
Pitfalls: NULLs, sequence gaps, and dead tuples
This chapter assumes you can write INSERT ... ON CONFLICT DO NOTHING and DO UPDATE with EXCLUDED. It also assumes you know what a unique index is and how to read a query result in psql. Upserts work correctly in the cases covered earlier. The three problems below don't raise errors, so they usually show up later as duplicate rows, odd ids, or a table that keeps growing.
Pitfall 1: NULLs never conflict
A unique constraint treats every NULL as different from every other NULL, following the SQL standard. Two rows with NULL in a unique column do not violate the constraint, so ON CONFLICT never fires for them. The upsert inserts a new row every time.
CREATE TABLE price (
sku text NOT NULL,
region text,
amount numeric(10,2) NOT NULL,
UNIQUE (sku, region)
);
INSERT INTO price (sku, region, amount)
VALUES ('A-100', NULL, 9.99)
ON CONFLICT (sku, region) DO UPDATE
SET amount = EXCLUDED.amount;
INSERT INTO price (sku, region, amount)
VALUES ('A-100', NULL, 10.49)
ON CONFLICT (sku, region) DO UPDATE
SET amount = EXCLUDED.amount;
SELECT sku, region, amount FROM price;The query returns two rows, 9.99 and 10.49. Both statements succeeded and neither updated anything, because (A-100, NULL) never matches an existing key. The table now holds two "global" prices for one product.
You have three ways to fix this. Pick one when you design the table, because the conflict target must match whichever you choose.
Option A: NULLS NOT DISTINCT (PostgreSQL 15 and later)
NULLS NOT DISTINCT tells the unique constraint to treat NULLs as equal.
CREATE TABLE price_v2 (
sku text NOT NULL,
region text,
amount numeric(10,2) NOT NULL,
UNIQUE NULLS NOT DISTINCT (sku, region)
);
INSERT INTO price_v2 (sku, region, amount)
VALUES ('A-100', NULL, 9.99)
ON CONFLICT (sku, region) DO UPDATE
SET amount = EXCLUDED.amount;Running this statement again with a different amount now updates the existing row. The conflict target stays an ordinary column list. This is the simplest fix when your server version supports it.
Option B: forbid NULL
If "no region" can be a real value such as an empty string or 'global', declare the column NOT NULL with a default. The constraint then never sees a NULL. This works on every version, but the sentinel value can leak into reports and joins, so document it.
Option C: an expression index
On older versions, index a NULL-free expression. The conflict target must repeat the expression, with extra parentheses around it, so that PostgreSQL can infer the index.
CREATE TABLE price_v3 (
sku text NOT NULL,
region text,
amount numeric(10,2) NOT NULL
);
CREATE UNIQUE INDEX price_v3_sku_region_idx
ON price_v3 (sku, (coalesce(region, '')));
INSERT INTO price_v3 (sku, region, amount)
VALUES ('A-100', NULL, 9.99)
ON CONFLICT (sku, (coalesce(region, ''))) DO UPDATE
SET amount = EXCLUDED.amount;The drawback is that NULL and '' now count as the same key. Make sure that matches your data.
Pitfall 2: sequence gaps
A sequence hands out numbers for serial and identity columns. Calling nextval() is not transactional, so a number that has been handed out is never given back. That has a consequence for upserts. PostgreSQL computes the proposed row, including column defaults, before it knows whether the row conflicts. The default nextval() runs first, and the number is consumed even if the row is then skipped or turned into an update.
CREATE TABLE tag (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL UNIQUE,
hits integer NOT NULL DEFAULT 0
);
INSERT INTO tag (name) VALUES ('sql') ON CONFLICT (name) DO NOTHING;
INSERT INTO tag (name) VALUES ('sql') ON CONFLICT (name) DO NOTHING;
INSERT INTO tag (name) VALUES ('sql') ON CONFLICT (name) DO NOTHING;
INSERT INTO tag (name) VALUES ('pg') ON CONFLICT (name) DO NOTHING;
SELECT id, name FROM tag ORDER BY id;The result is (1, sql) and (4, pg). Two skipped inserts consumed ids 2 and 3. The same thing happens with DO UPDATE. An upsert job that runs every minute against a table with a few thousand keys can burn through millions of identity values a year.
Why this matters
- A
bigintidentity will not run out in practice. A 32-bitserialorintegeridentity can, because each skipped upsert uses up a value. If a hot table is upserted often, usebigint. - Gaps are normal. Rolled-back transactions and crashes also leave gaps. Do not build logic that assumes ids are consecutive, such as "the previous row is
id - 1" or "the row count equals the max id". - Resetting the sequence with
setvalto close the gaps is risky. A concurrent insert can then collide with a value you re-issue.
Reducing the waste
If most upserts are expected to hit existing rows, an UPDATE first and an INSERT only on a miss avoids the burn. But that two-step pattern brings back the race conditions that ON CONFLICT was designed to remove. In most systems it is better to accept the gaps and use a wide integer type.
Pitfall 3: dead tuples from no-op updates
PostgreSQL uses multiversion concurrency control (MVCC). An UPDATE never changes a row in place. It writes a new row version, called a tuple, and marks the old one as dead. Dead tuples take up space until VACUUM removes them.
The DO UPDATE branch is an ordinary update. When the key exists, it writes a new tuple even if every new value equals the old one. A job that re-imports the same 100,000 rows each hour creates 100,000 dead tuples each hour. It also writes WAL, may update indexes, and fires update triggers.
You can watch the effect in the statistics view. This example reuses the product_stock table from earlier in the tutorial.
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity,
updated_at = now();
SELECT relname, n_live_tup, n_dead_tup, last_autovacuum
FROM pg_stat_user_tables
WHERE relname = 'product_stock';Repeat the statement a few hundred times, from a client loop or a script, and n_dead_tup climbs while n_live_tup stays the same. The counters can lag by a second or so, and they are estimates, so check again after a short wait.
The fix: skip rows that did not change
Add a WHERE clause to the DO UPDATE branch, as in the conditional-update chapter. When the condition is false, PostgreSQL skips the update, so no new tuple is written.
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;Use IS DISTINCT FROM rather than <>. Comparing with <> yields NULL when either side is NULL, and a NULL condition counts as false, so a change from NULL to a value would be skipped. For tables with many columns, compare whole rows:
WHERE (product_stock.quantity) IS DISTINCT FROM (EXCLUDED.quantity)For wide tables, compare only the columns that your SET clause changes. Do not include updated_at in the comparison, because it changes on every run and would defeat the filter.
Other ways to keep bloat down
- Heap-only tuples (HOT). When an update changes no indexed column and the page has free space, PostgreSQL can write the new tuple without touching any index, and later cleanup is cheap. Leave room with
ALTER TABLE product_stock SET (fillfactor = 80);. The setting applies to new pages and to rewritten ones. - Autovacuum tuning. On a table that is upserted heavily, lower the trigger threshold:
ALTER TABLE product_stock SET (autovacuum_vacuum_scale_factor = 0.02);. The default of 0.2 waits until 20% of the rows are dead. - Avoid indexing columns that change often. Every index on
updated_atrules out HOT updates for that table. - Use DO NOTHING when the data is immutable. If you only need to make sure a row exists,
DO NOTHINGwrites no new tuple for the conflicting row.
How the three pitfalls fit into the upsert path
Summary of pitfalls
| Pitfall | Symptom | Cause | Remedy |
|---|---|---|---|
| NULL in key | Duplicate rows, no conflict | Unique indexes treat NULLs as distinct | `NULLS NOT DISTINCT`, `NOT NULL`, or an expression index |
| Sequence gaps | Ids skip numbers, integer overflow risk | Defaults are evaluated before the conflict check | Use `bigint`, accept gaps |
| Dead tuples | Table and index bloat, high WAL volume | `DO UPDATE` writes a new tuple even for equal values | `WHERE ... IS DISTINCT FROM`, fillfactor, autovacuum tuning |
| Triggers | Audit rows for unchanged data | Update triggers run for no-op updates | The same `WHERE` filter |
A checklist before shipping an upsert
- Can any column in the conflict target be NULL? If so, choose one of the three NULL fixes and test that a second run updates the row.
- Is the id column
bigint? Estimate how many upserts per day will consume values without inserting. - Does the
DO UPDATEbranch have aWHEREclause that skips unchanged rows? - Does
updated_ator a version counter change only when real data changes? - Does the table have a sensible autovacuum setting for its write rate?
Exercise
A table has UNIQUE (customer_id, coupon_code) where coupon_code can be NULL. An import runs INSERT ... ON CONFLICT (customer_id, coupon_code) DO UPDATE ... nightly, and the table grows by the full import size each night for rows with no coupon. Why, and how do you fix it on PostgreSQL 15 or later?
Show answer
Rows with a NULL coupon_code never conflict, because a unique constraint treats NULLs as distinct, so every run inserts new rows. Recreate the constraint as UNIQUE NULLS NOT DISTINCT (customer_id, coupon_code), after removing the existing duplicates. The same conflict target then matches the NULL rows and updates them.
Exercise
A table has an identity primary key and a unique name column. You run INSERT ... ON CONFLICT (name) DO NOTHING 10 times with an existing name, and then insert a new name. The new row gets an id 10 higher than the previous maximum. Is this a bug, and what should you do about it?
Show answer
It is not a bug. The default nextval() runs for each proposed row before the conflict is detected, and sequence values are never returned. Do not rely on consecutive ids. Use a bigint identity so the burned values cannot overflow the column, and do not reset the sequence to close the gap.
Exercise
Your hourly job upserts the same 50,000 rows with DO UPDATE SET quantity = EXCLUDED.quantity, updated_at = now(). Most quantities do not change, and n_dead_tup grows quickly. Write the clause that reduces the dead tuples, and explain why <> is a poor choice for it.
Show answer
Add WHERE product_stock.quantity IS DISTINCT FROM EXCLUDED.quantity to the DO UPDATE branch. Rows with an unchanged quantity are then skipped and write no new tuple. The <> operator returns NULL if either side is NULL, and a NULL condition counts as false, so a change from NULL to a value, or the reverse, would be silently skipped.