Skip to content

Latest commit

 

History

History
15 lines (14 loc) · 979 Bytes

3006.md

File metadata and controls

15 lines (14 loc) · 979 Bytes

ORDER BY RAND Usage

Sorting by a nondeterministic expression (RAND()) means the sorting cannot benefit from an index:

There is no index containing the values returned by the random function. That's the point of them being ran- dom: they are different and unpredictable each time they're selected. This is a problem for the performance of the query, because using an index is one of the best ways of speeding up sorting. The consequence of not using an index is that the query result set has to be sorted by the database using a slow table scan. One technique that avoids sorting the table is to choose a random value between 1 and the greatest primary key value. Still another technique that avoids problems found in the preceding alternatives is to count the rows in the data set and return a random number between 0 and the count. Then use this number as an offset when querying the data set. Some queries just cannot be optimized consider taking a different approach.