MySQL HAVING Clause

The HAVING clause can be used as a filter on a GROUP BY clause. It is used to apply a filter to a group of rows or aggregates. This is in contrast to the WHERE clause, which is applied before the GROUP BY clause.

Consider the following example.

Result:

Screenshot of record set

In the above example, we use the HAVING clause to filter the result set to only those records that have a count of greater than three (i.e. HAVING COUNT(*) > 3).

If we didn't use the HAVING CLAUSE, it would have returned all records — regardless of their count. Like this:

Screenshot of record set

Another Example

Here's a slightly more advanced example that uses an INNER JOIN to retrieve data from two tables, as well as a SUM() function to add up the totals that each customer has paid.

Result:

Screenshot of record set

Here, we use the HAVING clause to return only those records where the total amount returned by the SUM() function exceeds 180.

We also sort this amount in descending order using the ORDER BY clause (so that the customer who's spent the most is listed at the top).

The examples on this page use the Sakila sample database.