SQL · Module 03: Aggregations, GROUP BY & CASE WHENTutorial 8 of 24

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.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

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:

FeatureWHEREHAVING
Execution StageStep 2 — BEFORE GROUP BYStep 4 — AFTER GROUP BY
What It FiltersIndividual raw rowsCollapsed 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 in WHERE, never in HAVING! 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:

Tracing WHERE → GROUP BY → HAVING → ORDER BY
Interactive SQL Execution Tracer · Step 1 of 4 (1. FROM orders)
1SELECT customer, SUM(amount) AS total_spent
2→FROM orders
3WHERE status = 'paid'
4GROUP BY customer
5HAVING SUM(amount) > 1000
6ORDER BY total_spent DESC;
Live Table State · 1. FROM orders5 rows
order_idcustomerstatusamount
1Aaravpaid700
2Aaravpaid600
3Meerapaid400
4Meeracancelled2000
5Kabirpaid1100
What the DB engine just did: Loads all 5 raw orders including Meera's cancelled ₹2000 order.

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"):

SQL
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(...):

SQL
SELECT
    COALESCE(department, 'ALL DEPARTMENTS') AS department,
    COUNT(*)    AS employees,
    SUM(salary) AS total_payroll
FROM employees
GROUP BY ROLLUP (department);
  • ROLLUP produces every normal group plus a summary row where department is NULL (which COALESCE labels '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

Q1.Why does WHERE SUM(amount) > 1000 fail with an error?
Q2.Should a condition like country = 'IN' be placed in WHERE or HAVING?

Keep Exploring: Related Lessons & Tools

All Courses →