The HAVING
clause
HAVING
clauses can place extra restrictions on the output rows of an aggregate query — just like WHERE
clauses do in record-by-record queries.A HAVING
clause can impose conditions on any output column or combination of columns, aggregate or not.
As far as NULL
is concerned, the following two facts are worth knowing (and hardly surprising, I would guess):
-
Rows for which the
HAVING
condition evaluates toNULL
won’t be included in the result set.(“Onlytrue
is good enough.”) -
“
HAVING <col> IS [NOT] NULL
” is a legal and often useful condition, whether<col>
is aggregate or not.(But if<col>
is non-aggregate, you may save the engine some work by changingHAVING
toWHERE
and placing the condition before the “GROUP BY
” clause.This goes for any condition on non-aggregate columns.)
For instance, adding the following clause to the example query from the “GROUP BY
” paragraph:
...HAVING Dept IS NOT NULL
will prevent the first row from being output, whereas this one:
...HAVING SUM(Salary) IS NOT NULL
suppresses the sixth row (the one with Dept = 120).