How do WHERE and HAVING clauses differ in SQL?
This question distinguishes between filtering rows before aggregation and filtering groups after aggregation. It is a fundamental test of SQL query execution order.
Why Interviewers Ask This
Interviewers need to confirm you understand the logical processing order of SQL statements. Many candidates confuse these two because they both filter data. Knowing when to use each prevents errors in reporting and ensures efficient query execution by filtering early where possible.
How to Answer This Question
Explain that WHERE filters individual rows before any grouping occurs. Emphasize that aggregate functions cannot be used in the WHERE clause. Then explain that HAVING filters the results after the GROUP BY operation has created groups. Use an example showing a date range in WHERE and a count threshold in HAVING.
Key Points to Cover
- WHERE filters rows before grouping
- HAVING filters groups after aggregation
- Aggregates are allowed only in HAVING
Sample Answer
The WHERE clause filters rows before the database groups them together. You cannot use aggregate functions like SUM or COUNT in a WHERE clause because the data isn't grouped yet. In contrast, the HAVING clause filters th…
Common Mistakes to Avoid
- Trying to use aggregates in the WHERE clause
- Thinking they function identically
- Ignoring the execution order of SQL
Sound confident on this question in 5 minutes
Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.