Performance Implications
You'll learn why WHERE is faster than HAVING and how filtering early saves your database from unnecessary work.
The Core Performance Difference
When you filter data with WHERE, you're reducing the dataset before the database performs any grouping or aggregation. When you use HAVING, the database must first group all the rows, calculate all the aggregates, and then throw away groups that don't meet your criteria.
Think of it like sorting mail: Would you rather throw away junk mail at your mailbox (WHERE), or carry everything up three flights of stairs, organize it all into piles, then throw away the junk (HAVING)?
Why WHERE is More Efficient
-- Efficient: Filter first, then aggregate
SELECT department, AVG(salary)
FROM employees
WHERE hire_date > '2020-01-01'
GROUP BY department;
-- Less efficient: Aggregate everything, then filter
SELECT department, AVG(salary)
FROM employees
GROUP BY department
HAVING MIN(hire_date) > '2020-01-01';
In the first query, if 90% of employees were hired before 2020, WHERE eliminates them immediately. The database only groups and calculates averages for the remaining 10%.
In the second query, the database groups all employees, calculates aggregates for every department, then discards departments that don't meet the condition. That's wasted computational effort.
The Rule of Thumb
Use WHERE whenever you're filtering based on individual row values. Save HAVING exclusively for conditions that require aggregate calculations (like "departments with average salary > 75000").
Key Takeaway: Always filter with WHERE when possible—it reduces the dataset early, making grouping and aggregation faster by processing fewer rows.