Selecting a random row using MySQL

There are many examples where you would need to retrieve a random record or more from a set of tables. For example your page template may be cycling through QOTDs, testimonials, offers, specials, and so forth.

To retrieve a random row in MySQL, use the ORDER BY RAND() statement to randomly order the rows of a table. Then use LIMIT x to retrieve the first x rows from the randomised representation of the table.

For example:

SQL:
  1. /*  Retrieve 5 random special offers to display in your e-commerce store's sidebar */
  2. SELECT  offer_id
  3. FROM    special_offers
  4. ORDER BY RAND()
  5. LIMIT 5

Of course, we can make our query as complex as needed, and then randomly order the resultset.

SQL:
  1. SELECT  so.offer_id, i.title
  2. FROM    special_offers so
  3.           LEFT JOIN items i ON (so.item_id = i.item_id)
  4.           LEFT JOIN item_categories ic ON (i.item_id = ic.item_id)
  5. WHERE   ic.category_id = 2344
  6. ORDER BY RAND()
  7. LIMIT 5

Leave a Reply

Your email address will not be published. Required fields are marked *

*


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>