Sub topic 9
UUIDs as identifiers
This chapter covers the uuid type in PostgreSQL: what it stores, how to generate values, and when it is a better or worse primary key than a bigint identity column. It assumes you know basic SQL (SELECT, INSERT, CREATE TABLE), can run queries in psql, and have read the chapter on integers and identity columns.
What a uuid is
A UUID (universally unique identifier) is a 128-bit value. It is usually written as 32 hexadecimal digits in five groups separated by hyphens:
a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11PostgreSQL stores a uuid as 16 bytes of binary data, not as a 36-character string. The text form is only how the value is displayed and parsed.
The input parser is forgiving. It accepts uppercase or lowercase digits, braces around the value, and hyphens in other positions or no hyphens at all. It always prints the value in the standard lowercase form.
SELECT 'A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11'::uuid AS a,
'a0eebc999c0b4ef8bb6d6bb9bd380a11'::uuid AS b;Both columns print a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11. A string that is not a valid UUID raises invalid input syntax for type uuid.
Why use UUIDs
A UUID can be generated by any client, service, or database without asking a central counter for the next number. That gives you several practical benefits:
- Generation outside the database. An application can create an ID before inserting the row. This helps when you need the ID of a parent row to build child rows in the same batch, or when you queue work before it is saved.
- Merging data. Rows created in separate databases (shards, offline clients, staging copies) are very unlikely to collide when combined.
- Hard to guess. A random UUID does not reveal how many rows exist, and a URL such as
/invoices/a0eeb...cannot be enumerated by adding one to the number.
The last point needs care. A random UUID makes guessing impractical, but it is not an access control. You still need authorization checks on every request.
Generating UUIDs
Since PostgreSQL 13, the built-in function gen_random_uuid() returns a random version 4 UUID. Earlier versions needed the pgcrypto extension for the same function.
SELECT gen_random_uuid();Use it as a column default so that inserts do not have to supply a value:
CREATE TABLE customers (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
email text NOT NULL UNIQUE,
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO customers (email)
VALUES ('[email protected]')
RETURNING id;RETURNING id gives the generated value back to the caller, so your application can use it immediately.
PostgreSQL 18 adds uuidv7(), which generates a time-ordered UUID (see below). It also adds uuidv4() as an alias for gen_random_uuid(). If you run an older version, uuidv7() is not available, and you would generate version 7 values in the application or with an extension.
The uuid-ossp extension offers other versions, such as uuid_generate_v1(). For random IDs you do not need it.
UUID versions in brief
The version is encoded inside the value. Two matter in practice for primary keys.
| Version | How it is built | Ordering | Typical use |
|---|---|---|---|
| 4 | 122 random bits | None | Opaque identifiers, public tokens |
| 7 | 48-bit millisecond timestamp, then random bits | Roughly by creation time | Primary keys that insert in order |
Version 1 embeds a timestamp and a node identifier (often derived from a MAC address). That leaks information about the machine and the creation time, so it is rarely the right choice today.
Cost compared with bigint
A uuid takes 16 bytes. A bigint takes 8 bytes and an integer takes 4. The difference is small for one row but it multiplies. The primary key index stores the key, and every foreign key column in other tables repeats it, along with its own index.
Consider an orders table with 100 million rows and three tables that reference it. Moving from bigint to uuid adds 8 bytes per key entry in each place, which can add several gigabytes across tables and indexes. This is usually acceptable. It is still a real cost for very large tables, because bigger indexes mean fewer entries per page and less of the index fits in memory.
Random UUIDs and index locality
The bigger practical issue is ordering. A bigint identity column grows over time, so new rows land at the right edge of the primary key B-tree. That part of the index stays in cache, and pages fill completely.
A random version 4 value lands at an arbitrary position in the index. Each insert may touch a different page, which causes these effects:
- More page reads and cache misses once the index is larger than memory.
- Page splits scattered through the tree, which leaves pages partly empty.
- More write-ahead log (WAL) traffic, because PostgreSQL writes full-page images of pages after a checkpoint when they are first modified.
For small and medium tables you will not notice. On write-heavy tables with hundreds of millions of rows, the difference can be measurable.
Version 7 UUIDs address this. Their leading bits are a timestamp, so new values sort after older ones and inserts concentrate at the right edge of the index, as they do with a sequence. You keep client-side generation and the 16-byte size, and you get much better locality.
-- PostgreSQL 18 or later
CREATE TABLE events_log (
id uuid PRIMARY KEY DEFAULT uuidv7(),
message text NOT NULL
);A time-ordered ID has a trade-off. It reveals roughly when the row was created, which may matter if the ID is public. Random version 4 does not leak that.
Working with uuid values
A few behaviors to know:
- Comparison.
uuidsupports=,<,>, and sorting. Comparison is bytewise on the 16 bytes. For version 4 the order is meaningless. For version 7 it follows creation time at millisecond resolution. - Indexes. B-tree indexes work as usual.
PRIMARY KEYandUNIQUEcreate one automatically. - No arithmetic. You cannot add to a UUID or take its maximum meaningfully for "latest row" queries when it is random. Use a
created_atcolumn for that. - Casting to text.
id::textgives the 36-character form. Use it only for display or for interfacing with systems that need strings. Do not store UUIDs in atextcolumn. That doubles or triples the storage and loses validation. - Casting from text.
'...'::uuidvalidates the format and raises an error otherwise.
SELECT id, id::text AS id_text, length(id::text) AS chars
FROM customers;The chars column is 36.
Common mistakes
- Storing UUIDs as
varchar(36)ortext. You pay for roughly 37 bytes instead of 16, and nothing prevents a malformed value from being inserted. - Using a random UUID as a clustered ordering. PostgreSQL tables are heaps, so there is no clustered primary key. Still, if you query by recent rows, add a
created_atindex instead of relying on key order. - Treating a UUID as a secret. A UUID in a URL can leak through logs, browser history, and referrer headers. Check permissions on the server regardless.
- Mixing key types. If
orders.idisuuid, thenorder_items.order_idmust beuuidas well. A mismatch causes an error or forces a cast that can prevent index use. - Using the wrong generator on old servers. On PostgreSQL 12 or earlier,
gen_random_uuid()fails unlesspgcryptois installed.
Choosing between bigint and uuid
| Situation | Reasonable choice |
|---|---|
| Single database, internal IDs, high insert rate | `bigint` identity |
| IDs must exist before the insert, or are created by many clients | `uuid` (version 7 if available) |
| IDs appear in public URLs and must not be guessable | `uuid`, or a `bigint` key plus a separate public `uuid` column |
| Data merged from several databases | `uuid` |
| Very large tables where index size matters | `bigint` |
Some schemas use both: an internal bigint primary key for joins and a unique uuid column exposed to the outside. This gives compact foreign keys and non-guessable public identifiers, at the cost of an extra column and index.
Exercise
A table has id uuid PRIMARY KEY DEFAULT gen_random_uuid(). It receives thousands of inserts per second and now has 300 million rows. Inserts are slowing down and WAL volume is high. What is the likely cause, and what change would you consider?
Show answer
Version 4 UUIDs are random, so each insert lands on an arbitrary page of the primary key index. Once the index no longer fits in memory this causes cache misses, page splits, and extra full-page images in the WAL. Consider a time-ordered key: uuidv7() on PostgreSQL 18 or later (or version 7 values generated by the application), or a bigint identity column with a separate public UUID if the ID needs to be non-guessable.
Exercise
Why is id text a poor choice for storing UUIDs, and what should you use instead?
Show answer
A text column stores the 36-character string (about 37 bytes) rather than 16 bytes, makes indexes larger and comparisons slower, and accepts any string, so malformed IDs can be inserted. Use the uuid type, which stores 16 bytes and rejects invalid input.