Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: How to retrieve a random row or multiple random rows?

Tags:

mysql

I have a MySQL database table that stores the URLs of photos. I need to pull 5 random records from the database of a particular type. I can pull 5 records like this:

SELECT Photos.* 
FROM Photos 
WHERE Photos.Type_ID = 4 
LIMIT 5

Now I need help trying to figure out how to pull different records every time. How can I retrieve random rows from this result set?

like image 670
Andrew Avatar asked Jan 03 '11 17:01

Andrew


2 Answers

You can use ORDER BY RAND() to get random rows in your query.

like image 170
girasquid Avatar answered Sep 28 '22 02:09

girasquid


SELECT Photos.* 
FROM Photos 
ORDER BY RAND()
LIMIT 5
like image 42
Alex Avatar answered Sep 28 '22 03:09

Alex