Skip to content

Random functions ​

Random functions generate values, set the connection pseudorandom seed or request cryptographically strong random bytes. These are separate randomness sources.

setseed controls the connection pseudorandom sequence; it does not control OS-random bytes or UUID entropy. Examples below compare stable properties such as byte length rather than expecting fixed random output.

Example: Checking size and a zero-deviation sample ​

sql
SELECT length(gen_random_bytes(16)), random_normal(7, 0)
FORMAT csv;
text
16,7.0

gen_random_bytes ​

Read bounded cryptographically strong OS-random bytes.

Syntax ​

text
gen_random_bytes(count)

Arguments ​

Integer count 1..1024. OS entropy is independent of setseed. Failures use IO_ERROR. SQL NULL propagates.

Returned value ​

BLOB random bytes; nondeterministic.

Example ​

sql
SELECT length(gen_random_bytes(8)) FORMAT csv;
text
8

random_normal ​

Draw an approximate normally distributed random value.

Syntax ​

text
random_normal([mean[,stddev]])

Arguments ​

Defaults: mean zero and stddev one. Calls use connection-local random state and are nondeterministic. IEEE nonfinite arithmetic applies and native NaN becomes SQL NULL. SQL NULL arguments propagate.

Returned value ​

Approximate REAL normal sample; no cryptographic or seeded PostgreSQL sequence compatibility.

Example ​

sql
SELECT random_normal(0,1) IS NOT NULL FORMAT csv;
text
1

setseed ​

Reset the connection-local random sequence.

Syntax ​

text
setseed(seed)

Arguments ​

Finite seed in [-1,1]. Equal seeds repeat random/random_normal/array sampling draws. UUIDs and gen_random_bytes keep independent OS entropy. NULL does not reseed. Native draw sequences differ from PostgreSQL.

Returned value ​

SQL NULL after resetting the generator.

Example ​

sql
SELECT setseed(0.25) FORMAT csv;
text
\N

random and randomblob ​

random() returns a signed INTEGER random value. randomblob(length) returns that many random bytes as a BLOB; lengths below one, including NULL after integer conversion, produce one byte. Requests above 1,000,000,000 bytes fail, and request memory limits also apply.

These functions are nondeterministic. Use gen_random_bytes when cryptographically strong random bytes are required.

sql
SELECT typeof(random()),length(randomblob(8)),length(randomblob(0)),length(randomblob(NULL)) FORMAT csv;
text
"integer",8,1,1