In SQL, both WHERE and HAVING are used to filter data, but they serve different purposes. The key distinction is when they filter: WHERE applies rows before grouping, while HAVING filters groups after aggregation.
You cannot use aggregate functions (like COUNT, SUM, AVG) in a WHERE clause because the groups don't exist yet. That's exactly where HAVING comes in — it allows you to filter based on aggregated results.
Example: To find departments with more than 10 employees, you would use:
SELECT department, COUNT(*)
FROM employees
GROUP BY department
HAVING COUNT(*) > 10;
Remember: WHERE first, HAVING after. Use WHERE for row-level filters and HAVING for group-level filters.