How to SELECT a Random Record in SQL

Sometimes we need to retrieve a random entry from the Database. An examples for that could be trying to display “random posts” or “a random image”.

Some developers pull some or all of the records and then preform the randomization in the application tier (AKA in code).

In most cases letting the Database return random eateries could prove to be a better option performance-wise.

Here is how it is done:

SELECT fields FROM table AS alias WHERE condition ORDER BY rand() ASC LIMIT number

The key section responsible for the randomization in this statement is the “ORDER BY rand()”. Adding this would retrieve X amount of random records from the database without additional application logic.

Share the love...Tweet about this on TwitterShare on LinkedInShare on Google+Share on Facebook

Amir Shevat

Amir Shevat is the global Startup Outreach lead in Google Developer Relations (g.co/launch). Previously, Amir Led Google Campus Tel Aviv and was the co founder of several startups.

You may also like...

Leave a Reply

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