MySQL Forums
Forum List  »  Quality Assurance

Re: Retrieve a random row, but fast.
Posted by: Jay Paroline
Date: February 04, 2008 02:52AM

Hi there,

Hope this isn't too late to help you.
I'm sure you already know that the performance of ORDER BY RAND() LIMIT 1 is terrible for large tables and doesn't scale at all.

MySQL is not too smart and so I believe what is happening the way you are doing the nested select to get the random value is that MySQL is executing that select for every single row it is doing a comparison with. You don't have that problem when you set a variable because comparing with a variable 50,000 times is a lot faster than running a count(*)*rand() 50,000 times.

The trick is to put your nested select in as a nested JOIN. That way it only gets executed once, much faster.

http://wanderr.com/grooveshark/order-by-slow/2008/01/30/

The part you're looking for is this:
SELECT * FROM Table T JOIN (SELECT FLOOR(MAX(ID)*RAND()) AS ID FROM Table) AS x ON T.ID >= x.ID LIMIT 1;

Options: ReplyQuote


Subject
Views
Written By
Posted
12539
November 28, 2007 07:21AM
6061
November 28, 2007 07:24AM
5213
December 06, 2007 09:02PM
5775
December 11, 2007 12:42AM
Re: Retrieve a random row, but fast.
42828
February 04, 2008 02:52AM
9260
July 22, 2008 07:20AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.