Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't use mysql ORDER BY RAND()?

Tags:

mysql

I saw many websites saying don't use ORDER BY RAND(), eg http://forge.mysql.com/wiki/Top10SQLPerformanceTips So I run a test, I have tested the speed and performance on 20k records table, 10k records among them have the username="username" :

SELECT username FROM testingspeed WHERE username='username' ORDER BY RAND();

The result :

Showing rows 0 - 29 (10,000 total, Query took 0.0119 sec).
id = 1 
select_type = SIMPLE
table = testingspeed
type = ref
posible_keys = username
key = username
key_len = 32
ref = const
rows = 3225
Extra = Using where; Using index; Using temporary; Using filesort

since it took 0.0119 seconds only to execute the query, it should be very good speed, why people still say DON'T use ORDER BY RAND()? Why 3225 rows are affected only? Why not 10,000 rows are affected?

like image 267
zac1987 Avatar asked Jul 06 '11 07:07

zac1987


People also ask

What does order by rand () do?

If you ORDER BY RAND() a random number is calculated for every single row in the table. This is because it must calculate the random value for every row in order to know which row generated the largest value.

How do I sort in MySQL?

The MySQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.


1 Answers

The problem of ORDER BY RAND() is that as your explain tells you the "Using temporary" and the "Using filesort". For each request a temporary table is created and sorted. Thats a pretty heavy operation. It will probably not matter when your database is not under heavy load but it will cost a lot of performance.

like image 56
fyr Avatar answered Sep 23 '22 16:09

fyr