Andrew
Andrew

Reputation: 238747

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

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?

Upvotes: 7

Views: 2957

Answers (3)

Nishant
Nishant

Reputation: 55866

Google points to this detailed page. Looks like it works. I am sure it can't ensure distinct record each time, but worth trying. http://akinas.com/pages/en/blog/mysql_random_row/

Upvotes: 2

Alex
Alex

Reputation: 403

SELECT Photos.* 
FROM Photos 
ORDER BY RAND()
LIMIT 5

Upvotes: 6

girasquid
girasquid

Reputation: 15526

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

Upvotes: 8

Related Questions