What is the difference between HAVING and WHERE?

Why Interviewers Ask This

This question tests conceptual clarity. Interviewers want to hear a precise, confident definition before moving to more complex MySQL / SQL topics. It also reveals how well you can explain technical ideas to non-experts.

Answer

Both WHERE and HAVING filter rows, but they operate at different stages: WHERE filters individual rows before any grouping or aggregation. It cannot reference aggregate functions. Example: WHERE salary > 50000 — filter employees with salary over 50k before grouping. HAVING filters groups after GROUP BY and aggregation. It can (and typically does) reference aggregate functions. Example: HAVING AVG(salary) > 50000 — filter departments where the average salary is over 50k. Both together: SELECT department, COUNT(*) AS emp_count, AVG(salary) AS avg_sal FROM employees WHERE hire_date > "2020-01-01" GROUP BY department HAVING COUNT(*) > 5 ORDER BY avg_sal DESC; — WHERE filters employees hired after 2020 (before grouping), GROUP BY groups by department, HAVING keeps only departments with more than 5 such employees. Order of execution: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT. Performance tip: use WHERE (not HAVING) to filter non-aggregated conditions, as it reduces the number of rows before grouping.

Common Mistake

Don't just define the term — demonstrate that you understand when to use it and when not to. Showing awareness of trade-offs is what separates average from strong MySQL / SQL candidates.