19

I want update my table with random values from given set, not from another table.

e.g. value1, value2, value3

and MySQL query should be update all records from above values.

I am looking similar type of solution but with random string values from given set: Update column with random value

4 Answers 4

41

I would use the elt() function:

update tablename
    set columnname = elt(floor(rand()*3) + 1, 'value1', 'value2', 'value3');

elt() chooses a particular element from a list. rand() produces a random values.

2
  • 4
    Love this function. Very useful if you 18,600 UK postcodes you want to randomly populate a table with. I would have had to create a php script or something if I thought I would have had to do a case, when, then for 18k values! Commented Sep 2, 2016 at 14:17
  • At the risk of spamming: I stumbled upon this because I was trying to autopopulate a postcode table too! Cool function; I didn't know you could populate random data from within the SQL console itself :D
    – Hippo
    Commented Jul 25 at 13:12
13

Use floor(rand()*3) to generate a random number among 0, 1, and 2, then use case when to assign value

update test
set i = (case floor(rand()*3) 
         when 0 then 0 
         when 1 then 10 
         when 2 then 20 
         end);

fiddle

0
5

Try with CEIL and RAND function

UPDATE `table`
SET `column`=(CASE CEIL(RAND()*3)
              WHEN 1 THEN 'value1'
              WHEN 2 THEN 'value2'
              WHEN 3 THEN 'value3'
          END);
1
  • Hi, I want to use this, but by selecting reference data from a foreign key MS SqlServer Db table, can you show me this with select random (maybe 3 or 4 values) from a Ref table and update the current table with that.
    – aggie
    Commented Jan 8, 2016 at 23:33
1

Rand() returns the same value for all the rows within a given call. Use newid() to get a random number for every row.

https://web.archive.org/web/20071228004107/http://articles.techrepublic.com.com/5100-10878_11-6089823.html

Update dbo.Employees 
Set City= (Case abs(checksum(NewId()) % 3)
        WHEN 0 THEN 'Lndon'
        WHEN 1 THEN 'New York'
        WHEN 2 THEN 'Paris'
    END
        );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.