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;| type | text_length |
|---|---|
| uuid | 36 |
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