Menu

UUID v4 vs v7: Which Should You Use for Database Keys?
📰

UUID v4 vs v7: Which Should You Use for Database Keys?

DEV Community: backend·Sanjaya Sahu·6 days ago
#Qdz6ZtP0
#devtobackend#devto#dev#uuid#random
Reading 0:00
15s threshold

UUIDs are the default choice for distributed IDs, but the version matters more than most people think.

UUID v4: random

v4 is 122 random bits. It is simple and unguessable, but random inserts scatter across a B-tree index, causing page splits, cache misses and slower writes on large tables.

UUID v7: time-ordered

v7 puts a millisecond timestamp in the first 48 bits, followed by random bits. New IDs sort roughly by creation time, so inserts stay append-friendly and indexes stay compact.

v4: 3f2b8c1e-9a4d-4e6b-8f1a-2c7d5e9b0a13 v7: 0192f3a1-7c2e-7b4d-9e1f-5a6b7c8d9e0f

Enter fullscreen mode

Exit fullscreen mode

When to pick which

v4 : tokens, public identifiers, anything where you do not want to leak creation time.

v7 : primary keys on write-heavy tables, event logs, anything you often sort or paginate by time.

Common mistakes

Storing UUIDs as CHAR(36) . Use a native uuid type or BINARY(16) to halve storage.

Using v1 and leaking the MAC address and timestamp.

Assuming v7 is secret.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.