views:

49

answers:

1

I haven't been able to find a very good way of getting 10 random records out of a sqlite database. Seen a few examples that work with mysql, but they don't seem to work well with sqlite even though I am trying to us Random() instead of rand().

I have tried to get random numbers and then get the records by id, but for some reason I am getting nil result for a couple of them. I was curios if there was a better approach.

Also as a side note this is day 3 for my using Ruby and Rails so still a bit new to it.

+1  A: 

How about

User.all.sort_by{rand}.slice(0,10)

?

This is just for testing, right?

Edit: No longer database-independent, but, for sqlite3:

User.find(:all, :order => "RANDOM()", :limit => 10)

and for mysql:

User.find(:all, :order => "RAND()", :limit => 10)
unsorted
That worked great, thank you.Actually it is for a project where on the home page I want to display several random things. Fortunately it is a personal project so performance doesn't really matter.
percent20
Oh, so it is for the actual website rather than just, say, in the console. Okay, editing my answer to give a better way that works for sqlite3. I just tested it in my console (backed by sqlite3) and it seems fine, so I'm not sure why it is failing for you. I agree with your comment about RAND() vs RANDOM().
unsorted
see also http://trevorturk.com/2007/12/04/random-records-in-rails/... looks like a useful and relevant article (especially as a result of the comments)
unsorted
The initial approach is quite naive and will bring your server to it's knees with any sizable amount of users. It's best to use the second approach that lets the database do the heavy lifting. Even letting the DB do the hard work, this will still be dog slow after any non-trivial number of records. See this Rails issue for more details why: https://rails.lighthouseapp.com/projects/8994/tickets/1274-patch-add-support-for-order-random-in-queries
Preston Marshall