Memory App
 




Slow

Order by rand is very slow.

SELECT * FROM article ORDER BY RAND() LIMIT 1;
(1/4)

Fast

Order by index (random) is fast.

ALTER TABLE article ADD random FLOAT NOT NULL;

ALTER TABLE ADD INDEX random (random);

UPDATE article SET random = RAND();

INSERT INTO article (..., random) VALUES (..., RAND());

SELECT * FROM article WHERE random > 
    (SELECT RAND() as rand) ORDER BY random LIMIT 1;
(2/4)

Daily


SELECT * FROM article ORDER BY rand("20190131") # date(Ymd)    
(3/4)

Array


SELECT * FROM documents WHERE id IN (3, 7, 5) ORDER BY FIELD (id, 3, 7, 5)
http://www.electrictoolbox.com/mysql-random-order-random-value/ http://stackoverflow.com/questions/1244555/how-can-i-optimize-mysqls-order-by-rand-function http://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html#function_rand

Questions