HAVING is an optional clause used with GROUP BY to filter the result set of aggregated queries. WHERE filters individual rows before grouping, while HAVING filters entire groups created by GROUP BY. Because it operates on groups, HAVING can reference aggregate functions such as COUNT, SUM, AVG, MIN, and MAX. If GROUP BY is omitted, HAVING treats the entire result set as a single group, effectively acting like WHERE on aggregates. Execution order matters: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT. Incorrect placement of filters can lead to unexpected results or performance issues. Some databases allow HAVING without GROUP BY but behavior may vary, so test queries in your target dialect.
condition
(mandatory) - Boolean expression that can include aggregate functions and column references present in the GROUP BY list.GROUP BY, WHERE, ORDER BY, DISTINCT, aggregate functions, window functions
SQL-92
WHERE filters rows before grouping, while HAVING filters groups after aggregation and can reference aggregate functions.
Yes. The database treats the entire result set as a single group, so aggregate functions still work. Behavior is portable across major vendors but verify performance.
If a column is referenced without an aggregate function, it must also be listed in GROUP BY. Aggregated columns are exempt.
Move non-aggregate filters to WHERE, add indexes on grouping keys, and avoid complex expressions inside aggregate functions where possible.