Why Generated Row Numbers Can Have Gaps

A sequence or identity mechanism can supply distinct values without promising that every integer appears in saved rows.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace an unsuccessful insertion
  2. Use a count for totals
  3. Trace allocation and rollback as separate events
  4. Avoid turning technical IDs into another business guarantee

Trace an unsuccessful insertion

A database can allocate number 12 before an insertion fails. Another row then uses 13. Allocation and successfully committed rows are different observations. Partial success and failure explain the general distinction.

Use a count for totals

The highest ID does not reliably count rows because of gaps, deletions, and alternate insertions. Row granularity identifies which population should be counted.[1][2]

Trace allocation and rollback as separate events

A transaction can reserve generated ID 10 and then roll back. In PostgreSQL, a sequence allocation generally is not undone by that rollback. A later committed item may receive 11 while 10 remains unused. See transaction commit and rollback.

Transaction A obtains 10 → rolls back
Transaction B obtains 11 → commits
Stored IDs show a gap
Row count needs its own query

Avoid turning technical IDs into another business guarantee

A generated primary key identifies a row. Counts and commit order require their own evidence. If the application requires an audited sequence, design and test that requirement separately under concurrency.

References

  1. PostgreSQL Global Development Group, Data Definition ↩
  2. PostgreSQL Global Development Group, SQL Language Tutorial ↩