1 min read

Retrieving random row from a table in ActiveRecord

Syed Aslam

There are multiple ways to retrive a random row from a table:

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

This is fast and requires no custom SQL. 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, 8 and get 3 at random, this method will take 3rd row, which has ID = 4.

Another way of doing this is use a randomly generated number (up to the current record count) but would require two queries:

offset = rand(Model.count)

rand_record = Model.offset(offset).first

Yet another way of doing the same which is quite fast with smaller to medium datasets is to use RANDOM()

Model.order('RANDOM()').first

RAND() in MySQL, however it is not recommended to use RAND() in MySQL and you should atleast add `limit to the query.