Generate UUIDs
Generate a named UUID (v3 or v5) from a namespace and a name
Named UUIDs are deterministic: the same namespace plus the same name always produces the same UUID. Use v5 (SHA-1) for new work; v3 (MD5) exists only for compatibility with older systems. Everything is hashed in your browser.
—
www.widgets.com with the DNS namespace: v3 gives 3d813cbb-47fb-32ba-91df-831e1593ac29 and v5 gives 21f7f8de-8051-5b89-8680-0195ef798b6a — the reference values published in the RFC.Parse and decode a UUID — version, timestamp and node
Paste any UUID in any common form — with or without hyphens, upper or lower case, braced or prefixed with urn:uuid:. The parser normalises it and reads the fields out of the 128 bits.
Output formats
Pick the format that fits your stack. All formats below are produced from the same UUID.
- Standard (hyphenated):
123e4567-e89b-42d3-a456-426614174000 - Uppercase:
123E4567-E89B-42D3-A456-426614174000 - No hyphens:
123e4567e89b42d3a456426614174000 - Braces:
{123e4567-e89b-42d3-a456-426614174000} - URN:
urn:uuid:123e4567-e89b-42d3-a456-426614174000
Generate a UUID in your language
How to generate a UUID in MySQL, PostgreSQL, Excel and more
Same 128-bit identifier, different platform. Each recipe below is self-contained — copy it as-is. All of them use the platform's own primitives, so nothing leaves your machine.
How to generate a UUID in MySQL 8 / MariaDB
UUID() returns an RFC 4122 version-1 UUID (time-based, derived partly from the host). MySQL has no built-in v7, so generate v7 in your application if you need time-ordered keys. Store UUIDs as BINARY(16) rather than CHAR(36) to reduce storage size. For v1 only, pass the swap flag (1) on both write and read to reorder the time fields. For application-generated v7, use 0 (or omit the flag) because its timestamp is already first. The binary conversion example below is for MySQL 8, not MariaDB.
-- generate
SELECT UUID(); -- v1, e.g. 6ccd780c-baba-1026-9564-5b8c656024db
-- store compactly and keep inserts index-friendly
CREATE TABLE orders (
id BINARY(16) PRIMARY KEY,
sku VARCHAR(32)
);
INSERT INTO orders (id, sku) VALUES (UUID_TO_BIN(UUID(), 1), 'A-1');
SELECT BIN_TO_UUID(id, 1) AS id, sku FROM orders;
How to generate a UUID in PostgreSQL
gen_random_uuid() returns a version-4 UUID and is built into PostgreSQL 13 and later (older servers need CREATE EXTENSION pgcrypto;). PostgreSQL 18 adds uuidv7(), a built-in time-ordered UUID per RFC 9562; on older versions install the pg_uuidv7 extension and call uuid_generate_v7(). The native uuid type stores 16 bytes.
CREATE TABLE orders (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
sku text
);
SELECT gen_random_uuid(); -- v4, PostgreSQL 13+
SELECT uuidv7(); -- v7, PostgreSQL 18+
-- PostgreSQL < 18: CREATE EXTENSION pg_uuidv7; SELECT uuid_generate_v7();
How to generate a UUID in SQL Server
NEWID() returns a random version-4 GUID and can be called in any query. NEWSEQUENTIALID() produces GUIDs that increase in value, which avoids index page splits — but it is only allowed as a column default, never in a SELECT. Use the uniqueidentifier type.
SELECT NEWID(); -- random v4 GUID
CREATE TABLE orders (
id uniqueidentifier PRIMARY KEY DEFAULT NEWSEQUENTIALID(),
sku nvarchar(32)
);
How to generate a UUID in MongoDB
MongoDB's default _id is an ObjectId, which is not a UUID — it is a 12-byte value with a timestamp prefix. Reach for a real UUID when the identifier must match an external system. Drivers store UUIDs as BSON Binary subtype 4 (the "standard" subtype); the legacy subtype 3 is only needed when reading data written by very old drivers.
// mongosh
UUID() // v4 UUID, BSON Binary subtype 4 (standard)
ObjectId() // MongoDB's own 12-byte id, not a UUID
db.orders.insertOne({ _id: UUID(), sku: 'A-1' });
How to generate a UUID from the Linux / macOS shell
uuidgen ships with util-linux on Linux and with macOS. On Linux, uuidgen -t gives a time-based (v1) UUID; the kernel also exposes one random v4 per read of /proc/sys/kernel/random/uuid. Output case varies by implementation, so pipe through tr when you need a specific case.
uuidgen # v4 (random)
uuidgen -t # v1 (time-based, Linux only)
cat /proc/sys/kernel/random/uuid # one v4 per read (Linux)
uuidgen | tr '[:upper:]' '[:lower:]' # force lowercase
How to generate a UUID in Windows PowerShell
PowerShell exposes .NET's GUID type directly. New-Guid is the cmdlet form (PowerShell 5.0+); [guid]::NewGuid() works everywhere and lets you format immediately.
New-Guid # v4 GUID
[guid]::NewGuid() # same, as a .NET call
[guid]::NewGuid().ToString('N') # no hyphens
[guid]::NewGuid().ToString('B') # braces
How to generate a UUID in Excel
Excel has no built-in UUID function. For throwaway sample data, the simplest route is to generate values with the tool at the top of this page and paste them in as static text. If the workbook must generate them itself, call the Windows COM type library from VBA; wrap it in a volatile function so it recalculates on demand.
Function NewUUID() As String
' Windows only — returns a GUID without braces
NewUUID = Replace(Replace( _
LCase$(CreateObject("Scriptlet.TypeLib").GUID), "{", ""), "}", "")
End Function
' then in a cell: =NewUUID()
How to generate a UUID in Google Sheets
Sheets has no built-in UUID function either, but Apps Script exposes one: Utilities.getUuid(), which returns an RFC 4122 version-4 UUID. Add the function via Extensions → Apps Script, then call it from any cell.
function UUID() {
return Utilities.getUuid(); // v4, RFC 4122
}
// then in a cell: =UUID()
UUID versions at a glance — v1, v3, v4, v5, v6, v7, v8
The version is the 13th hex digit — the first digit of the third group. RFC 4122 defined v1–v5; RFC 9562 added v6, v7 and v8 and renamed the whole family to UUIDs without changing the 128-bit layout.
| Version | Built from | Sortable | What it reveals | Reach for it when |
|---|---|---|---|---|
v1 | 60-bit timestamp (100 ns ticks since 1582-10-15) + clock sequence + 48-bit node | No — the time bytes are out of order | Creation time and, usually, the host MAC address | Interfacing with legacy systems that already emit v1 |
v2 | DCE security: like v1 but the clock sequence and node hold a POSIX uid/gid | No | Time plus a local user or group id | Almost never — it is a historical corner of RFC 4122 |
v3 | MD5 hash of a namespace UUID plus a name | No | Nothing — but the input is guessable | Matching an existing system that already uses v3 |
v4 | 122 random bits | No | Nothing | General-purpose object IDs and request IDs; not authentication credentials |
v5 | SHA-1 hash of a namespace UUID plus a name | No | Nothing | You need the same input to always yield the same UUID |
v6 | v1 with the timestamp bytes reordered so they read high-to-low | Yes | Creation time and node, like v1 | Lossless conversion of v1 data to a sortable layout; the UUID value changes, so update references |
v7 | 48-bit Unix epoch timestamp in milliseconds + 74 random bits | Roughly — ordered by millisecond, random within the same millisecond | Creation time only | Database primary keys and anything you want roughly time-ordered |
v8 | Anything you like, as long as the version and variant bits are set | Your choice | Whatever you put in | Experiments and vendor-specific layouts |
| Nil UUID | All 128 bits set to zero — 00000000-0000-0000-0000-000000000000 | — | — | A sentinel meaning "no value yet", the way you would use NULL for an id column |
| Max UUID | All 128 bits set to one — ffffffff-ffff-ffff-ffff-ffffffffffff | — | — | A sentinel meaning "greatest possible value" (added by RFC 9562) |
Can you mix UUID versions in the same column?
At the format level yes, at the semantic level no. Every version shares the same 128-bit layout and the same variant bits, so any RFC-compliant parser reads any version and any UUID column stores all of them. Mixing does not raise collision odds either, because the version bits split the 128-bit space into disjoint blocks. What breaks is the set of assumptions you can make about that column.
- Ordering — only v6 and v7 sort by creation time, so ORDER BY on a mixed column follows neither time nor any useful sequence.
- Timestamps — only v1, v6 and v7 carry one. A v4 or a v3/v5 value has nothing to extract.
- Migration is asymmetric — v1 → v6 is lossless and reversible, but changes the UUID value and requires updating references; v1 → v7 keeps the timestamp but drops node and clock sequence; v4 → v7 is impossible, there is no timestamp to carry over.
- MySQL swap flag — if you store with UUID_TO_BIN(x, 1) you must read with BIN_TO_UUID(x, 1). A mismatch returns a wrong string silently, whatever versions sit in the column.
UUID vs ULID, NanoID, KSUID, Snowflake and auto-increment
Sorted by how they behave, not by hype. Sizes are the defaults each project ships with; ULID, NanoID, KSUID and Snowflake are community specifications or libraries, not IETF standards.
| Identifier | Size | Sortable | Random bits | Trade-off |
|---|---|---|---|---|
| UUID v4 | 128 bit · 36 chars · 16 bytes raw | No | 122 | Universally supported, leaks nothing, but random insertion order hurts clustered indexes |
| UUID v7 | 128 bit · 36 chars · 16 bytes raw | Yes, to the millisecond | 74 | Keeps v4's tool support while fixing insertion order; reveals creation time |
| ULID | 128 bit · 26 chars (Crockford base32) | Yes, lexicographically | 80 | Shorter and case-insensitive, but not an RFC and not a native column type in any major database |
| NanoID | 126 bit by default · 21 chars | No | 126 | Great for short public ids and slugs; a library convention, so other languages need a matching implementation |
| KSUID | 160 bit · 27 chars (base62) | Yes, to the second | 128 | Bigger timestamp headroom, but 20 bytes to store and no RFC behind it |
| Snowflake | 64 bit · up to 19 digits | Yes | 0 | Compact and sortable, but ids are only unique if you run a central generator and keep machine ids disjoint |
Auto-increment BIGINT | 64 bit · 8 bytes | Yes | 0 | Cheapest and most cache-friendly, but it leaks row counts, cannot be generated offline and complicates sharding and merges |
Rule of thumb: keep whatever your database and frameworks already generate well. Move to another scheme only when you have a concrete problem — leaking row counts, merging two databases, or generating ids on a client that is offline.
Should you use a UUID as a database primary key?
Usually yes when the id has to survive outside a single database, and no when you simply need a cheap local key. The cost is real but specific: it is about insertion order and index size, not about UUIDs being "slow".
What it actually costs
- Index size. A UUID is 16 bytes stored natively versus 8 bytes for
BIGINT— and 36 bytes or more if you store it as text. That difference is copied into every secondary index that references the key. - Insertion order. InnoDB and SQL Server cluster the table on the primary key, so random v4 values land at random points in the B-tree. Inserts touch pages that are already full, which causes page splits and evicts useful pages from the buffer pool. The effect grows with table size and write rate; on a small table or a low write rate you will not notice it.
- Debug friction. A 36-character key is harder to read out loud, harder to paste into a query, and makes URLs longer.
What you get back
- Ids generated anywhere. Clients, edge functions and offline apps can mint an id without a round trip, which removes the "insert first, then learn the id" dance.
- Safe merges and shards. Two databases can be combined without rewriting keys or renumbering a sequence.
- No leaked counts. A sequential id tells the world roughly how many rows you have and how fast you are growing.
If you do use one, do it this way
- Prefer v7 (or ULID) over v4 for a key that is inserted continuously — the time prefix keeps inserts roughly sequential. v7 is only ordered to the millisecond, so do not rely on it as a strict sort key.
- Prefer the 16-byte native type over
CHAR(36):BINARY(16)in MySQL,uuidin PostgreSQL,uniqueidentifierin SQL Server. - In MySQL, use
UUID_TO_BIN(x, 1)/BIN_TO_UUID(x, 1)only for v1 time-field reordering. For v7, useUUID_TO_BIN(x, 0)/BIN_TO_UUID(x, 0)to preserve its existing timestamp-first order. - Keep using
BIGINTwhen the table lives in one database, is written by one service, and you do not care that the id is guessable.
-- MySQL 8: 16 bytes, swap flag keeps inserts roughly sequential
CREATE TABLE orders (
id BINARY(16) PRIMARY KEY DEFAULT (UUID_TO_BIN(UUID(), 1)),
sku VARCHAR(32)
);
-- PostgreSQL 18+: native uuid type, built-in v7
CREATE TABLE orders (
id uuid PRIMARY KEY DEFAULT uuidv7(),
sku text
);
Frequently asked questions
What is a UUID?
123e4567-e89b-12d3-a456-426614174000.How is a UUID generated?
Can a UUID generate a duplicate?
What is the difference between UUID v1 and v4?
Should I use UUID v4 or v7?
How do I generate a UUID in MySQL?
SELECT UUID() in MySQL 8 or MariaDB; it returns an RFC 4122 version-1 UUID. MySQL has no built-in v7, so generate v7 in your application if you need time-ordered keys. In MySQL 8, store v1 UUIDs as BINARY(16) using UUID_TO_BIN(uuid, 1) and read them with BIN_TO_UUID(bin, 1). For v7 use flag 0 on both operations; its timestamp is already first. These conversion functions are MySQL-specific; do not assume the same SQL works in MariaDB.What is the UUID function in PostgreSQL?
gen_random_uuid() returns a version-4 UUID and is built into PostgreSQL 13 and later; older servers need CREATE EXTENSION pgcrypto. PostgreSQL 18 adds uuidv7(), a built-in time-ordered UUID per RFC 9562. On older versions install the pg_uuidv7 extension and call uuid_generate_v7(). Use the native uuid column type, which stores 16 bytes.How do I generate a UUID in Excel or Google Sheets?
CreateObject('Scriptlet.TypeLib').GUID from VBA (Windows only). In Google Sheets, add an Apps Script function UUID() that returns Utilities.getUuid(), then use =UUID() in a cell.Can I generate a UUID from the command line?
uuidgen prints a random version-4 UUID, and on Linux uuidgen -t gives a time-based one. Linux also exposes one random v4 per read of /proc/sys/kernel/random/uuid. In Windows PowerShell use New-Guid or [guid]::NewGuid().Should I use a UUID or an ObjectId in MongoDB?
_id is an ObjectId, a 12-byte value with a timestamp prefix, and it is the better default inside MongoDB. Use a UUID when the identifier must match an external system or your other services. Store it as BSON Binary subtype 4 (the standard subtype) so every driver reads it back identically.