Skip to content
Advertisement

Select Random Row from SQL Using PHP

I want to request 5 random rows from my SQL table using php. for instance, i need to:

mysql_query("SELECT * FROM catalogue >> not sure what goes here << LIMIT 5");

Advertisement

Answer

SELECT * FROM catalogue order by RAND() LIMIT 5

Edit:

For what its worth, Please note that using rand() on a table with large number of rows is going to be slow. This can actually crash your server.

Some Solution:

MediaWiki uses an interesting trick (for Wikipedia’s Special:Random feature): the table with the articles has an extra column with a random number (generated when the article is created). To get a random article, generate a random number and get the article with the next larger or smaller (don’t recall which) value in the random number column. With an index, this can be very fast. (And MediaWiki is written in PHP and developed for MySQL.)

But this is for a single random row only.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement