Having Clause 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 returned by an aggregate function. It's similar to the WHERE clause, but applies *after* the aggregation, allowing you to filter 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, enabling you to refine the output of aggregate functions like COUNT, SUM, AVG, MAX, and MIN. Imagine you have a table of sales data. You might want to find the average sales for each region. The aggregate function `AVG(sales)` would give you the average for each region, but what if you only wanted regions with an average sales amount above a certain threshold? This is where the HAVING clause comes in handy. It allows you to filter the results of aggregate functions based on conditions applied to the aggregated values, not the individual rows. Crucially, the HAVING clause cannot be used with the WHERE clause to filter individual rows before aggregation. This is a common mistake. The WHERE clause filters rows *before* any aggregation takes place. The HAVING clause filters groups of rows *after* the aggregation has been performed. This distinction is key to understanding how to use these clauses effectively.

Why Having Clause In SQL is important

The HAVING clause is essential for filtering aggregated data. It allows for complex analysis and reporting by enabling you to focus on specific groups of data that meet certain criteria. This is crucial for data analysis and reporting in various applications.

Having Clause In SQL Example Usage


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

INSERT INTO Sales (Region, SalesAmount) VALUES
('North', 100),
('North', 150),
('South', 200),
('South', 120),
('East', 180),
('East', 220),
('West', 90),
('West', 110);

SELECT Region, AVG(SalesAmount) AS AverageSales
FROM Sales
GROUP BY Region
HAVING AVG(SalesAmount) > 100;

Common Mistakes

Want to learn about other SQL terms?