Aggregate functions compute a single result value from a set of input values. Table 6-33 show the built-in aggregate functions. The special syntax considerations for aggregate functions are explained in Section 1.2.5. Consult the PostgreSQL 7.3.21 Tutorial for additional introductory information.
Table 6-33. Aggregate Functions
It should be noted that except for count, these functions return a null value when
no rows are selected. In particular, sum of no rows returns null, not zero as one
might expect. The function coalesce
may be used to substitute zero for null when necessary.
The aggregates do not make use of indexes. If I understand correctly, they do a seq scan even if an index is available. Thus, on tables larger that a few thousand rows they take forever to complete.
For production use all queries with MIN() and MAX() should be rewritten with SELECT ... ORDER BY ... LIMIT 1.
The lack of support for indexing with aggregates has been discussed ad nauseum on the mailing lists and is in the FAQ. Suffice it to say that our inability to use indexes for MIN() and MAX() is due to the ectensibility of PostgreSQL; it is the price we pay for supporting custom aggregates and data types.
Fixes for MIN() and MAX() have been proposed for PostgreSQL 7.5, but the implementation is far more difficult than it would appear to the layman.
Here\'s how I\'ve been able to do a \"conditional count\":
Define a table:
create table cities (id serial not null unique, title varchar, state varchar);
Assume that you want a count of all the cities, as well as a count of those just in California:
select count(*) as total, sum(case when state=\'CA\' then 1 else 0 end) as ca_total from cities;
No need to group by - you\'ll get a count of all the cities, as well as just those in California!
I think that case bypasses indexes, so this might not be a good performer.