Reputation: 19237
We'll do this on almost every "hit" to our site. Hosted at Heroku, running Postgres.
Pretty common scenario... a single method in our model gets the COUNT of records matching a condition and also the LAST record matching the same condition.
in realworld use, the COUNT will typically be less than 20. The table has about 20 fields, none are larger than 200 chars.
currently I do TWO queries, n=widget.count(conditions) and then I do z=widget.last(conditions)
but of course I could also do allfound = widget.find(conditions) then get n=allfound.count and z=allfound.last.
Which is "better"? And what are the tradeoffs? (There's always tradeoffs, right?)
Cheers! JP
Upvotes: 0
Views: 283
Reputation: 11395
I would stick with two queries because:
If you really want to know the real answer, the only way to know for sure is to benchmark it. Create a Rake task that does the benchmark and then run it on Heroku.
Upvotes: 1
Reputation: 21884
Did you check the logs? Are you sure Rails wont do 2 queries as well in the second case?
Upvotes: 0