gen_random_uuid
PG 13+→ uuidGenerates a version 4 (random) UUID using the pgcrypto random number generator.
Signature
gen_random_uuid ( ) → uuidExamples
SELECT gen_random_uuid();a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11 (varies)INSERT INTO items (id, name) VALUES (gen_random_uuid(), 'Widget');Row with random UUID primary keySELECT gen_random_uuid() FROM generate_series(1,5);5 unique UUIDsUPDATE sessions SET token = gen_random_uuid() WHERE expired = true;Expired sessions get fresh random tokensBefore PostgreSQL 13, `uuid_generate_v4()` from the uuid-ossp extension was the standard way to generate random UUIDs. Since PG 13, `gen_random_uuid()` is built-in and requires no extension — installing uuid-ossp adds unnecessary dependency.
✓ Instead: Use `gen_random_uuid()` directly on PostgreSQL 13+. If compatibility with older versions is needed, check with `SELECT current_setting('server_version_num')::int >= 130000` first.
Set `DEFAULT gen_random_uuid()` on UUID columns so every INSERT automatically gets a unique identifier without application code: `id uuid DEFAULT gen_random_uuid() PRIMARY KEY`.
CREATE TABLE orders (id uuid DEFAULT gen_random_uuid() PRIMARY KEY, amount numeric);Each row auto-assigned a random UUID