01 / 21

HAVING for
Group Filtering

Learn how to filter grouped data in SQL using the HAVING clause: the tool that WHERE cannot replace.

SQL

What is the HAVING Clause?

When you use GROUP BY in SQL, you create summary rows: one row per group. But what if you only want groups that meet a certain condition? That is exactly what HAVING does.

Think of it this way: WHERE is the bouncer at the door (checks rows before they enter). HAVING is the judge at the end (checks groups after they have been formed).

Why Can't WHERE Do This?

WHERE runs before GROUP BY, so it has no access to aggregate values like \( \text{COUNT}() \), \( \text{SUM}() \), or \( \text{AVG}() \). Trying to use an aggregate in WHERE causes an error.

-- This will ERROR!
SELECT department, COUNT(*)
FROM employees
WHERE COUNT(*) > 5  -- Aggregate not allowed here
GROUP BY department;

SQL Execution Order

Understanding when each clause runs is the key to mastering HAVING. SQL does not execute top-to-bottom like you write it:

1. FROM 2. WHERE 3. GROUP BY 4. HAVING 5. SELECT 6. ORDER BY Pick the table(s) Filter individual rows Combine rows into groups Filter groups (aggregates) Choose columns to display Sort the final results ★ HAVING lives here

The HAVING Syntax

SELECT column, AGG_FUNC(column)
FROM table_name
WHERE condition_on_rows
GROUP BY column
HAVING AGG_FUNC(column) condition;

The WHERE clause is optional. You can use HAVING without WHERE, but you must have GROUP BY before HAVING.

WHERE vs HAVING

WHERE HAVING
Filters Individual rows Groups
Runs Before GROUP BY After GROUP BY
Aggregates? ✕ Not allowed ✓ Required
Requires GROUP BY? No Yes
Example WHERE salary > 50000 HAVING \( \text{AVG}(\text{salary}) \) > 50000

How to Apply HAVING

1
Write your SELECT with an aggregate. Decide which aggregate function answers your question: \( \text{COUNT} \), \( \text{SUM} \), \( \text{AVG} \), \( \text{MIN} \), or \( \text{MAX} \).
2
Add GROUP BY. Specify the column that defines your groups.
3
Add HAVING with a condition on the aggregate. This is the filter that keeps or removes entire groups.
4
Optionally add WHERE before GROUP BY to pre-filter individual rows before grouping.

Example 1: Basic HAVING

Question: Find departments with more than 3 employees.

SELECT department, COUNT(*) AS emp_count
FROM employees
GROUP BY department
HAVING COUNT(*) > 3;
departmentemp_count
Marketing2
Engineering7
HR3
Sales5

Example 2: HAVING with AVG

Question: Find product categories where the average price exceeds $50.

SELECT category, AVG(price) AS avg_price
FROM products
GROUP BY category
HAVING AVG(price) > 50;
categoryavg_price
Electronics$89.50
Books$22.30
Furniture$175.00
Clothing$34.80

Example 3: WHERE + HAVING

Question: Among active employees only, find departments with total salary over $200,000.

SELECT department, SUM(salary) AS total_sal
FROM employees
WHERE status = 'active'  -- row filter
GROUP BY department
HAVING SUM(salary) > 200000;  -- group filter
WHERE step
Removes inactive employees before groups are formed
HAVING step
Removes groups whose total salary is \( \leq 200{,}000 \) after grouping

Visual Walkthrough

Raw Rows Alice - Eng Bob - Eng Carol - Sales Dave - Sales Eve - HR WHERE Filtered Rows Alice - Eng Bob - Eng Carol - Sales Dave - Sales Eve - HR ✕ GROUP BY Groups Eng: 2 employees Alice, Bob Sales: 2 employees Carol, Dave
HAVING \( \text{COUNT}(*) > 1 \)
Result: Both groups pass ✓
Eng → \( \text{COUNT}(*) = 2 \) ✓
Sales → \( \text{COUNT}(*) = 2 \) ✓
HR was eliminated by WHERE (Eve was inactive), so it never even formed a group.

Multiple Conditions in HAVING

You can combine multiple aggregate conditions using AND and OR, just like in WHERE.

SELECT city, COUNT(*) AS stores,
       AVG(revenue) AS avg_rev
FROM retail_stores
GROUP BY city
HAVING COUNT(*) >= 3
   AND AVG(revenue) > 100000;

HAVING with ORDER BY

After filtering groups, you can sort the surviving groups with ORDER BY, which runs last.

SELECT genre, COUNT(*) AS book_count
FROM books
GROUP BY genre
HAVING COUNT(*) > 10
ORDER BY book_count DESC;
HAVING
Keeps only genres with more than 10 books
ORDER BY
Sorts remaining genres from most to fewest books

Aggregate Functions in HAVING

\( \text{COUNT}(*) \)
Number of rows per group
\( \text{SUM}(\text{col}) \)
Total of a column per group
\( \text{AVG}(\text{col}) \)
Average value per group
\( \text{MIN}(\text{col}) \)
Smallest value per group
\( \text{MAX}(\text{col}) \)
Largest value per group

Common Mistakes

✕ Using WHERE for Aggregates
Writing WHERE \( \text{COUNT}(*) > 5 \) instead of HAVING \( \text{COUNT}(*) > 5 \). WHERE cannot see aggregate results.
✕ HAVING Without GROUP BY
HAVING requires GROUP BY. Without it, most databases will throw an error or treat the entire table as one group.
✕ Using Column Aliases
Writing HAVING \( \text{emp\_count} > 3 \) when emp_count is an alias. Most databases require the full expression: HAVING \( \text{COUNT}(*) > 3 \).

Summary Cheat Sheet

Clause Purpose Position
SELECT Choose columns/aggregates Written 1st, runs 5th
FROM Pick table(s) Written 2nd, runs 1st
WHERE Filter rows Written 3rd, runs 2nd
GROUP BY Form groups Written 4th, runs 3rd
HAVING Filter groups Written 5th, runs 4th
ORDER BY Sort results Written 6th, runs 6th

Question 1 of 5

Which clause is used to filter groups based on aggregate values?

Question 2 of 5

What is wrong with this query?

SELECT city, COUNT(*)
FROM customers
WHERE COUNT(*) > 10
GROUP BY city;

Question 3 of 5

In what order does SQL execute these clauses?

Question 4 of 5

Which query finds categories where total sales exceed $1000?

Question 5 of 5

You want only active users, grouped by country, showing countries with average age over 25. Which clauses do you need?