SQL HAVING Keyword
The HAVING
clause in SQL is used to filter the results of a GROUP BY
query. It's similar to the WHERE
clause, but it operates *after* the grouping has taken place.
HAVING: Definition and Usage
You use HAVING
to specify conditions based on aggregate functions (like COUNT()
, SUM()
, AVG()
, MAX()
, MIN()
). WHERE
can't be used directly with aggregate functions because it filters *before* grouping occurs; HAVING
filters *after* grouping.
Syntax
Syntax
SELECT aggregate_function(column_name), ...
FROM table_name
WHERE condition
GROUP BY column_name
HAVING condition;
Examples
Filtering Groups
This query counts customers per country and only includes countries with more than 5 customers.
Syntax
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
Output
COUNT(CustomerID) | Country
--------------------------
7 | USA (Example output; adapt to your data)
Filtering and Sorting Groups
This query does the same as above but also sorts the results in descending order based on the customer count.
Syntax
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;
Output
COUNT(CustomerID) | Country
--------------------------
7 | USA (Example output; adapt to your data)