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 NOTHINGconsumes 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