← Back to SQL, page 20

sql-0382 · Medium mid

Why do PostgreSQL sequences leave gaps in id values, and should that be fixed?

nextval() is never rolled back, so a failed or rolled-back insert consumes a value, and cached sequence values can be lost on a crash. Gaps are normal and harmless for surrogate keys. When gap-free numbers are legally required, such as invoice numbers, generate them from a counter row updated inside the same transaction, accepting that it serialises inserts.

Full answer
sql
BEGIN;
SELECT nextval('demo_seq');
ROLLBACK;
SELECT nextval('demo_seq') AS next_value;
next_value
2

The value 1 was taken inside a transaction that rolled back, yet the next call returns 2. Sequences are deliberately non-transactional so concurrent inserts never wait for each other's commit.

Other sources of gaps:

  • INSERT ... ON CONFLICT DO NOTHING consumes a value even when no row is inserted.
  • Sequence caching per session (CACHE 20) discards unused values when the session ends.
  • Deleted rows leave holes.

If a business needs consecutive numbers, keep invoice_counters(year, last_no) and run UPDATE invoice_counters SET last_no = last_no + 1 WHERE year = 2026 RETURNING last_no in the invoice transaction. A rollback then also rolls back the number. SQLite's INTEGER PRIMARY KEY without AUTOINCREMENT can reuse the largest deleted rowid instead of leaving a gap, which is a different behaviour again.

Key points

  • nextval is not rolled back
  • Gaps come from rollbacks, conflicts and caching
  • Gaps are fine for surrogate keys
  • Gap-free numbering needs a counter row in the transaction

Common mistakes

  • Reusing ids to fill gaps
  • Using MAX(id) + 1, which races

Follow-ups

  • Why is MAX(id) + 1 unsafe?
  • How does SQLite AUTOINCREMENT differ?

Tips

  • Show the rollback case