Sub topic 12
Pitfalls: NULLs, Sequence Gaps, and Dead Tuples
Assume you know basic SELECT, INSERT, and UPDATE, and understand primary keys and unique constraints. This chapter focuses on behavior that can surprise you after an upsert appears to work.
`NULL` is not an ordinary duplicate value
PostgreSQL usually treats NULL as unknown, not as equal to another NULL. Therefore, a normal unique constraint allows multiple rows whose constrained column is NULL.
CREATE TABLE customer_contact (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text UNIQUE
);
INSERT INTO customer_contact (email) VALUES (NULL);
INSERT INTO customer_contact (email) VALUES (NULL);
SELECT id, email
FROM customer_contact;Both inserts succeed. The unique constraint prevents two equal non-null emails, but it does not consider two nulls equal.
PostgreSQL 15 and later support NULLS NOT DISTINCT when you want nulls to conflict:
CREATE TABLE preferred_email (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text
);
CREATE UNIQUE INDEX preferred_email_unique
ON preferred_email (email) NULLS NOT DISTINCT;
INSERT INTO preferred_email (email) VALUES (NULL);
INSERT INTO preferred_email (email)
VALUES (NULL)
ON CONFLICT (email) DO UPDATE
SET email = EXCLUDED.email;The second statement finds the existing null row because this index treats nulls as equal. Use this option only when the application rule really is “at most one missing value.”
A different design is often clearer. If every customer must have an email, declare the column NOT NULL. If only active records must have unique emails, use a partial unique index and make the conflict target match its predicate.
Sequence gaps are normal
Identity columns and serial columns use sequences to generate values. PostgreSQL obtains a sequence value before it completes the insert and before ON CONFLICT decides whether to insert, update, or do nothing.
As a result, an upsert can consume an ID without creating a new row.
CREATE TABLE inventory_item (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sku text UNIQUE NOT NULL,
quantity integer NOT NULL
);
INSERT INTO inventory_item (sku, quantity)
VALUES ('A-100', 5);
INSERT INTO inventory_item (sku, quantity)
VALUES ('A-100', 7)
ON CONFLICT (sku) DO NOTHING;
SELECT id, sku, quantity
FROM inventory_item;The table might contain only id = 1, while the identity sequence has already advanced to 3. The skipped value is not an error. Rollbacks, failed inserts, and concurrent transactions can also create gaps.
Do not use an identity column as a gap-free invoice number or display counter. If a business process requires consecutive numbers, model that requirement separately with a carefully controlled allocation process. For ordinary primary keys, gaps are useful because sequences prioritize concurrency and speed over consecutiveness.
Also remember that DO NOTHING returns no row for a conflict. With DO UPDATE, you can request the resulting row:
INSERT INTO inventory_item (sku, quantity)
VALUES ('A-100', 7)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity
RETURNING id, sku, quantity;Updates create dead tuples
PostgreSQL uses multiversion concurrency control, or MVCC. An UPDATE creates a new row version instead of overwriting the old version immediately. After transactions no longer need the old version, it becomes a dead tuple. Vacuum later reclaims its space.
Therefore, an upsert that repeatedly executes DO UPDATE can create dead tuples even when the value does not change:
INSERT INTO inventory_item (sku, quantity)
VALUES ('A-100', 7)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity;If this statement runs frequently, avoid unnecessary updates with a WHERE clause:
INSERT INTO inventory_item (sku, quantity)
VALUES ('A-100', 7)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity
WHERE inventory_item.quantity IS DISTINCT FROM EXCLUDED.quantity
RETURNING id, sku, quantity;IS DISTINCT FROM handles nulls safely. When the existing and proposed values are equal, PostgreSQL skips the update. The row is then not returned by RETURNING, because no insert or update occurred.
Autovacuum normally cleans up dead tuples. High-volume upsert workloads may still require monitoring table and index size, vacuum activity, and transaction duration. Long-running transactions can prevent cleanup.
flowchart TD
A[Upsert arrives] --> B{Unique conflict?}
B -->|No| C[Insert new row version]
B -->|Yes| D{Values changed?}
D -->|No with WHERE| E[Skip update]
D -->|Yes| F[Create new row version]
F --> G[Old version becomes dead tuple]
G --> H[Vacuum reclaims space]Practical checklist
- Use
NOT NULLwhen a key value must exist. - Use
NULLS NOT DISTINCTwhen nulls must conflict. - Treat generated IDs as unique identifiers, not consecutive numbers.
- Add a
WHEREcondition to skip unchanged updates. - Monitor vacuum and table growth for high-frequency upserts.
Exercise
An upsert uses a unique email column, but two rows with NULL email are inserted. Why can both rows exist, and what PostgreSQL 15+ index option makes them conflict?
Show answer
Normal unique indexes treat NULL values as distinct, so both rows can exist. Define the unique index with NULLS NOT DISTINCT to make NULL values conflict.