What is the difference between the HAVING and WHERE statements in SQL Server
Loading
What is the difference between the HAVING and WHERE statements in SQL Server
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Sandhiya PriyaRank #26 · 43.2K reputationPosted Aug 12, 2025, 6:45 AM EDT
Answer:
The main difference between
WHEREandHAVINGin SQL Server is:WHERE
Filters rows before grouping happens.
Can be used with any column in the table (raw data).
Cannot be used with aggregate functions like
COUNT(),SUM(), etc.HAVING
Filters rows after grouping has been done using
GROUP BY.Is mainly used with aggregate functions to filter grouped results.
Can also be used without
GROUP BY(acts like aWHEREin that case).Example:
-- WHERE filters before grouping SELECT Department, COUNT(*) AS EmployeeCount FROM Employees WHERE Department <> 'HR' -- filter before grouping GROUP BY Department; -- HAVING filters after grouping SELECT Department, COUNT(*) AS EmployeeCount FROM Employees GROUP BY Department HAVING COUNT(*) > 5; -- filter after groupingExecution Order in SQL Server:
FROMWHERE(filters raw rows)GROUP BY(groups remaining rows)HAVING(filters grouped data)SELECTORDER BYSummary Table:
In short:
Use WHERE to filter rows before grouping.
Use HAVING to filter grouped results, especially when using aggregate functions.
Cynthia SathuragiriRank #937 · 2.2K reputationPosted Aug 12, 2025, 2:10 AM EDT
Using WHERE -> Filter rows before aggregation
SELECT Product, SUM(Quantity) AS TotalQty FROM Sales WHERE Quantity > 10 GROUP BY ProductThis only groups rows where
Quantity > 10(ignores rows ≤ 10).Using HAVING -> Filter after aggregation
SELECT Product, SUM(Quantity) AS TotalQty FROM Sales GROUP BY Product HAVING SUM(Quantity) > 20This groups all rows first then shows only products where the total quantity is more than 20.