Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5—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?

like image 427
Mirror318 Avatar asked Mar 28 '18 03:03

Mirror318


3 Answers

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.

like image 122
Ganesh Avatar answered Nov 12 '22 15:11

Ganesh


Using Postgresql or SQLite, using RANDOM():

User.order("RANDOM()").first

Presumably the same would work for MySQL with RAND()

User.order("RAND()").first
like image 32
fongfan999 Avatar answered Nov 12 '22 14:11

fongfan999


Well after lot of trials and errors i've found this solution to be helpful and error free.


Model.find(Model.ids.sample)

Model.ids will return an array of all ids in the database. we then call sample method on that array that will return a random item in the list.

like image 7
Ahmed Khattab Avatar answered Nov 12 '22 15:11

Ahmed Khattab