Retrieving random row from a table

April 5, 2011 by Syed Aslam

To retrive a random row from a table you have do just this:

 Model.find :first, :offset => ( Model.count * rand ).to_i 

This is fast and requires no custom SQL queries! All this does is count number of rows in a table and select one row at some offset while still having the table ordered by primary key.

It uses offset (limit), not ID number, so it chooses n-th found row, not a row with ID equal to n. So if you have IDs like 1, 2, 4, 8and get 3 at random, this method will take 3rd row, which has ID = 4.

© 2017 | Follow on Twitter