TypesPostgreSQL only

GEN_RANDOM_UUID

Generates a random UUID — a unique identifier like 3f2c9a1e-….

Syntax

GEN_RANDOM_UUID()

Returns a version 4 UUID: 32 randomly generated hexadecimal digits with hyphens. The chance of two identical ones is negligible, so such keys can be created anywhere — in the database or in the application — without coordination. Most often they're used as a default value: id uuid PRIMARY KEY DEFAULT gen_random_uuid().

Data for the examples

employees

namedepartmentsalarybonusphone
Emmabackend1200300+44 7700 900123
Liambackend1000NULLNULL
Oliviafrontend1350150+44 7700 900456
Noahfrontend950NULL+44 7700 900789
Sophiadesign1200200NULL

These tables already exist in the sandbox — the examples below use them. Want to try this in your own database? Copy the SQL.

A new UUID
SELECT GEN_RANDOM_UUID() AS id;
id
f9b34e8f-3f5a-45cf-b0b1-0c6add1723b7

The result is different every time — press “Run” again.

Each row gets its own
SELECT name, GEN_RANDOM_UUID() AS id
FROM employees;
nameid
Emma8163699d-3f38-4465-906f-9694ee1361ef
Liam465e8725-8440-4db0-9447-541a2edbccb4
Olivia6a504341-3ea7-496d-a870-3be957a3864c
Noaha1749abe-3d3c-4cd7-9dac-4a5ea254f914
Sophiac4a4a7e9-c8be-4e1a-b747-239b0ca0262d
Type and length
SELECT pg_typeof(GEN_RANDOM_UUID()) AS type,
LENGTH(GEN_RANDOM_UUID()::text) AS text_length;
typetext_length
uuid36

Watch out

Store it as uuid, not text: as uuid it takes 16 bytes, while as text it's 36 characters with slower comparisons.

Random UUIDs aren't ordered by creation time: ORDER BY id won't give you insertion order, and new values are scattered across the whole index. PostgreSQL 18 has uuidv7(), which puts the time at the beginning.

A UUID takes 16 bytes versus 8 for a bigint. For huge tables with many relationships, that's noticeable in index size.

Related functions

Learn more in the course