How to Generate a UUID for Your Database
If you have ever built an application that stores records in a database, you have probably faced a simple but important question: how should each row be identified? A common answer is a UUID, which stands for Universally Unique Identifier. A UUID is a 128-bit label that is written as a string of hexadecimal characters and hyphens. It is designed to be unique across systems, databases, and time, without needing a central authority to hand out numbers. That makes it a practical choice when records are created in different places, merged later, or exposed through an application programming interface.
This guide explains how to generate a UUID for your database, with a focus on version 4, the random form that most developers use most of the time. You will learn the format, the steps to generate one in common tools and languages, a worked example that breaks a real-looking UUID into its parts, and the limits you should keep in mind before you rely on UUIDs for every table. The advice here is general and practical. It does not assume a particular database, and it does not require you to change your existing tables unless a UUID genuinely fits your design.
What a UUID Is
A UUID is an identifier that is meant to be unique. It is 128 bits long. When it is written as text, it uses 32 hexadecimal digits, which are the characters 0 through 9 and a through f, plus four hyphens that divide the digits into groups. The standard written form is 8-4-4-4-12, which means the first group has eight characters, the next three groups have four characters each, and the final group has twelve characters. Counting only the hexadecimal digits gives 32 characters. Counting the hyphens as well gives 36 characters in total.
There are several versions of UUIDs. Version 1 uses a timestamp and a machine identifier. Version 3 and version 5 are created by hashing a name and a namespace. Version 4 is created from random or pseudo-random data. Version 7, a newer form, combines a timestamp with random data so that identifiers sort roughly in creation order. Version 4 remains a good default for many projects because it is widely supported, easy to generate, and does not expose a timestamp or a machine address. Unless you have a clear reason to choose another version, starting with version 4 keeps the decision simple.
In a version 4 UUID, not every digit is random. The version digit is fixed at 4, and a small number of bits in another group record the variant. Those fixed bits are what allow a reader to recognise the UUID as version 4. The remaining bits, 122 of them, come from random data. That is a very large space of possible values, which is why collisions, meaning two independently generated UUIDs turning out the same, are extremely unlikely in ordinary use. You should still treat uniqueness as a practical property, not as a mathematical guarantee, and you should still use database constraints where correctness matters.
How to Generate a UUID
Generating a UUID is a short task once you know where the generator lives in your environment. The steps below give you a reliable routine you can repeat whenever you need a new identifier.
- Decide where the UUID will be created. You can generate it in your application code, in the database itself, or with a command-line or online generator for a one-off test. For production records, generating the identifier in application code or in the database is usually clearer than copying values by hand, because the value is created at the same time as the record.
- Choose version 4. If your tool asks for a version, select version 4 for a random UUID. If your tool has a function named uuid4, randomUUID, or new UUID, it is usually giving you version 4. Check the documentation for your tool if the name is not clear.
- Generate one UUID and inspect it. Before you generate thousands of values, generate one and check that it follows the 8-4-4-4-12 pattern, that the version digit is 4, and that the value is lowercase unless your project has a reason to use uppercase. Lowercase is the common convention and it avoids confusion when values are compared.
- Store it in a suitable column. The simplest option is a text or character column that holds the 36-character string. Some databases also support a native UUID type, or allow you to store the value as 16 bytes of binary data. Choose the option that your database supports and that your team can maintain. Keep the choice consistent across tables that refer to the same kind of record.
- Add a uniqueness constraint. Make the UUID column a primary key or give it a unique constraint. This is important. A constraint protects you if application code ever tries to insert a duplicate, and it documents the intention that the UUID identifies one row.
- Use the UUID as a stable reference. Once a row has a UUID, do not change it. Other tables, logs, exports, and external systems may store the same value. If the identifier changes, those references can break, and the history of the record becomes harder to follow.
Common Ways to Generate a UUID
Most modern languages and databases include a UUID generator, so you do not need to write the random logic yourself. In Python, the standard uuid module provides uuid.uuid4(), which returns a version 4 UUID. In JavaScript, many environments provide crypto.randomUUID(), which also returns a version 4 UUID. In Java, the UUID class provides a randomUUID method. In a database, PostgreSQL provides gen_random_uuid() when the pgcrypto extension is available, and other databases offer similar functions or a native UUID type. On the command line, many systems provide a uuidgen tool that prints a new UUID.
Online UUID generators can be useful for a quick test, for documentation, or for creating a sample value while you are designing a table. If you use one, treat the result as a sample, not as a secret. A UUID is an identifier, not a password, and a generated value that has been displayed in a browser or copied through a shared screen may have been seen by other people. For real records, generate the identifier inside your own application or database, where the value stays within the system you control.
Worked Example
Consider this version 4 UUID, which is a widely used example value:
550e8400-e29b-41d4-a716-446655440000
Let us break it into the 8-4-4-4-12 groups. The first group is 550e8400, which has eight characters. The second group is e29b, which has four characters. The third group is 41d4, which has four characters. The fourth group is a716, which has four characters. The fifth group is 446655440000, which has twelve characters. Together, those groups give 32 hexadecimal characters and four hyphens, for a total length of 36 characters.
Now look at the version digit. The third group is 41d4. Its first character is 4, and that is the version digit. It tells a reader that this is a version 4 UUID. The fourth group is a716. Its first character is a, which is one of the characters that marks the variant used by the common UUID standard. If you see a version 4 UUID, the first character of the fourth group will normally be 8, 9, a, or b. Those details matter when you are checking a value by hand, because they let you confirm that a generator produced the kind of UUID you expected.
Suppose you are creating a table for customers. You might define a column named id and store the example value above for one test customer. A second customer would receive a different UUID, generated separately. When your application needs to find the first customer, it can search for the full string, including the hyphens, or for the binary form if that is how you stored it. The important point is that the lookup uses the complete identifier, not part of it. Shortening a UUID, or removing hyphens in one place but not another, can cause a lookup to fail or two systems to disagree about whether two values are the same.
Another useful check is length. If a value is shorter than 36 characters, or if it has hyphens in the wrong places, it may have been truncated, pasted incorrectly, or generated by a different scheme. A quick check of the pattern, the version digit, and the total length can catch many small mistakes before they reach the database. In application code, you can also validate a UUID with a parser or a regular expression, but a simple length and pattern check is often enough for a first review.
Storing a UUID in a Database
Store a UUID as text if you want the simplest approach. A CHAR(36) column holds the full 36-character form, including hyphens. A VARCHAR column can also hold it, but a fixed-length CHAR column can make the intended format clearer. If your database has a native UUID type, that is often a better choice, because the database can validate the value and store it efficiently. Some teams store a UUID as 16 bytes of binary data to save space, because the text form is longer than the underlying 128 bits. Binary storage can be more efficient, but it can also make debugging harder, because the values are not readable in a simple query result.
Think about indexing as well. A UUID primary key is wider than a small integer key, so indexes take more space. That is not a reason to avoid UUIDs, but it is a reason to be deliberate. If a table will hold a very large number of rows and will be joined frequently, test the design with realistic data and realistic queries. In some systems, random UUIDs can also lead to more scattered index entries than sequential identifiers, because new values are not close to previous values. Version 7 UUIDs were designed partly to reduce that problem, because they sort in roughly chronological order. If index behaviour matters for your table, read your database documentation and test the options before you commit.
When you use a UUID as a foreign key, use the same column type in every table that stores it. If one table stores the UUID as text and another stores it as binary, joins and comparisons become more complicated and errors become more likely. Consistency is more valuable than a small saving in one table. Document the type you chose, and use it in new tables that refer to the same records.
Limitations
UUIDs are useful, but they are not a solution to every identification problem. First, a UUID is not a password, a secret, or an access token. Knowing a UUID should not by itself give someone access to a record. If an identifier appears in a URL, an export, or a log file, assume that it could be seen by other people. Use proper authentication and authorisation to control access, and use a separate secret for any value that must stay private.
Second, a UUID does not guarantee that a record is real, correct, or safe. A well-formed UUID can be invented by anyone, and a database will accept it if it is unique and matches the column type. Validation of the format is not validation of the record. You still need to check the data that comes with the identifier, and you still need to handle missing, duplicate, or conflicting information.
Third, UUIDs are long and hard to read aloud. They are not a good choice for identifiers that people must type, remember, or say on a telephone call. A short order number, a readable slug, or a ticket number can be better for human-facing cases, even if the database also stores a UUID internally. Use the right identifier for the audience.
Fourth, UUIDs do not solve distributed problems by themselves. If two systems generate identifiers independently, UUIDs reduce the chance of a collision, but they do not resolve what happens if the same real-world record is created twice with different UUIDs. Deduplication, reconciliation, and clear rules about which system owns a record still require design and testing.
Finally, do not use a UUID as a substitute for a meaningful ordering or timestamp. A version 4 UUID does not contain a creation time, and sorting by a random UUID does not give you the order in which rows were created. If you need to know when a record was created, store a created-at timestamp in its own column.
Frequently Asked Questions
Can I use the same UUID for two rows?
No. The point of a UUID is to identify one record. If two rows share the same UUID, lookups, updates, and joins can affect the wrong row. Use a unique constraint, generate a fresh UUID for each new record, and investigate if a duplicate ever appears, because it may point to a bug in your insertion logic.
Should I store a UUID with or without hyphens?
Either form can work, but you should choose one form and use it consistently. The standard written form includes hyphens and is 36 characters long. Removing the hyphens gives a 32-character string. If you remove hyphens in one system and keep them in another, comparisons may fail unless you normalise the values first. For clarity, many teams store the standard hyphenated form.
Is a UUID safe to expose in a URL?
A UUID in a URL is common, but it is not a security control. Treat it as an identifier that may be seen, shared, or guessed by enumeration only with great difficulty. If the resource behind the URL is private, protect it with authentication and authorisation. Do not rely on the UUID being hard to guess as your only defence.
When should I avoid UUIDs?
Consider another identifier when people must type or remember the value, when you need a short human-friendly reference, when you need records to sort in creation order and your database does not support version 7, or when a small integer key is clearly simpler and your records are created in only one place. A UUID is a tool, not a rule. Choose the identifier that fits the system, the data, and the people who will use it.
Conclusion
To generate a UUID for your database, choose version 4, use a trusted generator in your language or database, store the result in a consistent column type, and protect it with a unique constraint. Check the 8-4-4-4-12 pattern and the version digit when you are testing, use the full identifier in lookups, and remember that a UUID is an identifier, not a secret. With those habits, UUIDs can make it easier to create records in different systems, merge data, and keep stable references over time. Start with one small table, test the approach with realistic data, and only then apply the same pattern more widely.
Try a Tool
Free, in your browser — no sign-up.
Related Articles
How to Format XML So It Is Easy to Read
Learn how to format XML so it is easy to read: consistent indentation, one element per line, matched tags, unchanged data, and…
Read article →How to Build a Query String Without Breaking Your Link
Build a query string without breaking your link. Learn ?key=value, the & separator, encoding, a worked example, and why secrets stay out…
Read article →How to Convert Base64 Back to an Image
Learn how to convert Base64 back to an image, read a data URI, decode a 1 by 1 PNG example, check the…
Read article →