SQL Group By Vs. Having
A great summary of the SQL Having and Group By clause differences:
Souce: http://archives.postgresql.org/pgsql-sql/2000-04/msg00146.php
... The thing to remember about WHERE vs HAVING is that WHERE filters tuples
before they are aggregated into groups, while HAVING filters afterwards.
Whatever tuples get past the WHERE filter are collected into groups,
and then HAVING is applied to the per-group output tuples to filter out
whole groups that you don't want.
In practice, you only need HAVING if you want to filter on aggregate
functions of the groups. For instance, if in your example you didn't
want to hear about codons with sum(nexamples) < 100, you'd do
SELECT codon, sum(nexamples)
FROM summary
WHERE expl = 'f'
GROUP BY codon
HAVING sum(nexamples) >= 100;
Once you realize that HAVING applies post-group, it should be pretty
clear why the HAVING clause can only reference group-column values
and aggregate results. Anything else is not well-defined at the
group level. For instance, the group for codon=286 has several
different values for nexamples, so you can't ask about a specific
value of nexamples in the HAVING clause --- which one would you get?....
tom lane