WHERE filters individual rows before aggregation; HAVING filters groups after aggregation. So you filter on raw columns in WHERE and on aggregate results such as COUNT or SUM in HAVING. Filter as much as you can in WHERE, since reducing rows before grouping is cheaper. A common bug is putting a date filter in HAVING, which still aggregates everything first and can change results.
Why interviewers ask this
It reveals whether you understand SQL's logical order of operations rather than pattern matching syntax. Interviewers often chain into related questions about why you cannot reference a column alias in WHERE, or why a filter placed in the wrong clause changed the numbers, both of which come from the same underlying execution order.
How to structure your answer
- Anchor the answer in the logical order of execution.
- Give the rule: raw columns in WHERE, aggregates in HAVING.
- Explain the performance reason for filtering early.
- Mention alias visibility as a consequence of the same ordering.
Example answer
It comes down to when each clause runs. WHERE happens before grouping, so it filters individual rows. HAVING happens after, so it filters the aggregated groups. If I want orders from this year, that is WHERE. If I want only customers with more than five orders, that has to be HAVING, because the count does not exist yet at WHERE time. I always push filters as far into WHERE as possible, since grouping ten thousand rows instead of ten million is a meaningful difference on a large table. The same execution order explains a thing that trips people up: you cannot reference a SELECT alias in WHERE, because the SELECT list is evaluated after the filter, although most engines will let you use the alias in GROUP BY and ORDER BY, which feels inconsistent until you know the ordering. And the bug I have actually had to fix was a date filter in HAVING that produced correct looking totals over the wrong window.
Walking into this interview soon? GhostPilot listens to your live call, spots the question the moment it is asked, and puts a structured answer on your screen in real time. Try it on your next mock, or grab a $29 Session Pass, no subscription, for the real thing.
See how it worksFollow-up questions to expect
- Why can you not use a SELECT alias in the WHERE clause?
- How would you filter on an aggregate without HAVING?
- What is the logical order of execution in a SELECT statement?
Related data analyst questions
Your interviewer will ask their own version of this. Paste your actual job description into the free Question Predictor and get the 20 questions that role is most likely to ask, with what each one is really probing.
Predict my questions