Skip to content
Back to 50 Concepts
Topic 21 of 50query-executionIntermediate

# 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().

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

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 Trace
Interactive Engine Simulation

Hash Aggregation & Bucket Pipeline

Step 1 of 3
SQL>SELECT department, AVG(salary) FROM employees GROUP BY department HAVING AVG(salary) > 65000;Active Input

Step 1: Hash Key Calculation

Engine Action: Hash department column for incoming rows
Bucket #1: IT

Alice ($80k), David ($70k)

Bucket #2: HR

Bob ($50k), Eve ($55k)

Bucket #3: Sales

Charlie ($90k)

How the Database Executes This:

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 Aggregates
departmentCOUNT(*)AVG(salary)
Engineering12$125,000 (Passes HAVING)
Sales8$85,000 (Fails salary check)
HR3$95,000 (Fails count check)
Relational walkthrough: HAVING COUNT(*) > 5 AND AVG(salary) > 100000 filters out Sales and HR.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Filtering grouped results with HAVING
SELECT 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;
WHERE filters individual tuples; HAVING filters aggregate buckets.

6. Important Rules & Behaviors

RuleBehavioral Explanation
WHERE vs HAVING TimingWHERE evaluates before GROUP BY; HAVING evaluates after GROUP BY and aggregate calculation.
Pre-Filter OptimizationNever put filters on plain columns in HAVING if they could be placed in WHERE (filtering early saves CPU).
Aggregate RequirementConditions inside HAVING typically involve aggregate functions like SUM, COUNT, or AVG.
Post-aggregation filteringHAVING evaluates only after rows are grouped and aggregate functions (COUNT, SUM) are computed.
Filter placement optimizationNon-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;
Caution: Only put conditions in HAVING that strictly require aggregate functions.

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

Scenario Question:

Which of the following queries correctly filters for departments where average salary exceeds 80,000?

Select your answer: