Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL: Query order by rand() very slow

Tags:

php

mysql

I have to pick 30 random records from a table, except that the query uses one second, and this slows mysql if the content is displayed by many users. This is the query:

SELECT relationship, COUNT(id) AS number FROM FR_user_friends GROUP BY relationship ORDER BY rand() LIMIT 30

Do you know how to speed up this query? Thank you.

If I remove rand() the query is fast. We have to find an alternative for rand()

like image 627
Mario Chiuri Avatar asked Feb 26 '16 18:02

Mario Chiuri


People also ask

Is Rand order slow?

the RAND() function is too slow and consumes too much CPU. it generates a random number for every row and picks the smallest one so that's why it's so slow.

What is rand () in mysql?

RAND() Return a random floating-point value.


1 Answers

ORDER BY RAND() causes the engine to generate random values for all rows, so if you want to select a few rows from a large table, it gives very bad performance.

You could for example generate 30 random values in php in the range [1, maximum row-id] and select the first row with a row-id that is bigger or equal to the random value with LIMIT 1.

SQL-only ways to deal with this you find in How can i optimize MySQL's ORDER BY RAND() function? (but some are not trivial as well).

like image 181
syck Avatar answered Sep 28 '22 08:09

syck