TryBench
Data Analysis & SQL · Practitioner lesson 12 of 19

SQL HAVING vs WHERE Explained With Examples

Filter raw records with WHERE and filter calculated totals with HAVING.

Why this matters

Many reports ask for groups that pass a total, such as departments earning over 5,000. You need the right filter for each job.

WHERE Checks Rows First

WHERE looks at single rows before any adding up happens. So you cannot write WHERE SUM(amount) >= 5000.

In real life: WHERE checks each single row before any adding up. It cannot test a total because the total does not exist yet.

HAVING Checks the Totals

HAVING SUM(amount) >= 5000 keeps only the groups whose total reaches the target.

In real life: HAVING checks the total after the groups are made. Use it for tests like SUM(amount) >= 5000.

Use Both Together

First, WHERE removes unwanted rows, like test data. Then HAVING keeps only the groups with big enough totals.

In real life: First you throw away the test orders (WHERE). Then you add up each department and keep only the ones above the target (HAVING). The order matters.

Your practice task

Identify high-revenue departments generating at least 5,000 in completed sales. Filter only completed orders, group by department, and filter the grouped totals so only departments with at least 5,000 in total revenue are returned.

How to do it

  1. First remove the rows that should not count.
  2. Then total the revenue for each department.
  3. Keep only the departments whose total reaches the target.
  4. Press Run proof and read the checklist.

Practice it for free in the app. You get instant checks that show what you got right and what to fix. A lesson takes about two minutes and you can try as many times as you like.

Quick reference: Aggregated Total Filter

The fundamental pattern for finding high-volume or high-spend segments.

Practice this lesson free

More lessons in this course

See all 19 lessons in Data Analysis & SQL