daily gadgets, computers, and electronic news
27/05
2005

Retrieve Random Records using MySQL Query

This is probably an old trick. But I still see some programmer, instead of directly using query, they:

  1. grab the whole records first
  2. put them in an array
  3. generate random number, for example using PHP rand() or mk_rand()
  4. 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.

Retrieve Random Records using MySQL Query is written by cosa and posted under Programming , , . If you like it, you might consider subscribing to our feed, follows us on Twitter, or receive our latest posts via email. Or else, you could also or store it to your favourite social bookmark sites. Further information about this article can be found.

3 Comments »

  1. 1
    david says:

    thanks it works perfect

  2. 2
    John says:

    This is the result of a random query. I was at id=237.

  3. 3
    hadziq says:

    So tricky (=

    thx . it’s helpful .

Leave a comment