Last Updated: 04 July, 2023
In MySQL, the HAVING clause is used to filter the results of a query based on a condition that applies to aggregate functions or grouped columns. It is similar to the WHERE clause but is specifically used with grouped data.
Here's the general syntax for using HAVING in a MySQL query:
SELECT column1, column2, ... FROM table GROUP BY column1, column2, ... HAVING condition;
Let's break down the syntax:
Here's an example to illustrate the usage of HAVING clause:
Suppose we have a table called orders with columns product and quantity, and we want to retrieve the products whose total quantity is greater than 100.
SELECT product, SUM(quantity) as total_quantity FROM orders GROUP BY product HAVING total_quantity > 100;
In this example, we are grouping the rows by the product column and calculating the total quantity for each product using the SUM aggregate function. The HAVING clause is then used to filter the groups where the total quantity is greater than 100.
Note that the columns used in the HAVING clause should either be part of the GROUP BY clause or be an aggregate function.
That's all, guys. I hope this MySQL article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com