Advertisement
Intermediate SQL Server, Aggregate Functions & GROUP BY

How do you filter the results of a grouped query based on an aggregated value, such as only showing customers who spent more than a certain amount?

Short answer

You use the HAVING clause instead of WHERE to filter after grouping and aggregation have already happened, since WHERE filters individual rows before grouping occurs, while HAVING filters the summarized group results themselves based on the aggregate calculation.

Save SQL Server mock interview
Advertisement
AModel answer
You use the HAVING clause instead of WHERE to filter after grouping and aggregation have already happened, since WHERE filters individual rows before grouping occurs, while HAVING filters the summarized group results themselves based on the aggregate calculation.
SELECT CustomerId, SUM(Amount) AS TotalSpent
FROM Orders
GROUP BY CustomerId
HAVING SUM(Amount) > 1000;
Real-world example
A marketing team identifies their top spending customers by filtering grouped order totals with HAVING, targeting only those who have spent over a thousand dollars for a loyalty campaign.
Likely follow-ups
  • Why can't you use an aggregate function directly inside a WHERE clause?
  • Can you combine both WHERE and HAVING in the same query?
Related topics