3.2 HAVING vs WHERE, Duplicate Detection & ROLLUP
Master the #1 most-asked SQL interview difference (WHERE vs HAVING), learn the classic GROUP BY + HAVING duplicate-detection pattern, and generate grand totals automatically with ROLLUP.
1. WHERE vs HAVING — The #1 SQL Interview Question
Both WHERE and HAVING filter data — the difference is WHEN they run and WHAT they filter:
| Feature | WHERE | HAVING |
|---|---|---|
| Execution Stage | Step 2 — BEFORE GROUP BY | Step 4 — AFTER GROUP BY |
| What It Filters | Individual raw rows | Collapsed summary groups |
Can Use SUM() / COUNT() / AVG()? | ❌ NO! (Throws syntax error) | ✅ YES! That's what it exists for! |
| Can Use Indexes? | ✅ YES (eliminates rows early = fast!) | ❌ Runs on already-aggregated buckets |
Can Be Used Without GROUP BY? | ✅ Yes (most queries) | Rarely (treats whole table as 1 group) |
Golden Performance Rule:
If a filter does NOT need an aggregate (status = 'paid',year = 2026), ALWAYS put it inWHERE, never inHAVING! Filtering 10 million rows down to 100k before grouping is 100× faster than grouping all 10 million first!
2. Combining WHERE + GROUP BY + HAVING Together
Find all customers who spent more than ₹1,000 across their paid orders:
| order_id | customer | status | amount |
|---|---|---|---|
| 1 | Aarav | paid | 700 |
| 2 | Aarav | paid | 600 |
| 3 | Meera | paid | 400 |
| 4 | Meera | cancelled | 2000 |
| 5 | Kabir | paid | 1100 |
3. Classic Interview Pattern: Finding Duplicate Emails in 3 Lines
Asked in hundreds of data analyst & backend interviews ("Find all duplicate emails in the users table"):
SELECT
email,
COUNT(*) AS duplicate_count
FROM users
GROUP BY email
HAVING COUNT(*) > 1
ORDER BY duplicate_count DESC;
4. Generating Subtotals & Grand Totals Automatically (ROLLUP)
Need a report with department totals plus a grand total row at the bottom without writing a second query? Use GROUP BY ROLLUP(...):
SELECT
COALESCE(department, 'ALL DEPARTMENTS') AS department,
COUNT(*) AS employees,
SUM(salary) AS total_payroll
FROM employees
GROUP BY ROLLUP (department);
ROLLUPproduces every normal group plus a summary row wheredepartmentisNULL(whichCOALESCElabels'ALL DEPARTMENTS').
5. Practice Challenge
Find all product_ids that have been ordered at least 5 times in 2026, where the average order quantity is greater than 2.
6. Quick Check Your Understanding
Module 3.2 Quick Quiz
Keep Exploring: Related Lessons & Tools
All Courses →Test regular expressions live with color-coded match highlights, capture group inspection, plain-English token breakdown, find-and-replace, and Python/JS snippets.
Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.