[SQL] Where vs Having?
Viktoria
Posted on November 11, 2021
It is easy to be confused with these 2 clauses because A HAVING clause is like a WHERE clause.
⚠️WHERE clause applies to individual rows and HAVING clause applies only to groups as a whole.
A query can contain both a WHERE clause and a HAVING clause.
✔️The WHERE clause is applied first to the individual rows in the tables or table-valued objects in the Diagram pane. Only the rows that meet the conditions in the WHERE clause are grouped.
✔️The HAVING clause is then applied to the rows in the result set. Only the groups that meet the HAVING conditions appear in the query output. You can apply a HAVING clause only to columns that also appear in the GROUP BY clause or in an aggregate function.
📝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.
Posted on November 11, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.