Learning Journal

Random Rows in MySQL

I have to admit that I had quite some trouble figuring out how I could get MySQL to return some random rows in a query. It was something I had to figure out for myself when I wanted to get a list of random web sites off GIDTopsites to place on these pages here.

As usual, everything fell nicely into place when I went out looking for the information and it was SO simple…


Using rand(), I just had to add it to my SQL query (in PHP) like this:

//  random row, mysql example query in php
$sql = "SELECT * FROM tablename
        WHERE somefield='something'
        ORDER BY RAND() LIMIT 5";

//  or, something like this
$sql = "SELECT * FROM tablename
        ORDER BY RAND()";

That’s it, that’s all you have to do to get MySQL to return a set of random rows for you to do what you will with it.

Leave a Reply

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