How to SELECT a Random Record in SQL

Submitted by Amir Shevat on Thu, 07/30/2009 - 09:40

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.

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

Powered by Drupal, an open source content management system