2

I am trying to generate random data (in volume) and was trying to use PostgreSQL's random() function with generate_series(), as shown:

SELECT
  (SELECT random()) AS a,
  (SELECT random()) AS b,
FROM generate_series(1,3);

However, I get the same random values per row:

   a   |   b   
-------+-------
 0.124 | 0.443 
 0.124 | 0.443 
 0.124 | 0.443 

How can this be solved?

2
  • 1
    You should not edit the question if it invalidates existing answers. If this is not what you wanted to ask, delete the question and ask a new one.
    – mustaccio
    Commented Nov 10, 2021 at 19:45
  • Thanks @mustaccio, understood.
    – ssn
    Commented Nov 11, 2021 at 0:07

2 Answers 2

3

Yes, quite an annoying "feature". You can fix the problem by stirring in a little of the outer query, in a way that doesn't change the result meaningfully.

SELECT
  (SELECT random()+f/1e39) AS a,
  (SELECT random()+f/1e39) AS b
FROM generate_series(1,3) f(f);
2
  • can you explain what +f/1e39 is doing with the generated random() number? Commented Aug 30, 2023 at 21:47
  • 2
    It is just making the subselect formally depend on f from the outer select, so that it gets re-executed for every row. It does this by adding a microscopically small amount to the random value.
    – jjanes
    Commented Aug 31, 2023 at 0:33
1

You can achieve that by calling the random() function separated from the generated_series() call like this:

    SELECT
    num,
    random() AS rand1,
    random() AS rand2
    FROM generate_series(1,10) AS gs(num)

But if you want to do some operations on the random columns, you will have to repeat the random() function call over and over as you can't call rand1 or rand2 directly.

A quick way to fix this is to use a CTE like this:

WITH rand AS (
    SELECT
    num,
    random() AS rand1,
    random() AS rand2
    FROM generate_series(1,10) AS s(num)
)
SELECT *
FROM rand
;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.