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?
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.
Using Postgresql or SQLite, using RANDOM()
:
User.order("RANDOM()").first
Presumably the same would work for MySQL with RAND()
User.order("RAND()").first
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With