DEV Community

Cover image for HAVING Clause In MySQL
Code Of Accuracy
Code Of Accuracy

Posted on

HAVING Clause In MySQL

The HAVING clause is used in MySQL to filter the results of a query based on a condition that involves an aggregate function. This clause is used after the GROUP BY clause to filter the grouped data based on the result of the aggregate function.

Syntax:

SELECT column1, column2, aggregate_function(column_name)
FROM table_name
WHERE condition
GROUP BY column1, column2
HAVING aggregate_function(column_name) condition;
Enter fullscreen mode Exit fullscreen mode

The HAVING clause is similar to the WHERE clause, but the WHERE clause filters the rows before the data is grouped, while the HAVING clause filters the groups after the data is grouped.

Example:

Let's consider the following table named orders:

OrderID CustomerID OrderDate TotalAmount
1 1 2022-01-01 100
2 2 2022-01-02 200
3 1 2022-01-03 300
4 2 2022-01-04 400
5 3 2022-01-05 500

If we want to find the total amount of orders for each customer and only show the results for customers who have ordered more than 300 dollars, we can use the following query:

SELECT CustomerID, SUM(TotalAmount) as Total
FROM orders
GROUP BY CustomerID
HAVING SUM(TotalAmount) > 300;
Enter fullscreen mode Exit fullscreen mode

The result will be:

CustomerID Total
1 400
2 600

As you can see, the HAVING clause is used to filter the result set based on the aggregate function SUM(TotalAmount), which calculates the total amount of orders for each customer. The condition SUM(TotalAmount) > 300 filters out the customers who have ordered less than 300 dollars.

Top comments (0)