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
- First remove the rows that should not count.
- Then total the revenue for each department.
- Keep only the departments whose total reaches the target.
- 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.
More lessons in this course
- Custom Category BucketsSegment numerical data into business tiers like High, Medium, and Low with CASE WHEN.
- Month-by-Month Trends & SQL DialectsGroup timestamps into uniform monthly buckets using DATE_TRUNC or strftime across different SQL dialects.
- Finding Top PerformersRank and retrieve top-N records without pulling millions of unnecessary rows.