SQL Interview Question: WHERE vs HAVING
Short answer: WHERE filters individual rows before grouping. HAVING filters groups after GROUP BY, so it can use aggregate functions like COUNT and SUM.
-- Customers who placed more than 5 paid orders in 2026
SELECT customer_id, COUNT(*) AS paid_orders, SUM(total) AS spent
FROM orders
WHERE status = 'paid' -- row filter: before grouping
AND created_at >= '2026-01-01'
GROUP BY customer_id
HAVING COUNT(*) > 5 -- group filter: after aggregation
ORDER BY spent DESC;
Logical order of a SELECT
FROM/JOINWHEREGROUP BYHAVINGSELECTORDER BYLIMIT
That's why you can't use an aggregate in WHERE (groups don't exist yet), and why a SELECT alias usually can't be used in WHERE (it hasn't been computed yet).
SELECT customer_id FROM orders WHERE COUNT(*) > 5 GROUP BY customer_id; -- error
Performance tip
Filter as early as possible. A condition on a plain column belongs in WHERE, where it can use an index and shrink the data before grouping; putting it in HAVING works but processes more rows.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.