2005
Retrieve Random Records using MySQL Query
Sponsored Links
This is probably an old trick. But I still see some programmer, instead of directly using query, they:
- grab the whole records first
- put them in an array
- generate random number, for example using PHP
rand()ormk_rand() - finally get the record from the array using the random number generated as the index.
If we only need to retrieve one random record from the database, without any further rule, I think those are too much. We can simplify the process by using MySQL query like below:
select * from [table_name] where [additional_condition] order by rand() limit [number_of_record_to_retrieve]
Using MySQL build-in rand() function, we can force the query to sort the result in random order. So if we grab the first n record(s), the return is always different.
And while you're here, why don't you check out our other articles:
Pssst! Most people are coming to this page searching for: 



thanks it works perfect
This is the result of a random query. I was at id=237.
So tricky (=
thx . it’s helpful .