// conversion reference

SQL GEN_RANDOM_UUID function

SELECT gen_random_uuid() returns a random version 4 uuid. It is built into PostgreSQL 13+ and is the usual DEFAULT for uuid primary keys.

Categoria
Conversion
Returns
uuid
In this category
32 of 39

Sintaxe

GEN_RANDOM_UUID()

Suporte a mecanismos

MotorSupportNotas
SQL Server Different name or syntax NEWID() is the v4 twin
PostgreSQL Sim Supported under this name.
MySQL Different name or syntax UUID() is v1, not v4; no gen_random_uuid
SQLite Not built in no built-in; randomblob(16) plus formatting
Oracle Different name or syntax UUID() from 23ai release update 23.9 returns a v4 RAW(16); SYS_GUID() before

Exemplos

PostgreSQL

SELECT gen_random_uuid() AS id;

PostgreSQL

CREATE TABLE events (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  label text
);

Bom saber

  • Before PostgreSQL 13 it lived in the pgcrypto extension; on 13+ it is core. CREATE EXTENSION pgcrypto is only needed on old clusters.
  • Random UUIDs scatter inserts across the B-tree. PostgreSQL 18 adds uuidv7(), which puts a millisecond timestamp first so new keys land at the end of the index; uuidv4() is an alias for gen_random_uuid().
  • The column type is uuid, not text: it stores 16 bytes, rejects malformed strings and compares natively. Casting text UUIDs on insert is the usual friction point.

Questions about GEN_RANDOM_UUID

Is it cryptographically random?

Yes, v4 UUIDs draw from a strong random source; only the version and variant bits are fixed. Fine for public identifiers as well as keys.

Why does gen_random_uuid() not exist on my cluster?

PostgreSQL 12 or older needs the pgcrypto extension: CREATE EXTENSION pgcrypto. From 13 on it is built in.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.