Friday, June 01, 2007

Tip: Selecting random row with MySQL and ActiveRecord

Here's a quick tip on how to select a random model instance from an ActiveRecord model when the database is MySQL:

Model.find(:first, :order => 'rand()', :limit => 1)

Please note:
  • Using rand() is MySQL specific
  • It performs bad when there are many rows in table (rand() is applied to all rows and then all rows are sorted)

No comments: