UUID Versions: When to Use Which
A comprehensive comparison of UUID versions (v1, v4, v5, v7) with practical guidance on choosing the right one.
UUIDs (Universally Unique Identifiers) are 128-bit identifiers used extensively in software development. But with multiple versions available, choosing the right one matters.
UUID Format
All UUIDs follow the same format: xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx where M indicates the version and N indicates the variant.
UUID Version 1: Time-based
UUID v1 uses the current timestamp and the MAC address of the machine:
f47ac10b-58cc-1bcd-8701-02c2b76aac88
^--- version 1
Pros:
- Naturally sortable by creation time
- Guaranteed unique across machines (uses MAC address)
- Good for distributed systems without coordination
Cons:
- Exposes the MAC address (privacy concern)
- Exposes creation timestamp
- Not suitable when privacy is important
UUID Version 4: Random
UUID v4 is generated entirely from random numbers:
550e8400-e29b-41d4-a716-446655440000
^--- version 4
Pros:
- No information leakage
- Simple to implement
- Most widely used version
Cons:
- Not sortable
- Poor database index performance (random distribution)
- Theoretically possible (but extremely unlikely) collisions
UUID Version 5: Name-based (SHA-1)
UUID v5 generates a deterministic UUID from a namespace and a name using SHA-1:
// Same inputs always produce the same UUID
UUID.v5('hello', UUID.DNS); // always the same
Pros:
- Deterministic: same input always produces same output
- No coordination needed for the same named resource
Cons:
- SHA-1 is no longer considered cryptographically secure
- Not unique across different names (by design)
UUID Version 7: Time-ordered (Newest)
UUID v7 is the newest addition, combining Unix timestamp with random data:
01894130-fd29-7d57-9e81-123456789abc
^timestamp^ ^--- version 7
Pros:
- Lexicographically sortable (great for database indexes)
- Includes millisecond-precision timestamp
- Better database performance than v4
- No privacy concerns (no MAC address)
Cons:
- Newer standard, less library support
- Timestamp is visible (though this is often desirable)
Choosing the Right Version
|----------|-------------------|
UUID in Databases
When using UUIDs as primary keys, consider:
1. v7 for sorted inserts: Reduces B-tree fragmentation
2. Binary storage: Store as BINARY(16) instead of CHAR(36) to save space
3. Indexing: v7 UUIDs perform much better than v4 for range queries
-- Using UUID v7 as primary key (MySQL)
CREATE TABLE users (
id BINARY(16) PRIMARY KEY,
name VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
UUID vs Alternatives
- Auto-increment: Simple but exposes count, not suitable for distributed systems
- ULID: Similar to UUID v7 but uses Crockford Base32 encoding
- CUID: Designed for horizontal scaling
- Snowflake ID: Used by Twitter, 64-bit time-ordered ID
Generate UUIDs instantly with our UUID Generator tool.