Forum: Ruby on Rails Fastest way to find the total length of your postgres query

968fc02da15a5f6bfe8d5b82a7e95ba1?d=identicon&s=25 Tom Choi (lifejuggler)
on 2012-06-29 05:25
Hello,

I know in ruby that when you want to find the size of your query say

[1,2,3,4,5,6] would provide 6 as the total size, length, or even count.

When I try to use size, length, or count on my application, I would get
a pretty darn slow performance (takes around 10 seconds to load each
count and I do it twice). Is there another faster way to get the total
size from the postgres query?

I am using this kind of format in database

e.g: table population [id, race id]
     table race [id, persons id]
     table persons[id, likes]

so if I use "population.race.persons.count" I would get the total size
of the persons in that particular race and population.
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2012-06-29 18:16
(Received via mailing list)
On Jun 29, 4:25am, Tom Choi <li...@ruby-forum.com> wrote:
> Hello,
>
> I know in ruby that when you want to find the size of your query say
>
> [1,2,3,4,5,6] would provide 6 as the total size, length, or even count.
>
> When I try to use size, length, or count on my application, I would get
> a pretty darn slow performance (takes around 10 seconds to load each
> count and I do it twice). Is there another faster way to get the total
> size from the postgres query?

on an active record scope (which includes associations)

- length will always force all the results to be loaded and then the
length of the array is returned
- count will do a select count(*)
- size will either use the length of the array if it is loaded or do a
count(*) if not

So using length if you don't actually want all the objects loaded will
be way slower.

if a simple count is that slow then you probably want to look at your
database indexes - use explain from the psql console to find out how
it is running your query (on rails 3.2 active record will do this for
you if you've turned on auto explains)

Fred
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.