MySQL, Select Random string values 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 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.

Advertisements

One thought on “MySQL, Select Random string values from a list of strings

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s