October 13, 2011

MySQL, select random string from a list of strings

If you have ever wondered how to select a random string value from a list of given string in MySQL?

If you have ever wondered how to select a random string value from a list of given string in MySQL? The following might be helpful :

UPDATE profile SET `GEO`= ELT(FLOOR(RAND()*8)+1, 
        'US', 'CA', 'FR', 'DE' , 'UK' , 'IR' , 'RU' , 'GR');

The code above sets the GEO field of the profile table to random values selected from a list. That would help when you’re populating dummy information in to your tables for testing.

ELT Command will return the string of a given index, and by doing a FLOOR(RAND()) , you can easily randomize the given index.

Hope it helps.

comments powered by Disqus
comments powered by Disqus