How Setseed() Works in PostgreSQL

In PostgreSQL, the setseed() function sets the seed for subsequent random() and random_normal() calls (value between -1.0 and 1.0, inclusive).

The random() function generates a pseudo-random number using a simple linear congruential algorithm. The random_normal() function generates a normally-distributed random number.

If setseed() is called, the results of subsequent random() and random_normal() calls in the current session are repeatable by re-issuing setseed() with the same argument.

Example

Here’s an example to demonstrate how it works.

SELECT 
  setseed(0.8),
  random(), 
  random();

Result:

 setseed | random             | random
---------+--------------------+--------------------
         | 0.7998745861323613 | 0.9776304992484732

Now, if I run the same statement again, I get exactly the same result:

 setseed | random             | random
---------+--------------------+--------------------
         | 0.7998745861323613 | 0.9776304992484732

Just to be clear, here’s the full output in my terminal when I run both SELECT statements at the same time.

SELECT 
  setseed(0.8),
  random(), 
  random();

SELECT 
  setseed(0.8),
  random(), 
  random();

Result:

postgres=# SELECT 
postgres-#   setseed(0.8),
postgres-#   random(), 
postgres-#   random();
 setseed |       random       |       random       
---------+--------------------+--------------------
         | 0.7998745861323613 | 0.9776304992484732
(1 row)


postgres=# 
postgres=# SELECT 
postgres-#   setseed(0.8),
postgres-#   random(), 
postgres-#   random();
 setseed |       random       |       random       
---------+--------------------+--------------------
         | 0.7998745861323613 | 0.9776304992484732
(1 row)

Example WITHOUT Setseed()

Now here’s what happens if I run both statements again, but without the setseed() function.

SELECT 
  random(), 
  random();

SELECT 
  random(), 
  random();

Result:

postgres=# SELECT 
postgres-#   random(), 
postgres-#   random();
       random       |       random       
--------------------+--------------------
 0.8789931563830109 | 0.8981750563441189
(1 row)


postgres=# 
postgres=# SELECT 
postgres-#   random(), 
postgres-#   random();
       random       |      random       
--------------------+-------------------
 0.3630186384623926 | 0.909389353037664
(1 row)

So in this case, the second statement generated a whole new set of random numbers.