PostgreSQL Tutorial PostgreSQL Advanced PostgreSQL Database Account Management PostgreSQL References
PostgreSQL Tutorial PostgreSQL Advanced PostgreSQL Database Account Management PostgreSQL References

PostgreSQL SETSEED() Function



The PostgreSQL SETSEED() function is used to set the seed for the subsequent RANDOM() function calls. The value of seed must be between -1.0 and 1.0, inclusive.

The RANDOM() function returns a random number between 0 (inclusive) and 1 (exclusive). It returns a completely random number if no seed is provided. Otherwise, it returns a repeatable sequence of random numbers, if seed is provided.

Syntax

SETSEED(seed)

Parameters

seed Required. Specify a value between 1.0 and -1.0, inclusive, that is used to provide the seed for the subsequent RANDOM() function calls.

Return Value

Nothing is returned.

Example:

The example below shows the usage of SETSEED() 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