Definition

UUID encoding refers to the byte or character representation used to store, transmit, or display a UUID. A UUID is fundamentally a 128-bit (16-byte) integer. How those 128 bits are serialised has significant practical consequences for storage efficiency, query performance, and interoperability.

The same UUID has several valid encodings:

Binary (hex dump): 01 8f be 3a 4c 5d 7b 12 8a bc 01 23 45 67 89 ab  (16 bytes)
Hex string:        018fbe3a4c5d7b128abc0123456789ab                  (32 chars)
Canonical string:  018fbe3a-4c5d-7b12-8abc-0123456789ab              (36 chars)
Base62:            2Bj9kFmNpQrSuVwXyZ4A7c                            (22 chars)
Base64url:         AY--OkxdexKKvAEjRWiA                              (22 chars, no padding)

All five representations carry the exact same 128 bits.

Encoding formats compared

FormatSizeURL-safeSort-preserving (v7)Human-readableStandard
Binary (16 bytes)16 BN/AYesNoRFC 9562
Hex no hyphens32 charsYesYesPartialRFC 9562
Canonical string36 charsMostlyYesYesRFC 9562
Base6222 charsYesYes*YesConvention
Base64url22–24 charsYesNoPartialRFC 4648
Base5822 charsYesNoYesConvention

* Base62 preserves sort order only when the alphabet is ordered 0–9, A–Z, a–z.

Binary encoding — 16 bytes

Binary is the most efficient encoding and is used inside databases, binary wire protocols (gRPC/protobuf), and memory-mapped structures.

import uuid

uid = uuid.UUID('018fbe3a-4c5d-7b12-8abc-0123456789ab')

# 16 raw bytes (big-endian, MSB first — the standard UUID byte order)
b = uid.bytes
print(b.hex())  # 018fbe3a4c5d7b128abc0123456789ab

# Round-trip
uid2 = uuid.UUID(bytes=b)
assert uid == uid2

In protobuf, UUIDs are commonly transmitted as bytes fields (16 bytes) rather than string fields (36+ bytes), cutting wire size by more than half.

message Event {
  bytes id = 1;   // 16-byte UUID — preferred
  // string id = 1; // 36-char string — larger on the wire
}

String encoding — canonical and hex-only

The canonical 36-character string is the most portable form — every UUID library in every language accepts it.

import { v7 as uuidv7 } from 'uuid';

const canonical = uuidv7();
// '018fbe3a-4c5d-7b12-8abc-0123456789ab'  — 36 chars

// Hyphen-free hex — 32 chars, still universally parseable
const hexOnly = canonical.replace(/-/g, '');
// '018fbe3a4c5d7b128abc0123456789ab'

// Uppercase — valid per RFC 9562, but lowercase is conventional
const upper = canonical.toUpperCase();
// '018FBE3A-4C5D-7B12-8ABC-0123456789AB'

Database string storage

When a native UUID type is unavailable, prefer hyphen-free CHAR(32) over VARCHAR(36):

-- PostgreSQL: use the native uuid type (stores as 16 bytes internally)
CREATE TABLE events (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid()
);

-- MySQL 8+: use BINARY(16) with helper functions
CREATE TABLE events (
  id BINARY(16) PRIMARY KEY DEFAULT (UUID_TO_BIN(UUID(), 1))
);

-- Fallback for any database: CHAR(32) without hyphens
CREATE TABLE events (
  id CHAR(32) PRIMARY KEY  -- hex, no hyphens
);

See UUID in Databases for full per-database guidance.

Compact encodings — Base62 and Base64url

When UUIDs appear in URLs, QR codes, or user-visible identifiers, the 36-character canonical string is verbose. Compact encodings reduce length at the cost of slightly higher encoding/decoding complexity.

// Base62 encode/decode (preserves sort order for UUID v7)
const ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

function toBase62(uuid: string): string {
  let n = BigInt('0x' + uuid.replace(/-/g, ''));
  const chars: string[] = [];
  while (n > 0n) {
    chars.unshift(ALPHABET[Number(n % 62n)]);
    n /= 62n;
  }
  return chars.join('').padStart(22, '0');
}

// Example URL with compact UUID
// Before: /orders/018fbe3a-4c5d-7b12-8abc-0123456789ab  (46 chars in path)
// After:  /orders/2Bj9kFmNpQrSuVwXyZ4A7c               (32 chars in path)

See Base62 Encoding for the full implementation.

Choosing the right encoding

Use caseRecommended encodingReason
PostgreSQL primary keyNative uuid type16-byte storage, native operators
MySQL primary keyBINARY(16)Compact, fast index comparison
HTTP API responseCanonical string (36 chars)Maximum library compatibility
URL path parameterBase62 (22 chars)Short, URL-safe, sort-preserving
gRPC / protobufbytes (16 bytes)Minimal wire size
Log outputCanonical stringHuman-readable, copy-pasteable
Redis key componentHyphen-free hex (32 chars)Compact, no escaping needed

Byte order — big-endian vs little-endian

The RFC 9562 standard byte order for UUIDs is big-endian (most significant byte first). This is what Python’s uuid.UUID.bytes, JavaScript’s Buffer.from(uuid.replace(/-/g,''), 'hex'), and most UUID libraries produce.

Some older Windows APIs (COM/OLE) use a mixed-endian format where the first three fields are little-endian. This is a historical artefact of the GUID representation on Windows. Modern UUID libraries do not use mixed endian — but if you are interoperating with legacy COM components, verify the byte order.

import uuid

uid = uuid.UUID('018fbe3a-4c5d-7b12-8abc-0123456789ab')

# Standard big-endian bytes (RFC 9562)
print(uid.bytes.hex())       # 018fbe3a4c5d7b128abc0123456789ab

# Windows mixed-endian bytes (GUID on-disk format)
print(uid.bytes_le.hex())    # 3abe8f01 5d4c 127b 8abc0123456789ab
#                               ^^^^^^^^ ^^^^ ^^^^ — first 3 fields reversed

Always use uid.bytes (big-endian) when storing UUIDs for cross-platform use.

External references

Frequently asked questions

Should I store UUIDs as binary or as strings in a database?

Binary (16 bytes) is almost always the better choice for databases. MySQL and MariaDB recommend BINARY(16); PostgreSQL has a native uuid type that stores 16 bytes internally. The string representation uses 36 bytes (or 32 without hyphens) — more than double the binary size. Binary storage also allows faster index comparisons because the database compares raw bytes rather than character-by-character strings. See UUID in Databases for per-database recommendations.

Do hyphens in a UUID string affect its value?

No. The hyphens in the canonical xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx format are purely cosmetic separators. Stripping them gives the same 32-hex-digit value. All UUID libraries accept both forms as input, and the underlying 128-bit value is identical. When storing as a string in a database, use the hyphen-free 32-character form to save 4 bytes per row, or use the native uuid type.

What is the most compact way to represent a UUID?

The most compact text representation is Base62 at 22 characters, followed by Base64url at 22–24 characters. In binary, 16 bytes is the absolute minimum. For URLs and human-readable identifiers, Base62 is a good balance of compactness and URL safety. For wire protocols and binary file formats, use the raw 16-byte representation.

Does encoding affect UUID v7's sort order?

It depends on the encoding. The canonical hex string and the raw 16-byte binary (big-endian, MSB first) both preserve UUID v7's lexicographic sort order — comparing strings alphabetically gives the same order as comparing timestamps. Base62 also preserves sort order if the alphabet is ordered numerically (0–9 before A–Z before a–z). Base64url does not preserve sort order because its alphabet ordering does not align with the UUID bit layout.