DelphiFAQ Home Search:

How to pick a random record from a mysql table

 

comments1 comments. Current rating: 4 stars (1 votes). Leave comments and/ or rate it.

Question:

I have a huge table in mysql with suitable passwords and want to pick a word from this table. If I use a simple select statement, I always get the first word.
How can I pick a random record from a mysql table (or result set, in general)?

Answer:

Use the order by RAND() phrase, and for performance reasons, combine it with LIMIT 1 as shown in the example below.

There was a bug in older mysql versions (prior to version 4) where this RAND() phrase did not really lead to truely random results but always to the same rows after a connection was started.

This has been resolved with version 4.

select word from wordlist ORDER BY RAND() LIMIT 1

Comments:

2007-11-19, 00:28:46
anonymous from Philippines  
rating
Great! Thanks a bunch!=)

 

 

NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.
 

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity.
The owner of this web site reserves the right to delete such material.

photo Add a picture: