7

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?

Andrew
  • 227,796
  • 193
  • 515
  • 708
  • Dup of [What is the best way to request a random row in pure SQL?](http://stackoverflow.com/q/19412/90527) – outis Mar 29 '12 at 18:09

3 Answers3

8

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

girasquid
  • 15,121
  • 2
  • 48
  • 58
6
SELECT Photos.* 
FROM Photos 
ORDER BY RAND()
LIMIT 5
Alex
  • 403
  • 3
  • 5
2

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/

Nishant
  • 54,584
  • 13
  • 112
  • 127