UUID & ULID Generator · Tutorial
How to use UUID v7 as a database primary key
7 min readintermediateUpdated
Random UUID v4 keys scatter new rows across a database index, which slows inserts on big tables. UUID v7 keeps the benefits of UUIDs but sorts by time. This tutorial generates v7 keys, confirms their order and shows how to store them.
What you need
- The UUID & ULID Generator
- A PostgreSQL or MySQL database (optional, for the last step)
Steps
Generate a batch of v7 IDs
Set Type to UUID v7, How many to 5 and keep Keep in order within a millisecond ticked. Press Generate new. All five IDs start with the same or very similar characters, because the first 12 hex digits are the current time.
Check that they sort by time
The list is already in creation order. Paste the IDs into any sorted list or spreadsheet and the order stays the same, unlike v4, where sorting shuffles them. This is what keeps database inserts at the end of the index.
Read the time back
Paste one ID into Inspect a UUID or ULID. The tool shows Version 7 and the moment it was created, in UTC and your own time zone. Handy when you only have an ID in a log line.
Choose a column type
Store UUIDs as 16 bytes, not as 36-character text. PostgreSQL has a native
uuidtype; in MySQL useBINARY(16)with the built-in conversion functions.-- PostgreSQL CREATE TABLE orders (id uuid PRIMARY KEY, total numeric(10,2)); -- MySQL 8 CREATE TABLE orders (id BINARY(16) PRIMARY KEY, total DECIMAL(10,2)); INSERT INTO orders VALUES (UUID_TO_BIN('019a3f0c-2b80-7c4e-9a51-3d2e1f0a9b47'), 19.99);Generate keys in your application
Use the generator for test data and fixtures, and a UUID v7 library in your code for real rows, so each server creates keys locally without asking the database.
Try it yourself
Opens the UUID & ULID Generator with this tutorial's sample loaded.
Common mistakes
- Using MySQL’s UUID_TO_BIN swap flag with v7
UUID_TO_BIN(id, 1)reorders the bytes of version 1 UUIDs. A v7 UUID is already in time order, so useUUID_TO_BIN(id)without the flag.- Exposing creation times by accident
- Anyone with a v7 ID can read when it was made. For IDs shown to users where that matters, such as invitation links, use v4.
- Storing IDs as text
- A
VARCHAR(36)key is more than twice the size of a 16-byte one, and every index that refers to it grows too.
Next steps
Go back to the UUID & ULID Generator, or keep going with one of these:
FAQ
Can I mix v4 and v7 keys in one table?
Yes, they share the same format, but you lose the ordering benefit for the v4 rows. Most teams switch new rows to v7 and leave old ones as they are.
Is v7 safe to generate on many servers at once?
Yes. After the timestamp there are 74 random bits, so two servers creating IDs in the same millisecond will not collide.