MySQL : HAVING Clause

The HAVING clause in MySQL is used in combination with the GROUP BY clause to filter the results of aggregate functions applied to grouped rows. It allows you to specify conditions on the grouped data.

Here's the basic syntax:


SELECT column1, aggregate_function(column2)
FROM table_name
WHERE condition
GROUP BY column1
HAVING condition2;

 

  • column1 is the column you want to group by.
  • aggregate_function can be COUNT, SUM, AVG, MIN, or MAX, among others, and is applied to column2.
  • table_name is the name of the table you're querying.
  • condition is an optional condition to filter the rows before grouping.
  • condition2 is the condition applied to the grouped data after grouping has been performed.

For example, suppose you have a table named sales with columns product and amount, and you want to find the total sales for each product, but only for products with total sales greater than $1000:


SELECT product, SUM(amount) AS total_sales
FROM sales
GROUP BY product
HAVING total_sales > 1000;

 

This will give you a result where each row represents a unique product along with its total sales, but only for products where the total sales exceed $1000.