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.

Leave a Reply