WHERE

The WHERE statement is one of the most basic ways to filter data. In the example below, a specific amount of money is queried from the payment table using the WHERE statement. This filters out any value in the amount column that is less than 11 euros. In other words, what is returned is any row in which the amount is greater than 11 euros.

HAVING

The HAVING statement can only be used in an aggregate function. An aggregate function is when the values of multiple rows are grouped together to form a single summary value. A good example of an aggregate function is the GROUP BY statement which groups the value of a set of rows based on a specific criterion. The difference between HAVING and WHERE is that HAVING applies to the result of a GROUP BY operation, WHERE applies before data are grouped by GROUP BY.

The example below returns the total amount spent by each customer id:

However, a more realistic question might ask which customers spent more than 170 Euros? The HAVING statement can be used here after the data has been grouped by customer_id, to filter out any rows where the total amount spent is less than 170 euros.

The Difference between WHERE and HAVING

The main difference is that the HAVING statement can only be used after an aggregate function, whereas the WHERE statement can be used on non-aggregated data.

In short, HAVING is always placed after the WHERE and GROUP BY clauses.

An example of this can be seen below: