Selecting a random row from MySQL.. efficiently!
- Published January 16th, 2006 in Tips & Tricks, MySQL
Selecting a random row from a MySQL table is quite easy…
SELECT * FROM table ORDER BY RAND() LIMIT 1
..if you don’t praise scalability. According to Jan, running the SQL statement mentioned above on a 1M table row would take about 58 minutes. So, besides taking hell to complete it is also a good way of doing a DoS.
Taking this in mind, Jan suggests a much cleaner solution. Unfortunately it only works on MySQL >= 4.1 so that’s why I made the upgrade. It was worth anyway.




No Responses to “Selecting a random row from MySQL.. efficiently!”