PostgreSQL PL/pgSQL random value from array of values

Mo J. Mughrabi picture Mo J. Mughrabi · Jan 13, 2013 · Viewed 10.8k times · Source

How can I declare an array like variable with two or three values and get them randomly during execution?

a := [1, 2, 5] -- sample sake
select random(a) -- returns random value

Any suggestion where to start?

Answer

Andrey Sarul picture Andrey Sarul · Oct 23, 2018

Try this one:

select (array['Yes', 'No', 'Maybe'])[floor(random() * 3 + 1)];