Skip to main content

HAVING

The HAVING clause is used in combination with the GROUP BY clause to filter the results of GROUP BY. It is used to mention conditions on the group functions, like SUM, COUNT, AVG, MAX or MIN.

It's important to note that where WHERE clause introduces conditions on individual rows, HAVING introduces conditions on groups created by the GROUP BY clause.

Also note, HAVING applies to summarized group records, whereas WHERE applies to individual records.

Syntax:

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);

Example

Consider this "Orders" table:

OrderIDCustomerAmount
1John1000
2Mary1500
3John2000
4Jane1000
5Mary2000
6John3000
7Jane2000
8Mary2500

For instance, if you wanted to find customers who have spent more than $3000 in total, you might use the HAVING clause as follows:

SELECT Customer, SUM(Amount)
FROM Orders
GROUP BY Customer
HAVING SUM(Amount) > 3000;

As a result, the query returns:

CustomerSUM(Amount)
John6000
Mary6000

In this case, the HAVING clause filters out all Customers with a total Amount less than $3000. Only John and Mary have the total sum of Amount more than or equal to $3000. Thus, only these records satisfy the HAVING clause and are included in the result.