Wednesday, July 13, 2011

MySql ORDER BY RAND()

Baca dibeberapa referensi jangan pernah menggunakan 'Order by Rand()', alasannya "The ORDER BY RAND() operation actually re-queries each row of your table, assigns a random number ID and then delivers the results. This takes a large amount of processing time for table of more than 500 rows." (http://www.webtrenches.com/post.cfm/avoid-rand-in-mysql)

Yes, aku butuh waktu 14.1786 sec hanya untuk mendapatkan hasil dari query

SELECT *
FROM XXXXXXXXXX
ORDER BY RAND( )
LIMIT 1000

Hanya untuk 'ngambil' 1000 row dari 1,6jt lebih record

Tapi dengan sedikit modifikasi, menjadi

SELECT *
FROM XXXXXXXXXX
WHERE RAND()>0.9
ORDER BY RAND()
LIMIT 1000

Membutuhkan waktu 1.8116 sec, karena 'where RAND()>0.9' mengurangi 90% overhead dari pengurutan. Lumayan membantulah.

Kalau query-nya seperti ini

SELECT *

FROM xxxxxxxxxxx b

WHERE b.participantId <> RAND( 1 )

ORDER BY RAND( 1 )

LIMIT 1000


Lebih cepat lagi 0.0030 sec, hheheheheh, Thx pak chery ngasih solusi lain. Disebutin nama fieldnya juga sepertinya masih sama cepat. :)