简体   繁体   中英

trying to select random data PostgreSQL

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM