Re: GROUP BY / HAVING - am I being thick?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: "Andrew C(dot)R(dot) Martin" <a(dot)c(dot)r(dot)martin(at)reading(dot)ac(dot)uk>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: GROUP BY / HAVING - am I being thick?
Date: 2000-04-13 15:37:45
Message-ID: 10966.955640265@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

"Andrew C.R. Martin" <a(dot)c(dot)r(dot)martin(at)reading(dot)ac(dot)uk> writes:
> For each codon number, I want to obtain sum(nexamples) where expl = 'f';

> The following looks as though it should work according to "The
> Practical SQL Handbook" (Bowman, Emerson & Darnovsky)

> SELECT codon, sum(nexamples)
> FROM summary
> WHERE expl = 'f'
> GROUP BY codon
> HAVING expl = 'f';

Just drop the HAVING clause and that will work --- you're already
filtering by expl at the WHERE stage, so there's no need to do it
again after grouping (quite aside from the fact that you can't
reference an ungrouped column in HAVING).

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?

regards, tom lane

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Andrew C.R. Martin 2000-04-13 15:52:12 Re: GROUP BY / HAVING - am I being thick?
Previous Message Moray McConnachie 2000-04-13 14:51:35 Re: Subtracting from a date