PostgreSQL RANDOM() Function
The PostgreSQL RANDOM() function returns a random number between 0 (inclusive) and 1 (exclusive). The SETSEED() function can be used to set the seed for the RANDOM() function. The RANDOM() function returns a completely random number if no seed is provided (seed is set with the SETSEED() function). The function returns a repeatable sequence of random numbers, if seed is provided (seed is set with the SETSEED() function).
Syntax
RANDOM()
Parameters
No parameter is required.
Return Value
Returns a random number between 0 (inclusive) and 1 (exclusive).
Example:
The example below shows the usage of RANDOM() function.
/* no seed value is provided, hence the result can vary */ SELECT RANDOM(); Result: 0.6763981107454846 /* seed value is provided using SETSEED(0.5) */ SELECT SETSEED(0.5); SELECT RANDOM(); Result: 0.2499104186659835 /* seed value is provided using SETSEED(0.3) */ SELECT SETSEED(0.3), RANDOM(); Result: 0.5499641674664169
Random Number in a given Range
The PostgreSQL RANDOM() function can be used to create a random number between a given range. For example - to create a random number in a range [a, b), the following formula can be used:
SELECT RANDOM()*(b-a) + a;
Example:
In the example below, the RANDOM function is used to create a random number between a range [100, 200).
/* no seed value is provided, hence the result can vary */ SELECT RANDOM()*(200-100) + 100; Result: 143.67012152790102 /* seed value is provided using SETSEED(0.5) */ SELECT SETSEED(0.5); SELECT RANDOM()*(200-100) + 100; Result: 124.99104186659835 /* seed value is provided using SETSEED(0.5) */ SELECT SETSEED(0.3); SELECT RANDOM()*(200-100) + 100; Result: 154.99641674664167
Random Integer in a given Range
The PostgreSQL RANDOM() function can be used to create a random integer between a given range. For example - to create a random integer in a range [a, b), the following formula can be used:
SELECT FLOOR(RANDOM()*(b-a)) + a;
Example:
In the example below, the RANDOM function is used to create a random integer between a range [500, 600).
/* no seed value is provided, hence the result can vary */ SELECT FLOOR(RANDOM()*(600-500)) + 500; Result: 533 /* seed value is provided using SETSEED(0.5) */ SELECT SETSEED(0.5); SELECT FLOOR(RANDOM()*(600-500)) + 500; Result: 524 /* seed value is provided using SETSEED(0.3) */ SELECT SETSEED(0.3); SELECT FLOOR(RANDOM()*(600-500)) + 500; Result: 554
❮ PostgreSQL Functions