ruby-on-railsactiverecordruby-on-rails-5

Rails—get a random record from db?


To get a single random record from the db, I'm currently doing:

User.all.sample

But when there are 100000+ users, it takes a few seconds to load them all, just to select one.

What's the simplest way to get load a single random user from db?


Solution

  • You can try following database independent query:

    User.find(User.pluck(:id).sample)
    [DEBUG]  (36.5ms)  SELECT `users`.`id` FROM `users`
    [DEBUG] User Load (0.5ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 58229 LIMIT 1
    

    this one fires two queries but this one is performance efficient as it took only 37ms to get single random user record.

    whereas the following query will take around 624.7ms

    User.order("RAND()").first
    [DEBUG] User Load (624.7ms)  SELECT  `users`.* FROM `users`  ORDER BY RAND() LIMIT 1
    

    I have checked this for 105510 user records.