Thursday, January 13, 2011

Selecting random record in MySQL

The random number generators are often used in almost all  kinds of application. The random numbers are generated using well known random number generator API. But what about selecting a random record from a database. There are cases we need this. for example- if you want to suggest a random picture to user in a web application. Pictures are stored in database. Fortunately databases provide this kind of feature but unfortunately different databases have different query to achieve this. Here is how this is achieved in MySQL  - 
SELECT columnName FROM tableName
ORDER BY RAND()
LIMIT 1

The value of limit can be changed to number of records to fetch.

No comments:

Post a Comment