← Back to SQL, page 18

sql-0346 · Medium mid

Should a new table use an auto-incrementing integer or a UUID as its primary key?

Integers are small, fast to index and easy to read, but they are guessable and need a central generator. UUIDs can be generated anywhere and hide row counts, at the cost of larger indexes; random UUIDv4 values also scatter inserts across the index. Time-ordered UUIDv7 gives most UUID benefits with insert locality.

Full answer

Considerations:

  • Size: bigint is 8 bytes; a UUID is 16 bytes in a native type (36 if stored as text, which should be avoided). Every foreign key and secondary index carries the key.
  • Insert pattern: sequential keys append to the right edge of the B-tree. Random UUIDv4 values land anywhere, causing more page splits and cache misses on large tables.
  • Generation: UUIDs can be created by clients, offline devices or several services without coordination, which helps merges and idempotent inserts.
  • Exposure: sequential ids in URLs reveal growth and invite enumeration; a UUID or a separate public id avoids that.

A common compromise is a bigint primary key internally plus a unique random public id for URLs, or UUIDv7 as the single key. PostgreSQL 18 adds a built-in uuidv7() function; on older versions it comes from an extension or the application (stated from documentation, not run here).

Key points

  • bigint keys are compact and sequential
  • UUIDs allow decentralised generation
  • Random UUIDs hurt index locality
  • UUIDv7 is time ordered
  • Store UUIDs in a native type, not text

Common mistakes

  • Storing UUIDs as 36-character text
  • Exposing sequential ids where enumeration matters

Follow-ups

  • How would you add a public id to an existing table?
  • Do UUID keys prevent all enumeration attacks?

Tips

  • Weigh size, locality and generation