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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

random()  |  random(min, max)

Parameters

ParameterDescription
min, max optional The range, both ends included (17+).

Return value

double precision from 0 to 1, or a value in the range.

Examples

Random numbers
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.

A repeatable range with setseed() (17+)
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

VersionChange
PostgreSQL 17Added random(min, max) for integer, bigint and numeric ranges.

In other languages

Was this page helpful?