wasAsked.

Difference between WHERE and HAVING.

Capgemini · Full Stack Developer · technical

Published

Year not specified · SQL

Community answers

Posted by wasAsked editorial collection

WHERE filters individual rows before grouping; HAVING filters groups after GROUP BY and aggregation. Logical query processing order FROM, then WHERE, then GROUP BY, then HAVING, then SELECT, then ORDER BY. Because WHERE runs before grouping, it cannot use aggregate results. HAVING runs after aggregation, so it can. Example — customers with more than 5 completed orders in 2026: SELECT CustomerId, COUNT(*) AS OrderCount, SUM(Total) AS Revenue FROM Orders WHERE Status = 'Completed' -- row filter: before grouping AND OrderDate >= '2026-01-01' GROUP BY CustomerId HAVING COUNT(*) > 5; -- group filter: after aggregation Differences - Applies to: WHERE filters rows; HAVING filters groups. - Aggregates: WHERE cannot use COUNT, SUM or AVG; HAVING can. - Timing: WHERE runs before GROUP BY; HAVING runs after it. - Without GROUP BY: WHERE is normal; HAVING treats the whole result as one group (valid but unusual). - Statement types: WHERE works with SELECT, UPDATE and DELETE; HAVING is used with SELECT (grouped queries). Performance tip Put conditions that do not depend on aggregates in WHERE, not HAVING. Filtering rows early reduces the data that must be grouped, and WHERE conditions can use indexes: -- Less efficient SELECT CustomerId, COUNT(*) FROM Orders GROUP BY CustomerId HAVING CustomerId > 100; -- Better SELECT CustomerId, COUNT(*) FROM Orders WHERE CustomerId > 100 GROUP BY CustomerId; (Query optimizers can sometimes move such conditions automatically, but writing them in WHERE is clearer and reliable.) Common mistake SELECT CustomerId FROM Orders WHERE COUNT(*) > 5 GROUP BY CustomerId; -- error Aggregates are not allowed in WHERE; move the condition to HAVING. Combined usage is common: WHERE narrows the rows, GROUP BY aggregates them, and HAVING keeps only the groups that meet aggregate conditions.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics