Numbers

RANDOM

Returns a random fractional number from 0 (inclusive) to 1 (exclusive).

Syntax

RANDOM()
RANDOM(<min>, <max>)

Every call gives a new number, and every row gets its own. Multiply it and drop the fractional part to get a random integer in the range you need; PostgreSQL 17 and newer also have a ready-made form, RANDOM(1, 6). Often used to pick random rows or shuffle them.

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 random number
SELECT RANDOM() AS random_number;
random_number
0.8767955776954344

The result is different every time — press “Run” a few times.

A die: an integer from 1 to 6
SELECT FLOOR(RANDOM() * 6) + 1 AS dice,
RANDOM(1, 6) AS dice_pg17;
dicedice_pg17
34
A random employee
SELECT name
FROM employees
ORDER BY RANDOM()
LIMIT 1;
name
Noah

Watch out

ROUND(RANDOM() * 6) gives an uneven distribution: 0 and 6 come up half as often as the other numbers. For an integer, use FLOOR(RANDOM() * 6) + 1.

ORDER BY RANDOM() goes through and sorts the whole table. On millions of rows that's slow — for large tables there's TABLESAMPLE.

RANDOM isn't suitable for passwords, tokens or anything that has to be unpredictable. For a random identifier, use gen_random_uuid().

Related functions