Having In 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 rows after aggregate functions have been applied. It's crucial for refining the output of functions like COUNT, SUM, AVG, MAX, and MIN. It's distinct from the WHERE clause, which filters individual rows before aggregation.
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 for filtering the results of aggregate functions. Imagine you have a table of sales data, and you want to find the departments with average sales exceeding a certain threshold. You can't use the WHERE clause directly to filter the average sales because the average is a calculated value, not a value in a specific row. This is where HAVING comes in. It allows you to apply conditions to the groups of rows after the aggregate function has calculated the values. Crucially, HAVING works *after* the GROUP BY clause, which is essential for grouping the data before applying the filter. For example, you might group sales by department and then use HAVING to filter out departments with an average sales amount below a certain value. This is a key difference from the WHERE clause, which filters individual rows before any aggregation takes place. The WHERE clause is used to filter individual rows based on their individual values, while HAVING filters groups of rows based on aggregate values. Understanding this distinction is essential for writing effective SQL queries that manipulate aggregated data.

Why Having In SQL is important

HAVING is essential for data analysis and reporting. It allows you to extract meaningful insights from aggregated data by filtering groups based on calculated values. This is crucial for tasks like identifying top-performing departments, understanding trends in sales, and more.

Example Usage


-- Sample table: Sales
CREATE TABLE Sales (
    Department VARCHAR(50),
    SalesAmount DECIMAL(10, 2)
);

INSERT INTO Sales (Department, SalesAmount) VALUES
('Electronics', 15000),
('Electronics', 12000),
('Clothing', 8000),
('Clothing', 9000),
('Clothing', 10000),
('Furniture', 18000),
('Furniture', 20000);

-- Calculate average sales per department and filter those with average > 10000
SELECT Department, AVG(SalesAmount) AS AverageSales
FROM Sales
GROUP BY Department
HAVING AVG(SalesAmount) > 10000;

Common Mistakes

Want to learn about other SQL terms?