2

For testing a database I'd like to generate a number of rows, each consisting of a set length array of random numbers. I can generate n rows of random numbers easily:

select round(random()*10) from generate_series(1,5);

and I can generate an array of random numbers:

select array(select round(random()*10) from generate_series(1,5));

but if I put them together the array() subquery only gets executed once:

select array(select round(random()*10) from generate_series(1,5)) from generate_series(1,5);

    array     
--------------
 {10,8,1,7,4}
 {10,8,1,7,4}
 {10,8,1,7,4}
 {10,8,1,7,4}
 {10,8,1,7,4}
(5 rows)

How do I get the subquery to run for each row?

1 Answer 1

3

I use the function:

create or replace function random_int_array(int, int)
returns int[] language sql as
$$
    select array_agg(round(random()* $1)::int)
    from generate_series(1, $2)
$$;

select random_int_array(10, 5)
from generate_series(1, 5)

 random_int_array 
------------------
 {3,8,4,7,5}
 {0,10,3,5,4}
 {2,2,0,2,10}
 {8,1,4,3,9}
 {7,4,1,3,6}
(5 rows)

Note that the function should be volatile.


Update. Another approach, generate 25 random values and aggregate them in 5 groups:

select array_agg(round(random()* 10))
from generate_series(1, 25) i
group by i % 5

db<>fiddle.

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

1 Comment

Thank you! That worked, and I learnt about volatile functions too!

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.