WHERE
is used to select data in the original tables being processed.
HAVING
is used to filter data in the result set that was produced by the query. This means it can reference aggregate values and aliases in the SELECT
clause.
For instance, can write:
SELECT t1.val - t2.val diff
FROM t1 JOIN t2 ON (some expression)
HAVING diff > 10
This wouldn't work using WHERE
because diff
is an alias, not one of the original table columns. You could write instead:
SELECT t1.val - t2.val diff
FROM t1 JOIN t2 ON (some expression)
WHERE t1.val - t2.val > 10
but then it may have to do all the subtractions twice: once for selecting, and again to produce the result set.