← Back to SQL, page 9

sql-0174 · Medium mid

When would you choose a UUID primary key over an auto-incrementing integer?

UUIDs can be generated anywhere without coordination, are safe to expose in URLs without revealing counts, and make merging data from several systems easy. Integers are smaller, faster to index and easier to read. Random UUIDs (v4) scatter inserts across a B-tree index; time-ordered UUIDs (v7) reduce that cost.

Full answer

Integer keys use 4 or 8 bytes and grow in order, so inserts append to the end of the index. They also leak information: /orders/1042 suggests roughly a thousand orders, and anyone can try 1043.

UUIDs use 16 bytes (36 as text). Clients, offline devices or several services can create them without asking the database, which helps with replication and imports.

Costs to mention:

  • Every secondary index and foreign key also stores the larger key.
  • Random v4 values land anywhere in the index, so inserts touch more pages and caches work less well.
  • UUIDv7 puts a timestamp first, so new keys are mostly increasing.

PostgreSQL has a native uuid type and gen_random_uuid():

sql
SELECT pg_typeof(gen_random_uuid()) AS type, length(gen_random_uuid()::text) AS text_length;
typetext_length
uuid36

SQLite has no UUID type or built-in generator; store 16-byte BLOBs or text generated by the application. A common compromise is an integer primary key for joins plus a unique public UUID column for external use.

Key points

  • UUIDs can be created without coordination
  • Integers are smaller and insert in order
  • Random UUIDs fragment B-tree inserts; v7 is time-ordered
  • Exposed integer ids reveal counts and invite guessing
  • Integer internal key plus public UUID is a common compromise

Common mistakes

  • Storing UUIDs as 36-character text in large tables
  • Using sequential ids in public URLs without access checks

Follow-ups

  • How does key size affect secondary indexes?
  • How would you migrate from integer to UUID keys?

Tips

  • Give both sides and a compromise