Efficiently Selecting Random Rows From a MySQL Table
- - on
- in uncategorized -
It’s tempting to simply use MySQL’s RAND() function to select random records from a table. Consider the following query:
SELECT FLOOR(7 + (RAND() * 5));
However, when considering overhead, this is a rather expensive method to employ. This becomes glaringly apparent when dealing with large datasets.
One effective solution is to select the first and last ids, and let PHP generate the random integer (id). Then, simply select the record using the random integer.
Tags: Technical, Work