0

I'm trying to select random strings. The problem is it returns the same value for each row. Why is that and how to fix?

SELECT array_to_string(ARRAY(SELECT chr((48 + round(random() * 59)) :: integer) 
FROM generate_series(1,40)), '') AS string FROM generate_series(1,10);

Output:
|  string   |
| duplicate |
| duplicate |
| duplicate |
...

10 rows

1 Answer 1

1

Postgres overoptimizes the subquery. I think this is an error, because it is missing the fact that random() is volatile.

A simple fix is a correlation clause:

select (select string_agg( chr(48 + (random() * 59)::int), '')
        from generate_series(1 ,40)
        where gs.i is not null
       ) AS string
from generate_series(1, 10) gs(i);

I rewrote the logic a bit, so it is simpler. There is no need to use arrays for what you want to do.

Here is a db<>fiddle.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.