June 2010
Intermediate to advanced
328 pages
7h 51m
English
The most common SQL trick to pick a random row from a query is to sort the query randomly and pick the first row. This technique is easy to understand and easy to implement:
| Random/anti/orderby-rand.sql | |
| | SELECT * FROM Bugs ORDER BY RAND() LIMIT 1; |
Although this is a popular solution, it quickly shows its weakness. To understand this weakness, let’s first compare it to conventional sorting, in which we compare values in a column and order the rows according to which row has a greater or lesser value in that column. This kind of sort is repeatable, in that it produces the same results when you run it more than once. It also benefits from an index, because an index is essentially a presorted set of the values ...
Read now
Unlock full access