I want to randomly populate a column in my table with the following values: Available, On Hold, Partial Downpayment, Sold/Unavailable, Token
I have tried using the following command but it populates the entire column with the first value it gets.
update mytable
set sold_status = (select (array['Available', 'On Hold', 'Partial Downpayment', 'Sold/Unavailable', 'Token Recieved'])[floor(random() * 5 + 1)])
I know how to achieve this with a programming language, but I would prefer a PostgreSQL query to achive this.
Postgres thinks it is doing you a favor by running random()
only once -- forgetting that random()
is a volatile function.
You can fix this using case
:
update mytable
set sold_status = (case (random()*5)::int when 0 then 'Available' when 1 then 'On Hold' when 2 then 'Partial Downpayment' when 3 then 'Sold/Unavailable' when 4 then 'Token Recieved' end);
Here is a db<>fiddle.