In SQL, the HAVING clause is used to filter the results of a group that has been processed by the GROUP BY clause. This clause is used when you want to set conditions for groups of data, not for individual records. For example, assume you have a sales table and you only want to find the groups of sales representatives whose total sales exceed a specific amount. In this situation, HAVING is utilized.
Suppose you have used GROUP BY to categorize the data and now you want to filter these categories based on specific conditions. For such tasks, you cannot use WHERE, as WHERE is applied before grouping the data, while HAVING is applied after grouping operations.
In fact, WHERE is used to filter individual records before grouping operations, and HAVING is used to filter groups after those operations take place. This distinction is fundamental in the use of WHERE and HAVING in SQL.
In situations where you want to limit aggregation functions, you need to use HAVING. Unlike WHERE, which cannot filter aggregate functions, HAVING effectively handles this task. This feature also allows for more complex and advanced reporting capabilities.
Example SQL Code Using HAVING
SELECT sales_rep, SUM(sales_amount) AS total_sales
FROM sales
GROUP BY sales_rep
HAVING SUM(sales_amount) > 10000;
Line-by-Line Code Explanation
SELECT sales_rep, SUM(sales_amount) AS total_sales
This line selects the sales representative's name and the total sales summed up.
FROM sales
This line specifies that the data is being retrieved from the sales table.
GROUP BY sales_rep
This line groups the data based on the names of sales representatives.
HAVING SUM(sales_amount) > 10000
This line selects groups whose total sales are greater than 10000.