Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql update each row with a random value

Tags:

sql

postgresql

This is similar to other questions but it appears to vary on a database-by-database implementation. I am using postgres and things like NEWID do not appear to exist.

This is what I want to work:

update foo set bar = (select floor(random() * 10) + 1);

I understand why it doesn't but I can't seem to find a suitable solution that works for Postgres. I want the value of bar to be a random number between 1 and 10 that differs per row.

like image 421
dreamriver Avatar asked Apr 06 '16 22:04

dreamriver


2 Answers

I think that Postgres might optimize the subquery. Doesn't this work?

update foo
   set bar = floor(random() * 9 + 1);  -- from 1 to 10, inclusive
like image 171
Gordon Linoff Avatar answered Oct 22 '22 23:10

Gordon Linoff


update foo set bar = floor(random() * 10) + 1;
like image 26
Alexey K Avatar answered Oct 23 '22 00:10

Alexey K