Thursday, April 21, 2011

Is there a faster way to get a random record from a MySQL table through ActiveRecord?

In a Rails application, I'm using this to get a random row from a MySQL table:

contact = Contact.find(:all, :limit => 1, :order => 'RAND()')[0]

Even though the table only has about 20,000 rows it takes a couple seconds. Does anyone know of a faster way?


Update

Also tried just running the SQL in the console...

SELECT * FROM `contacts` ORDER BY RAND() LIMIT 1

It still takes a long time, like two or three seconds.

From stackoverflow
  • I don't think my first answer will help you. Perhaps this Article will

    Ian Terrell : Be sure to read the comments to that article. Potentially buggy or non-optimal behavior depending on what you're trying to do and how distributed across id-space your instances are.
  • Get one rand from ruby and then transform it to your primary key

0 comments:

Post a Comment