SQL HAVING Clause Explained

In databases, the HAVING clause is typically used in conjunction with the GROUP BY clause to filter the results of grouped data. The HAVING clause allows for conditions to be applied to the results of aggregate functions, displaying only the groups that meet the specified conditions.

The basic syntax is as follows:

SELECT column_name, aggregate_function(column_name)
FROM table_name
GROUP BY column_name
HAVING condition;

In the above syntax, the conditions after the HAVING clause filter the results of the grouping, similar to how the WHERE clause filters individual rows of data. It is important to note that the HAVING clause can only be used after the GROUP BY clause.

For example, the following sample query displays departments where the average salary is greater than 5000.

SELECT department, AVG(salary)
FROM employees
GROUP BY department
HAVING AVG(salary) > 5000;
bannerAds