What is the purpose of the HAVING clause in SQL statements?
The HAVING clause is used in SQL queries to filter the results of grouped data. It allows filtering of groups based on the results of aggregate functions.
Specifically, the HAVING clause will be applied to the result set after the GROUP BY clause. It allows for the use of aggregate functions (such as SUM, COUNT, AVG, etc.) to summarize data and filter groups based on the results of these aggregate functions.
Usually, the WHERE clause is used to filter non-aggregate columns, while the HAVING clause is used to filter aggregate columns. This is because the WHERE clause filters before grouping, whereas the HAVING clause filters after grouping.
Here is an example demonstrating how to use the HAVING clause to filter out departments with total sales greater than 1000.
SELECT department, SUM(sales) as total_sales
FROM sales_table
GROUP BY department
HAVING total_sales > 1000;
In the example above, the HAVING clause filters out departments with total sales greater than 1000.