Beginner

76. WHERE vs HAVING

Understand the difference between WHERE and HAVING and when each should be used.

📘 Lesson 76 of 728 ⏱ 9 min 🎯 Beginner

WHERE and HAVING both filter data, but they operate at different stages of query processing. WHERE filters rows before grouping and aggregation, while HAVING filters grouped results after aggregation.

Using WHERE and HAVING correctly is essential for writing accurate SQL queries, especially when aggregate functions and GROUP BY are involved.

WHERE can filter employees whose salary is above ₹50,000 before grouping. HAVING can then filter departments whose resulting employee count is greater than five.

SQL
SELECT
    Department,
    COUNT(*) AS EmployeeCount
FROM Employees
WHERE Salary > 50000
GROUP BY Department
HAVING COUNT(*) > 5;

The distinction is important in sales analysis, employee reporting, customer segmentation, financial reporting, and dashboard queries.

  • WHERE filters rows.
  • HAVING filters groups.
  • WHERE normally occurs before GROUP BY.
  • HAVING normally occurs after GROUP BY.
  • HAVING is useful with aggregate conditions.
Which should filter rows before GROUP BY?

WHERE should normally be used to filter rows before grouping.

Which clause filters aggregate results?

HAVING filters grouped and aggregated results.

Have you finished this lesson?

Introduction to SQL – All Lessons