Keith Johnson
Keith Johnson

Reputation: 730

Retrieving x number of random objects

I'm just trying to load 5 random objects in a rails controller

Thing.all(:limit => 5, :order => "RANDOM()")

Is that the least expensive way to do it?

Upvotes: 0

Views: 47

Answers (2)

dedennufan
dedennufan

Reputation: 91

This is the best way:

Thing.all.sample(5)

Upvotes: 0

Taryn East
Taryn East

Reputation: 27747

Short answer: no.

What you have asked the db to do is: go order the entire thing table in a random order... then grab me five of them. If your thing table has a lot of rows... that's a very expensive operation.

A better option (if the ids are auto-increment and thus likely concurrent) is to generate a set of random ids within the id-range for your thing table and go fetch these individual things by those ids.

Upvotes: 1

Related Questions