What is the difference between HAVING and WHERE?

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.