Cuttings: SQL: WHERE vs HAVING SQL: WHERE vs HAVING | Cuttings
Things of interest.


 
February 2, 2017

SQL: WHERE vs HAVING


The difference can be a bit unintuitive.

From Stack Overflow:

WHERE clause introduces a condition on individual rows; HAVING clause introduces a condition on aggregations, i.e. results of selection where a single result, such as count, average, min, max, or sum, has been produced from multiple rows. Your query calls for a second kind of condition (i.e. a condition on an aggregation) hence HAVING works correctly.

As a rule of thumb, use WHERE before GROUP BY and HAVING after GROUP BY. It is a rather primitive rule, but it is useful in more than 90% of the cases.



 

 
© 1997 - 2018 / Info