Skip to main content
Practice

HAVING Clause

The HAVING clause lets you filter groups after applying aggregation.

It works like WHERE, but is used specifically with results that come from GROUP BY.


Why Not Use WHERE?

The difference between WHERE and HAVING is that:

  • WHERE filters rows before grouping
  • HAVING filters groups after aggregation

For example, if you want to find regions with an average sales above a certain amount, you must first group the data and then use HAVING to filter the grouped results.


Basic Syntax

The HAVING clause is used after the GROUP BY clause in a SELECT statement.

HAVING Syntax
SELECT column, AGG_FUNCTION(column)
FROM table_name
GROUP BY column
HAVING condition;

Example: Regions with High Sales

Assume you have a table called clients and you want to find regions with total sales above 25000.

You can use the HAVING clause to filter the results after the data is grouped.

Regions with high sales
SELECT region, SUM(sales) AS total_sales
FROM clients
GROUP BY region
HAVING SUM(sales) > 25000;

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.