I must be googling in the wrong way or I'm having a stupid moment in time.
What's the difference between HAVING
and WHERE
in an SQL SELECT
statement?
EDIT: I've marked Steven's answer as the correct one as it contained the key bit of information on the link:
When
GROUP BY
is not used,HAVING
behaves like aWHERE
clause
The situation I had seen the WHERE
in did not have GROUP BY
and is where my confusion started. Of course, until you know this you can't specify it in the question.
Many thanks for all the answers which were very enlightening.
In an Aggregate query, (Any query Where an aggregate function is used) Predicates in a where clause are evaluated before the aggregated intermediate result set is generated,
Predicates in a Having clause are applied to the aggregate result set AFTER it has been generated. That's why predicate conditions on aggregate values must be placed in Having clause, not in the Where clause, and why you can use aliases defined in the Select clause in a Having Clause, but not in a Where Clause.
HAVING
is used when you are using an aggregate such asGROUP BY
.One way to think of it is that the having clause is an additional filter to the where clause.
A WHERE clause is used filters records from a result. The filter occurs before any groupings are made. A HAVING clause is used to filter values from a group
I use HAVING for constraining a query based on the results of an aggregate function. E.G. select * in blahblahblah group by SOMETHING having count(SOMETHING)>0
Source
When
GROUP BY
is not used, theWHERE
andHAVING
clauses are essentially equivalent.However, when
GROUP BY
is used:WHERE
clause is used to filter records from a result. The filtering occurs before any groupings are made.HAVING
clause is used to filter values from a group (i.e., to check conditions after aggregation into groups has been performed).Resource from Here