Sub topic 9
UUIDs as identifiers
Assume you know how to create tables, define primary keys, and run SELECT and INSERT statements. This chapter focuses on choosing and using PostgreSQL's uuid type for identifiers.
A UUID, or universally unique identifier, is a 128-bit value designed to be unique across systems. It is usually written as 32 hexadecimal characters separated by hyphens:
550e8400-e29b-41d4-a716-446655440000
PostgreSQL has a native uuid type. Use it instead of storing UUIDs in text or varchar. The native type validates the format and stores the value compactly.
UUIDs compared with integer identifiers
An integer identity column gets values from a sequence. It is small, fast, and easy to read. A UUID can be generated independently by different application servers without coordinating a shared sequence.
| Choice | Strength | Cost |
|---|---|---|
| `bigint` identity | Small indexes and ordered values | Values can reveal insertion counts |
| `uuid` | Safe to generate across services and harder to guess | Larger indexes and less locality for random values |
| `text` UUID | Flexible input format | No native validation and more storage |
UUIDs are useful when records are created in multiple databases, synchronized between services, or exposed through public URLs. Random UUIDs do not reveal how many records exist or which record was created before another.
A UUID occupies 16 bytes, while a bigint occupies 8 bytes. UUID indexes and foreign-key columns therefore take more space. Random UUID values can also scatter inserts across a B-tree index, causing more page activity than increasing integer values.
Creating and referencing UUIDs
PostgreSQL can generate random UUIDs with gen_random_uuid(). On PostgreSQL versions where the function is supplied by the pgcrypto extension, enable that extension first.
CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE TABLE customers (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
email text NOT NULL UNIQUE
);
CREATE TABLE invoices (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
customer_id uuid NOT NULL REFERENCES customers(id),
amount numeric(12, 2) NOT NULL CHECK (amount >= 0)
);
INSERT INTO customers (email)
VALUES ('[email protected]')
RETURNING id;The DEFAULT expression runs when an INSERT does not provide an id. The foreign key must use the same uuid type as the referenced column. This avoids repeated conversions and makes schema intent clear.
You can provide a known UUID explicitly:
INSERT INTO customers (id, email)
VALUES ('550e8400-e29b-41d4-a716-446655440000'::uuid,
'[email protected]');The ::uuid syntax is an explicit cast. Invalid input raises an error instead of silently storing malformed text.
Choosing an identifier strategy
Choose bigint when one database owns the data, compact indexes matter, and sequential identifiers are acceptable. Choose UUIDs when independent creation, data merging, or opaque public identifiers matters more than index size.
If you expose identifiers in URLs but need smaller internal indexes, you can keep a bigint primary key and add a unique UUID column. That design costs another index, so choose it only when both properties are valuable.
Exercise
What type should orders.customer_id use if it references customers.id uuid PRIMARY KEY?
Show answer
It should use uuid, followed by a foreign key referencing customers(id).