What Is a UUID?
A UUID (Universally Unique Identifier), also known as a GUID (Globally Unique Identifier), is a 128-bit identifier standardized by RFC 4122. It is represented as a 32-character hexadecimal string in the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx β five groups separated by hyphens containing 8, 4, 4, 4 and 12 hex characters respectively. UUIDs are designed to be globally unique without requiring a central authority to coordinate assignment.
The probability of generating two identical UUID v4s is astronomically low β approximately 1 in 5.3 Γ 10Β³βΆ. This makes UUIDs suitable for use as database primary keys, API identifiers, session tokens, file names and any other context where uniqueness across distributed systems is required.
UUID Versions Explained
UUID v4 β Random
UUID v4 is the most commonly used version. It is generated using cryptographically random bytes β 122 bits of randomness with 6 bits reserved for version and variant information. Use v4 for general-purpose IDs in databases, REST APIs, microservices and session management.
UUID v1 β Time-Based
UUID v1 incorporates the current timestamp (100-nanosecond intervals since 15 October 1582) and the MAC address of the generating machine. This makes v1 UUIDs time-sortable but also potentially privacy-sensitive since they embed the machine's MAC address.
UUID v5 β Name-Based (SHA-1)
UUID v5 is deterministic β the same namespace UUID and name string always produce the same UUID. It is generated by computing the SHA-1 hash of the concatenation of a namespace UUID and a name string. This is useful for generating consistent IDs for the same resource across different systems.
ULID, CUID2 and Nano ID β Modern Alternatives
ULID (Universally Unique Lexicographically Sortable Identifier) encodes a 48-bit millisecond timestamp followed by 80 bits of randomness, encoded in Crockford's Base32. ULIDs sort chronologically as strings, making them excellent database primary keys. CUID2 is a collision-resistant, URL-safe, fingerprint-free identifier designed for horizontal scaling. Nano ID generates compact random IDs using a customizable alphabet and length, making it ideal for short URLs, invite codes and any context where a shorter identifier is preferred.
UUID Best Practices for Databases
When using UUIDs as database primary keys, prefer ULID or UUID v7 over v4 for write-heavy tables β random v4 UUIDs cause index fragmentation in B-tree indexes because new records insert at random positions rather than at the end. For PostgreSQL, use the uuid column type and the gen_random_uuid() function. For MySQL/MariaDB, store UUIDs in a BINARY(16) column using UUID_TO_BIN() with the swap_flag=1 parameter to improve index locality.