SQL HAVING Clause Explained: Filter Your Data Like a Pro
The only clause that lets you filter based on an aggregate result.
The HAVING clause exists for one specific reason: WHERE cannot filter based on the result of an aggregate function, because aggregates aren't calculated until after grouping happens. HAVING fills that gap.
Basic Syntax
SELECT column, AGG_FUNCTION(column) FROM table_name GROUP BY column HAVING AGG_FUNCTION(column) condition;
Example: Departments With More Than 5 Employees
SELECT department, COUNT(*) AS employee_count FROM employees GROUP BY department HAVING COUNT(*) > 5;
Example: Products With Average Rating Above 4
SELECT product_id, AVG(rating) AS avg_rating FROM reviews GROUP BY product_id HAVING AVG(rating) > 4;
Combining HAVING with Multiple Conditions
SELECT department, AVG(salary) AS avg_salary, COUNT(*) AS total FROM employees GROUP BY department HAVING AVG(salary) > 50000 AND COUNT(*) > 3;
WHERE filters rows before grouping, HAVING filters groups after aggregation.Common Mistakes to Avoid
- Using
HAVINGwithout aGROUP BYwhen a simpleWHEREwould do - Referencing a column in
HAVINGthat isn't part ofGROUP BYor an aggregate - Expecting
HAVINGto speed up a query — it filters after the aggregation has already been computed
Once this distinction clicks, HAVING stops feeling like an extra rule to memorize and starts feeling like the obvious tool for the job.
Where HAVING Sits in Query Processing
SQL is written in one order but evaluated in another. Knowing the logical order explains why HAVING can see aggregates and WHERE cannot.
FROMandJOIN: build the set of rows.WHERE: drop individual rows.GROUP BY: collect remaining rows into groups.- Aggregates such as
COUNTandSUMare calculated per group. HAVING: drop whole groups.SELECT: choose output columns.ORDER BYandLIMIT: sort and trim the result.
WHERE and HAVING Working Together
A sales manager wants cities where completed online orders add up to more than 2,00,000 rupees. Cancelled orders should not count at all.
SELECT city,
COUNT(*) AS orders,
SUM(amount) AS revenue
FROM orders
WHERE status = 'completed'
AND channel = 'online'
GROUP BY city
HAVING SUM(amount) > 200000
ORDER BY revenue DESC;
The status filter belongs in WHERE because it is about single rows. Putting it there also means fewer rows reach the grouping step, which is faster. The revenue filter must be in HAVING because the total only exists after grouping.
Finding Duplicates With HAVING
One of the most practical uses is spotting repeated values, such as customers registered twice with the same email.
SELECT email, COUNT(*) AS copies
FROM customers
GROUP BY email
HAVING COUNT(*) > 1;
The same idea works for duplicate invoice numbers, repeated phone numbers or the same product listed twice by one seller. To see the full duplicate rows, use this query as a subquery and join it back to customers on email.
MySQL Specifics Worth Knowing
- MySQL lets you use a select alias in HAVING, so
HAVING revenue > 200000works. Standard SQL and some other databases do not allow it, so repeating the aggregate is more portable. - HAVING can use aggregates that are not in the SELECT list, for example
HAVING MAX(amount) > 50000. - With
ONLY_FULL_GROUP_BYenabled (the default in current MySQL), every non-aggregated column in SELECT or HAVING must appear in GROUP BY. - HAVING without GROUP BY treats the whole table as one group, which is valid but rarely what you need.
Practice Task
Using a batch_students table with batch_id, student_id and fee_paid, try writing a query that lists batches with at least 20 students and an average fee paid above 10,000. One possible answer:
SELECT batch_id, COUNT(DISTINCT student_id) AS students, AVG(fee_paid) AS avg_fee
FROM batch_students
GROUP BY batch_id
HAVING COUNT(DISTINCT student_id) >= 20
AND AVG(fee_paid) > 10000;
Rule of thumb: if the condition could be checked by looking at one row alone, it goes in WHERE; if it needs a total, average, count, minimum or maximum, it goes in HAVING.