How do you correctly combine WHERE and HAVING in the same query to filter both individual rows and grouped results?
Short answer
You place WHERE before GROUP BY to filter out individual rows early, based on conditions that do not depend on aggregation, and then place HAVING after GROUP BY to filter the resulting groups based on the aggregate calculations, giving you precise control over both stages of…
Advertisement
AModel answer
You place WHERE before GROUP BY to filter out individual rows early, based on conditions that do not depend on aggregation, and then place HAVING after GROUP BY to filter the resulting groups based on the aggregate calculations, giving you precise control over both stages of filtering.
SELECT CustomerId, SUM(Amount) AS TotalSpent
FROM Orders
WHERE OrderDate >= '2026-01-01'
GROUP BY CustomerId
HAVING SUM(Amount) > 500;Real-world example
A report only considers orders placed this year using WHERE, then further narrows the results to customers who spent over five hundred dollars during that period using HAVING.
Likely follow-ups
- Does filtering early with WHERE improve query performance compared to filtering everything with HAVING?
- What happens if you try to use an aggregate function inside WHERE by mistake?
Related topics