HAVING Clause

HAVING filters the groups created by GROUP BY, keeping only those that meet a condition on an aggregate value. It is like WHERE, but for grouped results.

SQL

WHERE cannot filter on aggregates such as COUNT(*) because those values don't exist until rows are grouped. HAVING runs after grouping, so it can compare against them.

A common pattern is finding groups above a threshold, such as customers with more than five orders.

Syntax

SELECT column, COUNT(*)
FROM table_name
GROUP BY column
HAVING COUNT(*) > value;

Examples

SQL

SELECT country, COUNT(*) AS users
FROM users
GROUP BY country
HAVING COUNT(*) > 10;

Output:

country  users
-------  -----
USA      12

Learn it in a lesson

See also

Back to the Dictionary