✅ HAVING vs WHERE
Why HAVING exists
- WHERE filters individual rows.
- Aggregations work on groups.
- You need HAVING to filter groups.
Key difference
- WHERE filters rows before grouping
- HAVING filters groups after aggregation
Think in order
- FROM reads table
- WHERE filters rows
- GROUP BY creates groups
- HAVING filters groups
Example table. orders
order_id | customer_id | amount | order_date
WHERE with aggregation
SELECT customer_id, SUM(amount)
FROM orders
WHERE amount > 5000
GROUP BY customer_id;
What this query does
- Removes orders below 5,000
- Groups remaining orders by customer
- Calculates total high value spend per customer
HAVING example
SELECT customer_id, SUM(amount)
FROM orders
GROUP BY customer_id
HAVING SUM(amount) > 20000;
What this query does
- Groups all orders by customer
- Calculates total spend per customer
- Keeps only customers with total spend above 20,000
WHERE vs HAVING side by side
Use WHERE when
- Filtering raw rows
- Condition does not involve aggregate functions
Use HAVING when
- Filtering aggregated results
- Condition uses SUM, COUNT, AVG
Combined WHERE and HAVING
SELECT customer_id, COUNT(*)
FROM orders
WHERE order_date >= '2024-01-01'
GROUP BY customer_id
HAVING COUNT(*) >= 5;
What this query does
- Keeps orders from 2024 onward
- Groups orders by customer
- Counts orders per customer
- Returns customers with at least 5 orders
Common beginner mistakes
- Using HAVING without GROUP BY
- Using WHERE with SUM or COUNT
- Mixing WHERE and HAVING logic
Interview one-liner
WHERE filters rows. HAVING filters groups.
Double Tap ❤️ For More