PostgreSQL setseed() Function

The PostgreSQL setseed() function set the seed for subsequent random() calls so that the random() function produces a repeatable random sequence.

setseed() Syntax

This is the syntax of the PostgreSQL setseed() function:

setseed(seed) -> double precision

Parameters

seed

Required. The seed for subsequent calls to the random() function. It must be between -1 and 1 (including -1.0 and 1.0).

Return value

PostgreSQL setseed() has no return value.

setseed() Examples

Let’s first generate a few random numbers using the random() function without setseed().

SELECT
    random(),
    random(),
    random();
-[ RECORD 1 ]---------------
random | 0.39696090303700515
random | 0.8836384228449994
random | 0.4060772195260256

Run it again:

SELECT
    random(),
    random(),
    random();
-[ RECORD 1 ]----------------
random | 0.2312518157992649
random | 0.010247106452005994
random | 0.6146019109976812

We found that the numbers generated by the random() function each time are random and unpredictable.

Let’s use setseed() to set seed and then generate random numbers, as follows:

SELECT
    setseed(0.1),
    random(),
    random(),
    random();
-[ RECORD 1 ]---------------
setseed |
random  | 0.8499283349327946
random  | 0.6662111687168348
random  | 0.6272665186165547

Then, let’s run the above statement again:

SELECT
    setseed(0.1),
    random(),
    random(),
    random();
-[ RECORD 1 ]---------------
setseed |
random  | 0.8499283349327946
random  | 0.6662111687168348
random  | 0.6272665186165547

Now, we find that the results of both statements are the same. This is the setseed() function sets the same seed for subsequent random() functions in the same statement, so the random() function produces a repeatable random sequence.