The basic syntax of the HAVING
clause is:
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1
HAVING condition;
condition
: A condition applied to the groups created by the GROUP BY
clause.aggregate_function(column2)
: An aggregate function like SUM()
, COUNT()
, or AVG()
.Let’s say we want to find departments where the total salary exceeds $50,000. First, we group the employees by department and then use the HAVING
clause to filter the results:
SELECT department, SUM(salary) AS total_salary
FROM employees
GROUP BY department
HAVING SUM(salary) > 50000;
In this example:
department
column.SUM()
function.HAVING
clause filters out departments where the total salary is less than or equal to $50,000.WHERE
filters rows before grouping, while HAVING
filters after the data is grouped.WHERE
for non-aggregated conditions and HAVING
for conditions on aggregated data.The HAVING
clause is a powerful tool for filtering aggregated data in MySQL. By applying it after grouping with GROUP BY
, you can refine your results based on the aggregated values. Understanding how and when to use HAVING
alongside GROUP BY
helps in advanced data analysis and reporting.