Having Clause SQL

Galaxy Glossary

How do you filter the results of aggregate functions in SQL?

The HAVING clause in SQL is used to filter groups of data after aggregate functions like COUNT, SUM, AVG, MAX, and MIN have been applied. It's crucial for refining results based on calculated values.
Sign up for the latest in SQL knowledge from the Galaxy Team!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Description

The HAVING clause is a powerful tool in SQL that allows you to filter groups of rows after aggregate functions have been applied. Imagine you have a table of sales data, and you want to find the departments with total sales exceeding a certain threshold. You can't directly filter the raw sales data because you need to calculate the total sales for each department first. This is where the HAVING clause comes in. It lets you apply a filter to the groups of data that result from aggregate functions. Crucially, the HAVING clause operates on the *grouped* data, unlike the WHERE clause, which operates on individual rows before any grouping occurs. This distinction is key to understanding how to use HAVING effectively. For example, you might use HAVING to find departments with an average sales amount greater than $10,000. The WHERE clause would be inappropriate for this task because it would filter individual sales records, not the aggregated department totals. The HAVING clause is essential for complex queries that require filtering after aggregate calculations.

Why Having Clause SQL is important

The HAVING clause is essential for creating sophisticated queries that analyze aggregated data. It allows for filtering of groups based on calculated values, which is crucial for tasks like identifying top-performing departments, analyzing trends, and more.

Example Usage


CREATE TABLE Sales (
    Department VARCHAR(50),
    SalesAmount DECIMAL(10, 2)
);

INSERT INTO Sales (Department, SalesAmount) VALUES
('Electronics', 15000.00),
('Electronics', 12000.00),
('Clothing', 8000.00),
('Clothing', 9000.00),
('Books', 11000.00),
('Books', 18000.00);

SELECT Department, SUM(SalesAmount) AS TotalSales
FROM Sales
GROUP BY Department
HAVING SUM(SalesAmount) > 10000;

Common Mistakes

Want to learn about other SQL terms?