45

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.

2 Answers 2

60

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
Sign up to request clarification or add additional context in comments.

2 Comments

my take is to create a random function and use it. CREATE OR REPLACE FUNCTION random_between(low INT ,high INT) RETURNS INT AS$$ BEGIN RETURN floor(random()* (high-low + 1) + low); END; $$ language 'plpgsql' STRICT; Then use the function update foo set bar = random_between(1,10)
@Doogle: this is not required to +1
17
update foo set bar = floor(random() * 10) + 1;

2 Comments

This was very helpful in anonymizing my accounts table's emails: UPDATE accounts SET email = (select 'anonymized-' || (select floor(random() * 1000000) + 1 where accounts.id = accounts.id) || '@localhost')
updated. there is no need in "where accounts.id = accounts.id". just call function directly. without 'select'.

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.