SQL · Queries that survive scale
What is the difference between WHERE and HAVING?
Short answer
WHERE filters individual rows before grouping, while HAVING filters groups after aggregation. Put row-level predicates in WHERE so the database can reduce the input earlier.
Both clauses filter, but at different stages. WHERE sees one row at a time and cannot reference aggregate results. HAVING sees grouped rows and can filter on COUNT, SUM, or other aggregates.
SELECT customer_id,
COUNT(*) AS paid_orders,
SUM(total_cents) AS revenue_cents
FROM orders
WHERE status = 'paid'
AND created_at >= '2026-01-01'
GROUP BY customer_id
HAVING COUNT(*) >= 3
AND SUM(total_cents) > 50000
ORDER BY revenue_cents DESC;Why placement matters
- WHERE reduces the rows that must be grouped and sorted
- A row-level condition in HAVING forces more work before filtering
- HAVING without GROUP BY treats the whole result as one group
- An aggregate in WHERE is invalid because grouping has not happened yet
The optimizer can sometimes push a HAVING predicate down when safe, but do not depend on it. Writing the condition in the correct clause keeps intent clear and gives the planner the best chance to use an index.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Can HAVING reference a column that is not grouped?
- 2Why is WHERE generally better for row-level filters?
- 3What happens if you use HAVING without GROUP BY?
- 4Can an index be used for a HAVING predicate?
Say it in the interview
WHERE filters rows before aggregation, and HAVING filters groups after aggregation. I put row-level conditions such as status or date in WHERE so fewer rows reach the grouping step. I use HAVING only for aggregate conditions such as count or sum thresholds. That distinction keeps the query correct and usually helps the optimizer.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live SQL mock interview and get scored feedback on depth, clarity and confidence.