🗄️ Database Design / Normalization
Beginner
What is the difference between WHERE and HAVING?
Answer
WHERE filters rows before aggregation — it operates on individual rows and cannot reference aggregate functions. HAVING filters groups after GROUP BY aggregation — it can reference aggregate functions. Example: to find departments with more than 10 employees whose average salary exceeds 50,000: SELECT dept_id, COUNT(*), AVG(salary) FROM employees WHERE status = 'active' GROUP BY dept_id HAVING COUNT(*) > 10 AND AVG(salary) > 50000. WHERE filters out inactive employees before grouping; HAVING filters resulting groups after the COUNT and AVG are computed.