SQL Server Interview Question #89

What is the difference between WHERE and HAVING?

Aggregate Functions, GROUP BY & Window Functions Mid-Level Intermediate

Detailed Explanation

WHERE filters source rows before GROUP BY and aggregate calculation. HAVING filters the grouped result after aggregation.

Conditions that do not depend on aggregates should generally be placed in WHERE so unnecessary rows can be eliminated earlier. Aggregate conditions belong in HAVING.

Code Example

SELECT CategoryId,
       COUNT(*) AS ActiveProducts
FROM dbo.Products
WHERE IsActive = 1
GROUP BY CategoryId
HAVING COUNT(*) >= 5;