PostgreSQL random() Function
The PostgreSQL random()
function returns a random number between 0 (inclusive) and 1 (exclusive).
random()
Syntax
This is the syntax of the PostgreSQL random()
function:
random()
Parameters
The PostgreSQL random()
function does not have any parameters.
Return value
The PostgreSQL random()
function returns a random number between 0 (inclusive) and 1 (exclusive).
The return value of random()
is a random decimal between 0 (inclusive) and 1 (exclusive). If you want to return random numbers in other intervals (such as m
and n
), please use the following formulas.
- A random number between
m
andn
:random() * (n - m) + m
- A random integer between
m
andn
:FLOOR(random() * (n - m + 1) + m)
If you want to get a stable random sequence, use the random()
function in conjunction with the setseed()
function.
random()
Examples
Get a random number between 0 and 1
This example shows how to use the random()
function function to get a random number between 0 and 1.
SELECT
random(),
random(),
random(),
random();
-[ RECORD 1 ]---------------
random | 0.3029171607224228
random | 0.42633738304023794
random | 0.584824959131069
random | 0.7533572011921841
Get a random number between 10 and 20
This example shows how to use the random()
function function to get a random number between 10 and 20.
SELECT
random() * (20 - 10) + 10 AS "10 <= x < 20",
random() * (20 - 10) + 10 AS "10 <= x < 20",
random() * (20 - 10) + 10 AS "10 <= x < 20",
random() * (20 - 10) + 10 AS "10 <= x < 20";
-[ RECORD 1 ]+-------------------
10 <= x < 20 | 19.504483402831525
10 <= x < 20 | 13.118109640092719
10 <= x < 20 | 17.609356732100565
10 <= x < 20 | 10.092857779143252
Get a random integer between 10 and 20
This example shows how to use random()
the and floor()
to get a random integer between 10 and 20.
SELECT
floor(random() * (20 - 10 + 1) + 10) AS "10 <= x < 20",
floor(random() * (20 - 10 + 1) + 10) AS "10 <= x < 20",
floor(random() * (20 - 10 + 1) + 10) AS "10 <= x < 20",
floor(random() * (20 - 10 + 1) + 10) AS "10 <= x < 20";
-[ RECORD 1 ]+---
10 <= x < 20 | 15
10 <= x < 20 | 17
10 <= x < 20 | 12
10 <= x < 20 | 14