UUID (universally unique identifier)
Last updated: 2026-11-04
UUID (universally unique identifier)
UUID is a 128-bit universally unique identifier. PostgreSQL stores it as 16 bytes and compares it by byte order rather than string order, which keeps both storage and comparison efficient. Since PostgreSQL 13 the built-in gen_random_uuid() generates version 4 (random) UUIDs with no extension required. UUIDs are the safe default when data must be merged across several systems, or when exposing auto-increment IDs is undesirable.
| Kind | type |
|---|---|
| Example Language | SQL |
📝 Syntax
UUID —— 16 bytes, canonical 8-4-4-4-12 form
-- generation:
gen_random_uuid() -- version 4, random (built in since PG13)
-- legacy approach needs an extension: CREATE EXTENSION "uuid-ossp"; uuid_generate_v4()
Returns:Stores a 128-bit UUID. A valid string can be converted with ::uuid, while malformed input raises "invalid input syntax for type uuid". gen_random_uuid() returns a random version 4 UUID.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
id | name | matches_fixed | gen_len | gen_version | col_type
--------------------------------------+----------+---------------+---------+-------------+----------
a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11 | fixed id | t | 36 | 4 | uuid
📌 Key Points
- gen_random_uuid() has been built in since PostgreSQL 13 and needs no extension; the uuid-ossp extension is a historical artefact of older projects.
- Random UUID primary keys scatter inserts across B-tree pages, causing page splits and write amplification; auto-increment keys generally insert faster on large tables.
- Trade-off: use UUID when uniqueness must hold across systems or the row count should stay hidden. Prefer an auto-increment BIGINT when write throughput on a single database matters most.