Difference Between WHERE and HAVING in SQL Server

Difference Between WHERE and HAVING in SQL Server

In SQL Server, both WHERE and HAVING clauses are used to filter records in a query. However, they serve different purposes and are applied at different stages of the query processing.

 


WHERE Clause

  • Used to filter rows before any grouping or aggregation.
  • Applies to individual rows in the table.
  • Cannot be used with aggregate functions like SUM(), COUNT(), etc.

Example:

SELECT *

FROM Employees

WHERE Department = 'HR'

This query returns only those rows where the Department is "HR".

 

HAVING Clause

  • Used to filter groups after aggregation has been performed (usually with GROUP BY).
  • Applies to the result of the GROUP BY clause.
  • Can be used with aggregate functions like COUNT(), SUM(), AVG().

Example:

SELECT Department, COUNT(*) AS EmployeeCount

FROM Employees

GROUP BY Department

HAVING COUNT(*) > 10

This query shows only those departments that have more than 10 employees.

 

Key Differences Between WHERE and HAVING

Feature

WHERE

HAVING

Applies to

Rows before grouping

Groups after aggregation

Works with aggregates

No

Yes

Can be used without GROUP BY

Yes

Yes (but usually used with GROUP BY)

Performance impact

Faster, filters early

Slower, filters after grouping


Combined Usage Example

SELECT Department, COUNT(*) AS EmployeeCount

FROM Employees

WHERE IsActive = 1

GROUP BY Department

HAVING COUNT(*) > 5

  • WHERE IsActive = 1: filters rows before grouping
  • HAVING COUNT(*) > 5: filters groups after aggregation

 

Summary

  • Use WHERE to filter raw rows before grouping or aggregation.
  • Use HAVING to filter groups created by GROUP BY.

Both can be used together in the same query to create precise and efficient filtering logic.

  

Comments

Popular posts from this blog

Debouncing & Throttling in RxJS: Optimizing API Calls and User Interactions

Promises in Angular

Comprehensive Guide to C# and .NET Core OOP Concepts and Language Features