Retrieving Random Elements from an ActiveRecord

This one is short but not something I immediately thought of. It doesn’t rely on an ActiveRecord abstraction, but I originally thought it would need to, so the title is to save future Web searchers.

The idea is that you want to create a list of all the Users, but ordered randomly. It turns out that it’s just this (Postgre)SQL:

SELECT * FROM users ORDER BY random();

So, in Rails:

User.find(:all, :order => 'random()')

Update: Check out the plugin based on this, and the drawbacks to this.

Advertisements

3 Comments

  1. Gudata
    Posted April 17, 2007 at 4:25 pm | Permalink

    for mysql

    User.find(:all, :order => ‘rand()’)

  2. Posted December 14, 2007 at 10:35 am | Permalink

    Hello,

    your method is very good if you want to select all the rows from the table in random order.
    It wouldn’t do very good if you wanted to get just 1 row or even 10 out of 10000.
    Here’s a nice way to get just 1 random row:

    http://robzon.aenima.pl/2007/12/selecting-random-row-from-table.html

    cheers!

  3. Posted August 17, 2011 at 9:32 am | Permalink

    I made a gem for selecting random records that performs much better than order by rand():

    https://github.com/spilliton/randumb


%d bloggers like this: