wasAsked.

Why can't aggregate functions like COUNT() or SUM() be used in a WHERE clause?

Capgemini · Full Stack Developer · technical

Published

Year not specified · SQL

Community answers

Posted by wasAsked editorial collection

Because of the logical order in which SQL evaluates a query. WHERE is processed before rows are grouped and aggregated, so at that point COUNT(), SUM() and other aggregates do not exist yet. Logical processing order of a SELECT 1. FROM and JOIN — build the set of rows. 2. WHERE — filter individual rows. 3. GROUP BY — form groups. 4. Aggregate calculation — COUNT, SUM, AVG, MIN, MAX per group. 5. HAVING — filter groups using aggregates. 6. SELECT — compute output columns. 7. DISTINCT, then ORDER BY, then TOP, OFFSET or FETCH. WHERE operates on one row at a time, but an aggregate summarises many rows. The question "is SUM(Total) > 1000?" only makes sense after the rows are grouped, so SQL raises an error: SELECT CustomerId FROM Orders WHERE SUM(Total) > 1000 GROUP BY CustomerId; -- Error: an aggregate may not appear in the WHERE clause... Correct approaches 1. HAVING filters groups after aggregation: SELECT CustomerId, SUM(Total) AS Revenue FROM Orders GROUP BY CustomerId HAVING SUM(Total) > 1000; 2. A subquery or CTE when you need to compare rows with an aggregate: SELECT * FROM Orders WHERE Total > (SELECT AVG(Total) FROM Orders); -- aggregate computed in a subquery first WITH CustomerRevenue AS (SELECT CustomerId, SUM(Total) AS Revenue FROM Orders GROUP BY CustomerId) SELECT * FROM CustomerRevenue WHERE Revenue > 1000; 3. Window functions in a CTE when you need row details alongside aggregates: WITH x AS (SELECT *, SUM(Total) OVER (PARTITION BY CustomerId) AS CustomerTotal FROM Orders) SELECT * FROM x WHERE CustomerTotal > 1000; Related rule: for the same reason, column aliases defined in SELECT cannot be used in WHERE (SELECT Total * 1.18 AS WithTax ... WHERE WithTax > 100 fails), because SELECT is evaluated after WHERE. Repeat the expression, or use a CTE or subquery. Best practice: use WHERE for row-level conditions (it runs early, reduces the data to group, and can use indexes), and HAVING only for conditions on aggregated values.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics