Fastest way to find the total length of your postgres query

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.

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