Is it true that ORDER BY rand()
performance is very slow compared to other solutions? If yes, what are better ways to select random row(s) from the database?
My query:
SELECT sName FROM bpoint WHERE placeID=? ORDER BY rand() LIMIT 1;
asked Apr 29, 2013 at 22:28
1 Answer 1
Yes, ORDER BY RAND()
can be very slow in larger result-sets.
An option is to fetch resultset with this statement (into an array):
SELECT sName FROM bpoint WHERE placeID=?;
After that - use array_rand($resultset)
to get a randomized item from the $resultset
query.
Hassaan
7,7107 gold badges34 silver badges53 bronze badges
answered Apr 29, 2013 at 22:37
bestprogrammerintheworld bestprogrammerintheworld
5,5189 gold badges48 silver badges75 bronze badges
9 Comments
Biker John
So, it is php function array_rand() faster?
bestprogrammerintheworld
@JamaicaBob - it really depends on how large the resultset is. How many rows do you have in your table bpoint?
Biker John
approximately 10.000 rows
bestprogrammerintheworld
@JamaicaBob - ok, I THINK it would be faster with an array then, but I'm not sure. I guess you will just have to test and see difference. How long does the actual query take now?
Wes
@BikerJohn - Older question, but depending on your programming language, php has mt_rand(). I implemented this by doing a quick count of the number of rows I have, and then doing $random = mt_rand(1,$count) to get a random int in the range, then SELECT * FROM 'table' WHERE ID = $random; Performance numbers jumped significantly. Only works if you have unique IDs though (auto_increment ftw!)
|
default
i
toj
, you could filterWHERE column >= FLOOR(i + RAND() * (j – i)) ORDER BY column LIMIT 1
. But if there are gaps, you won't obtain a perfectly uniform distribution of probabilities...