Generate UUID v4 and v7 in SQL (Postgres)
Copy-paste SQL (Postgres) code that produces a UUID v4 (random, the long-standing default) or UUID v7 (time-ordered, the modern choice for database keys). Both blocks below are production-ready.
UUID v4 in SQL (Postgres)
v4 is purely random — 122 bits of entropy, no structure. Use it when you don't want timing information embedded in the ID, or when you don't care about index locality.
-- Postgres 13+ has gen_random_uuid() built in:
SELECT gen_random_uuid();
-- For Postgres 12 and earlier, enable the pgcrypto extension first:
CREATE EXTENSION IF NOT EXISTS pgcrypto;
SELECT gen_random_uuid();
UUID v7 in SQL (Postgres)
v7 embeds a millisecond Unix timestamp in the first 48 bits, so the IDs sort chronologically. This is what modern databases want from a primary key — sequential inserts land in adjacent index pages instead of scattering writes.
-- Postgres 18 (Q4 2025) added native uuidv7():
SELECT uuidv7();
-- For Postgres 17 and earlier, use a SQL function:
CREATE OR REPLACE FUNCTION uuid_v7() RETURNS uuid AS $$
DECLARE
unix_ms bigint := (extract(epoch from clock_timestamp()) * 1000)::bigint;
rand_bytes bytea := gen_random_bytes(10);
BEGIN
RETURN (
lpad(to_hex(unix_ms), 12, '0') ||
'7' || encode(substring(rand_bytes from 1 for 2), 'hex') ||
'8' || encode(substring(rand_bytes from 3 for 1), 'hex') ||
encode(substring(rand_bytes from 4 for 6), 'hex')
)::uuid;
END;
$$ LANGUAGE plpgsql VOLATILE;
Library support
Postgres 18 (released Q4 2025) added native `uuidv7()` and time-ordered storage optimisations. For Postgres 17 and earlier, the SQL function above is a drop-in.
Notes
Use `uuid` as the column type. Prefer v7 for primary keys — random v4 IDs hurt insert performance on B-tree indexes at scale by scattering writes across pages.
Need them in bulk?
Our UUID generator produces 1 to 1000 UUIDs (v4 or v7) instantly, all in your browser, with one-click copy and JSON/CSV export. Useful for seeding test data or pre-generating IDs offline.