PostgreSQL 18 reference · Math Functions
PostgreSQL RANDOM() Function
Return a random number from 0 up to 1, or since PostgreSQL 17 a random integer or numeric in a range.
PostgreSQL 18
Syntax
random() | random(min, max)
Parameters
| Parameter | Description |
|---|---|
min, max optional |
The range, both ends included (17+). |
Return value
double precision from 0 to 1, or a value in the range.
Examples
SELECT random() < 1 AS below_one, floor(random() * 6 + 1) BETWEEN 1 AND 6 AS dice_ok;
Output
below_one | dice_ok -----------+--------- t | t (1 row)
Run this on your computer — see “Get Started” for setup.
SELECT random(1, 100) AS repeatable
FROM (SELECT setseed(0.42)) AS seeded;
Output
repeatable
------------
96
(1 row)Run this on your computer — see “Get Started” for setup.
ORDER BY random() LIMIT n picks random rows from small tables; for large tables use
TABLESAMPLE SYSTEM (1). random() isn't cryptographically secure.
Version history
| Version | Change |
|---|---|
| PostgreSQL 17 | Added random(min, max) for integer, bigint and numeric ranges. |
In other languages
RANDOM()· SQLite
Related
GEN_RANDOM_UUID()· Generate a random version 4 UUID. Since PostgreSQL 18, uuidv4() is another name for it.- SQL Aggregate Functions · tutorial