Sub topic 11
Why gaps happen
This chapter assumes you can create an identity column, insert rows, and use COMMIT and ROLLBACK. It explains why the IDs in an identity column are not a gapless counter, and what to do when you need one.
The rule behind every gap
An identity column takes its values from a sequence. A sequence is a special database object that hands out the next number each time something calls nextval. It deliberately sits outside transaction control:
- A value, once handed out, is never taken back.
- A rollback does not rewind the sequence.
- Other sessions never wait for your transaction to finish before they get their own numbers.
This is a design choice. If a rollback gave numbers back, every insert would have to lock the sequence until commit. Concurrent inserts would then queue behind each other. PostgreSQL gives up gaplessness so that many sessions can insert at once.
The guarantee you do get is that a sequence never hands out the same value twice, apart from a CYCLE wrap-around. Values are unique and, within one session, increasing. They are not contiguous.
Gap cause 1: rolled-back transactions
When you insert a row, the column default calls nextval before the row is stored. If the transaction later rolls back, the row disappears but the number stays used.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer text NOT NULL
);
INSERT INTO orders (customer) VALUES ('Ada') RETURNING id;
BEGIN;
INSERT INTO orders (customer) VALUES ('rolled back');
ROLLBACK;
INSERT INTO orders (customer) VALUES ('kept') RETURNING id;The first insert returns 1. The rolled-back insert consumed 2. The last insert returns 3, so 2 is a permanent gap.
Gap cause 2: failed statements
You do not need an explicit ROLLBACK. Any statement that fails after the default has been evaluated wastes a number. The most common case is a unique violation.
CREATE TABLE invoices (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer text NOT NULL UNIQUE
);
INSERT INTO invoices (customer) VALUES ('Ada'); -- id 1
INSERT INTO invoices (customer) VALUES ('Ada'); -- fails, burns id 2
-- ERROR: duplicate key value violates unique constraint "invoices_customer_key"
INSERT INTO invoices (customer) VALUES ('Grace'); -- id 3
INSERT INTO invoices (customer) VALUES ('Grace')
ON CONFLICT (customer) DO NOTHING; -- burns id 4, inserts nothing
INSERT INTO invoices (customer) VALUES ('Linus'); -- id 5
SELECT id, customer FROM invoices ORDER BY id;The final query returns IDs 1, 3 and 5. The same thing happens with other failures, such as a NOT NULL violation on a different column, a check constraint failure, or a foreign key failure. PostgreSQL computes the default value first and checks constraints afterward.
INSERT ... ON CONFLICT DO NOTHING deserves attention. If you run it in a loop or on a schedule against mostly duplicate data, it can consume a large number of IDs while inserting few rows. That makes a smallint or integer column run out much sooner than the row count suggests.
Gap cause 3: concurrent transactions
Two sessions can interleave. Each takes a number as soon as it runs its insert. If one session rolls back, its number is lost, even though the other session's number is committed.
This diagram also shows a second effect. IDs are assigned in the order sessions call nextval, not in the order they commit. Suppose session A had committed instead of rolling back. For a short time a reader could see row 6 without row 5, and row 5 would appear later. Remember this when you write code that polls for id > last_seen_id. Such a loop can permanently skip a row that commits late.
Gap cause 4: CACHE
The CACHE option on a sequence makes each session reserve a block of numbers in advance. Identity columns default to CACHE 1, which means no pre-allocation. If you raise it, as shown below, gaps get larger.
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY (CACHE 50) PRIMARY KEY,
payload text NOT NULL
);With CACHE 50, a session that inserts one row reserves 50 numbers and uses one. When that session disconnects, the other 49 are discarded. Two sessions that insert alternately will also produce IDs that look out of order: session A gets 1 to 50 and session B gets 51 to 100, so B's first row has a higher ID even if it was inserted earlier. A larger cache reduces contention on very busy sequences. For most tables the default is correct.
Gap cause 5: crashes and failover
PostgreSQL does not write to the transaction log (WAL) on every nextval. To save I/O, it logs the sequence state about 32 values ahead of what it has actually handed out. After a crash, recovery restarts the sequence from the logged position. This can skip up to 32 numbers. The same can happen after you promote a standby server, because the standby only knows the logged state.
You cannot configure this away. It is another reason not to build logic that assumes id = previous id + 1.
Gap cause 6: deletes
Deleting rows also leaves holes. Deleted rows leave their IDs unused forever. A table with IDs 1 to 100 and a row deleted at 40 has a gap, and a new insert does not reuse 40. This is intended behavior. Reusing IDs would make old references, such as logs, URLs and external systems, point at the wrong row.
Summary of causes
| Cause | Why the number is lost | Can you prevent it? |
|---|---|---|
| `ROLLBACK` | `nextval` is not transactional | No |
| Failed statement | The default is evaluated before constraint checks | Only by avoiding failures |
| `ON CONFLICT DO NOTHING` | The default is evaluated before the conflict is found | No |
| `CACHE` greater than 1 | Unused reserved numbers are discarded | Keep `CACHE 1` |
| Crash or failover | Sequence state is logged about 32 values ahead | No |
| `DELETE` | The row is gone but its ID is never reissued | No |
What not to do
Two tempting fixes are both wrong.
First, do not reset the sequence to close gaps. Running setval or RESTART to a lower value risks handing out an ID that already exists. With GENERATED BY DEFAULT, or after an OVERRIDING SYSTEM VALUE insert, nothing stops the duplicate until the primary key rejects it.
Second, do not compute the next ID yourself with SELECT max(id) + 1. Two concurrent sessions read the same maximum and collide. Even with a lock, it does not scale.
-- Wrong: racy and slow
INSERT INTO orders (id, customer)
OVERRIDING SYSTEM VALUE
SELECT coalesce(max(id), 0) + 1, 'Ada' FROM orders;When you need gapless numbers
Some requirements do demand numbers with no gaps, such as legally mandated invoice numbering in some jurisdictions. A sequence cannot provide this. Use a counter table and accept that writers will take turns.
CREATE TABLE invoice_counter (
last_number bigint NOT NULL
);
INSERT INTO invoice_counter VALUES (0);
BEGIN;
UPDATE invoice_counter
SET last_number = last_number + 1
RETURNING last_number;
-- use the returned number in the invoice insert, then:
COMMIT;The UPDATE takes a row lock that is held until the transaction ends. If the transaction rolls back, the counter update rolls back too, so the number is reused. The price is that all invoice-creating transactions are serialized. Keep those transactions short.
A common compromise is to keep the identity column as the internal primary key and add a separate gapless invoice_number column that is assigned only at the moment an invoice is finalized.
Practical guidance
- Use
count(*)to count rows, andORDER BYa timestamp column such ascreated_atfor ordering by time. - Pick a column type with room to spare. Failed inserts and
ON CONFLICT DO NOTHINGburn IDs faster than rows accumulate, so abigintis the safer default. - Never expose the assumption "ID 1042 follows ID 1041" in application logic or reports.
- If an auditor asks about missing numbers, explain that the numbers were allocated and never committed. A counter table is the answer only when the requirement is genuine.
Exercise
A table has id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY and a UNIQUE constraint on email. A nightly job runs INSERT ... ON CONFLICT (email) DO NOTHING for 2 million rows, and 99% of them already exist. After 400 nights the table holds only about 25,000 more rows, yet inserts start failing with "nextval: reached maximum value of sequence". Explain why, and name two changes that would fix or reduce the problem.
Show answer
Each attempted insert evaluates the identity default and calls nextval before PostgreSQL detects the conflict, so even skipped rows consume an ID. The job burns about 2 million IDs per night, so 400 nights consume about 800 million, and the job exhausts the integer limit of about 2.1 billion within roughly 1,000 nights. In this case the sequence reached its maximum sooner, because the job burned IDs faster than that estimate. Fixes: change the column and sequence to bigint, or filter out existing rows before inserting, for example with INSERT ... SELECT ... WHERE NOT EXISTS (...) or by loading into a staging table first, so far fewer IDs are consumed.
Exercise
Session A runs BEGIN; INSERT INTO orders (customer) VALUES ('x'); and receives ID 10 but has not committed. Session B then inserts and commits ID 11. A poller reads WHERE id > last_seen and sets last_seen = 11. Session A then commits. What goes wrong, and why?
Show answer
The poller never sees ID 10. Sequence values are assigned in the order of nextval calls, not in commit order. The row with ID 10 became visible only after the poller had already moved past it, so id > 11 skips it permanently. A safer design tracks processed rows by a different mechanism, such as a status column, or re-reads a window of recent IDs.