Using ORDER BY RAND() is considered antipattern because you force the database to perform a full table scan and an expensive sort operation.
To take advantage of query caching, you can create a hybrid solution, for example:
// take all image ids $keys = $db->query('SELECT image_id FROM images')->fetchALL(PDO::FETCH_COLUMN, 0); // pick 30 $random_keys = join(',', array_rand(array_flip($keys), 30)); // query those images only $values = $db->query("SELECT * FROM images WHERE image_id IN ($random_keys)")->fetchAll(PDO::FETCH_ASSOC);
The above key request can be cached in PHP, so it can be used for more frequent requests. However , when your table is in the range of 100 thousand or more, I would suggest creating a separate table with image identifiers in a randomized order with which you can join the image table. You can fill this one or more times a day with ORDER BY RAND() .
source share