Order of precedence in SQL: WHERE vs HAVING

Photo by Kyle Glenn on Unsplash

Order of precedence in SQL: WHERE vs HAVING


1 min read

If you're just getting started with SQL, this post is for you. So, it's worth looking at the order of precedence of SQL operators.

One particular case is WHERE vs HAVING, especially if you bind the aggregated column to the same column alias as in the input table.

This can save you from some unexpected results ๐Ÿ˜

In short:
- WHERE = filter before aggregation
- HAVING = filter after aggregation

In the example below, the 'quantity' filtered in the HAVING clause is no longer the same 'quantity' in the original table, rather the SUM of quantities per each country bucket.

In practice, I'd rename the aggregated column to something like total_quantity to make it more readable.

Depending what we need, we pick which approach we take, filtering out records before or after aggregation.

No alt text provided for this image

Found it useful? Subscribe to my Analytics newsletter at notjustsql.com.