# Topic 21: HAVING Clause
Filtering aggregated groups vs individual rows, WHERE vs HAVING execution order, and performance implications.
1. Definition
The HAVING clause specifies filter conditions applied to grouped rows (the output of GROUP BY), filtering based on aggregate expressions like COUNT(), SUM(), or AVG().
2. Explain Like I'm 5
WHERE filters individual applicants before the team is formed; HAVING filters whole teams after their total scores have been calculated.
3. Animation & Visual Simulation
Interactive Engine TraceHash Aggregation & Bucket Pipeline
SELECT department, AVG(salary) FROM employees GROUP BY department HAVING AVG(salary) > 65000;Active InputStep 1: Hash Key Calculation
Alice ($80k), David ($70k)
Bob ($50k), Eve ($55k)
Charlie ($90k)
The engine hashes the group key ("IT", "HR", "Sales") into in-memory hash buckets.
4. Real-World Example
Finding departments that have more than 5 employees and an average salary over $100,000.
| department | COUNT(*) | AVG(salary) |
|---|---|---|
| Engineering | 12 | $125,000 (Passes HAVING) |
| Sales | 8 | $85,000 (Fails salary check) |
| HR | 3 | $95,000 (Fails count check) |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectSELECT department, COUNT(*) AS staff_count, AVG(salary) AS avg_sal FROM employees WHERE status = 'active' -- Filters rows BEFORE grouping GROUP BY department HAVING COUNT(*) >= 5 -- Filters groups AFTER aggregation ORDER BY avg_sal DESC;
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| WHERE vs HAVING Timing | WHERE evaluates before GROUP BY; HAVING evaluates after GROUP BY and aggregate calculation. |
| Pre-Filter Optimization | Never put filters on plain columns in HAVING if they could be placed in WHERE (filtering early saves CPU). |
| Aggregate Requirement | Conditions inside HAVING typically involve aggregate functions like SUM, COUNT, or AVG. |
| Post-aggregation filtering | HAVING evaluates only after rows are grouped and aggregate functions (COUNT, SUM) are computed. |
| Filter placement optimization | Non-aggregate row filters should always be placed in WHERE rather than HAVING to eliminate rows early. |
7. Deep Dive: Performance: Why Filtering in WHERE Beats HAVING
Filtering in WHERE discards rows before the engine allocates memory for HashAggregate. If you filter in HAVING, the database must ingest, sort, or hash every single row first, wasting memory and CPU.
-- SLOW (Groups all countries first, then discards): SELECT country, COUNT(*) FROM users GROUP BY country HAVING country = 'US'; -- FAST (Filters in WHERE, grouping ONLY US rows): SELECT country, COUNT(*) FROM users WHERE country = 'US' GROUP BY country;
8. Advantages & Disadvantages
Advantages
- •Enables conditional filtering on calculated group metrics.
- •Completes the relational pipeline for grouped analytics.
Disadvantages & Trade-offs
- •Misplacing row-level predicates into HAVING wastes substantial query memory.
9. Common Interview Questions
Q1.Why should you filter in WHERE instead of HAVING whenever possible?
WHERE filters rows before they are placed into grouping buckets or processed by aggregate accumulators, dramatically reducing the amount of data the engine must hold in memory (work_mem). Filtering in HAVING forces the engine to group and aggregate millions of rows first, only to throw them away at the very end.
Q2.Can you use a column in the HAVING clause that is NOT present in the SELECT projection list?
Yes! You can filter on any aggregate function in HAVING even if it is not selected: SELECT department, COUNT(*) FROM employees GROUP BY department HAVING AVG(salary) > 80000; The engine computes AVG(salary) internally during aggregation, evaluates the boolean filter, and then drops the metric from the final projected output.
Q3.Can HAVING be used without a GROUP BY clause in SQL?
Yes! When HAVING is used without GROUP BY, the entire table is treated as a single implicit group: SELECT COUNT(*) FROM orders HAVING COUNT(*) > 1000; If the condition is met, it returns the count; if not, it returns zero rows.
Q4.What is the logical execution order relationship between WHERE, GROUP BY, and HAVING?
1. WHERE filters individual candidate rows from the source table. 2. GROUP BY partitions the remaining rows into distinct hash buckets. 3. Aggregates compute metrics per bucket. 4. HAVING filters the completed group summary rows. Any group failing HAVING is discarded from the result pipeline.
Q5.Can you filter on window functions inside a HAVING clause?
No. Window functions (e.g. ROW_NUMBER(), RANK()) are evaluated at Step 5.5 (during or right after SELECT), which occurs AFTER the HAVING clause (Step 4). To filter on a window function result, you must wrap the query in a Common Table Expression (CTE) or derived table subquery.
10. Interview-Ready Answer
“WHERE filters rows before grouping, while HAVING filters groups after aggregation. To maximize database performance, always filter raw rows in the WHERE clause as early as possible and reserve HAVING exclusively for aggregate calculations.”
11. Quick Test
Which of the following queries correctly filters for departments where average salary exceeds 80,000?