UUID v7: GUIDs that sort by creation time
Posted: (EET/GMT+2)
Classic GUIDs are useful because they can be generated independently without asking the database for the next value.
But they have one annoying property when used as database keys: they do not tell you when they were created. Imagine your SELECT query would return the following:
3f0f5f8d-9b90-4e2d-a4b7-3f26a1c39c41 b18348f8-3f2a-43a3-9b4d-8f6b94dcb0d2 0a7cb7d3-91c4-45f8-bdb5-67e9db6b4f11
Which one of these was created first?
With a regular random GUID, you cannot tell from the value itself.
This is where newly-suggested UUID version 7 (UUIDv7) is interesting. UUID version 7 is a proposed UUID format that puts a timestamp at the beginning of the identifier, followed by random data.
The important practical effect is that new values sort roughly in creation order.
0182f4b7-0e80-7c36-9f62-6d7e4c5b7b01 0182f4b7-0f12-7a91-b2ce-8890b4b2f2a9 0182f4b7-0fa4-7e20-8d3f-7b5c2e40c812
Now the identifier still looks like a GUID, but sorting by the value (even as a string) also gives you a useful creation-time order.
That can matter in databases. Random GUID primary keys can cause index fragmentation because new rows are inserted into random places in the index.
Sequential integer keys avoid that problem, but they require central coordination. UUID v7 tries to keep the distributed generation benefit of GUIDs while making the values friendlier for database indexes.
For example, this kind of query becomes more natural:
SELECT TOP 100 * FROM Orders ORDER BY Id DESC;
With UUID v7-style identifiers, the newest rows are usually near the end of the index.
Keep in mind that UUID v7 is not just a timestamp. It still includes random bits, so multiple machines can generate identifiers independently.
For .NET applications in 2022, UUID v7 support is not yet built into the standard .NET APIs. If you want to experiment with it, I found about a project called uuid7-csharp in GitHub.
If you are already using database-generated integer keys (such as SQL Server's IDENTITY fields) and they work well, there is no need to change only for fashion. UUID v7 is most interesting when you need distributed ID generation, public-safe identifiers, or easier merging between systems.
Happy ordering!