Lesson 3 of 16
10. Unique ID Generation

10.2 What's wrong with auto-increment?

3 min read+10 XP

At the bank: With one branch, the token machine is perfect: simple, short numbers, always in order, never repeated.

In the system: Auto-increment (SERIAL, IDENTITY, AUTO_INCREMENT) makes the database hand out the next number on every insert. With one database, it's excellent:

  • Unique, guaranteed by the database.
  • Short (fits in a 64-bit integer, or even 32-bit at first).
  • Sorted: new rows go at the end of the primary-key index, which databases handle very efficiently.
  • No extra system to run.

For a single database, use it. Many very large products ran on auto-increment IDs for years. The problems only start when you need IDs from more than one place (10.3), or when IDs are shown to the public (10.9).

One gotcha even on one database: auto-increment numbers can have gaps. A rolled-back transaction or a crash may skip numbers. Never rely on IDs being continuous; never use them to count rows.

Memory code: "One machine, one counter: perfect, until there are two."