Practical SQL

Order of precedence in SQL: WHERE vs HAVING

Constantin LunguUpdated 1 min read

Photo by Kyle Glenn on Unsplash

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.

Input data: quantity and country rows 10 UK, 15 UK, 15 US, -5 US, -10 FR and -5 FR.

SELECT
  country,
  SUM(quantity) AS quantity

FROM input_data

GROUP BY country

HAVING quantity > 0
SELECT
  country,
  SUM(quantity) AS quantity

FROM input_data

WHERE quantity > 0

GROUP BY country

BigQuery results side by side: the HAVING query (left) returns UK 25 and US 10, the WHERE query (right) returns UK 25 and US 15.


Enjoyed this? Here are some related articles you might find useful: