Beginner

390. WHERE vs HAVING

Understand when to use WHERE and when to use HAVING in SQL queries.

📘 Lesson 390 of 728 ⏱ 12 min 🎯 Intermediate

WHERE filters individual rows before grouping and aggregation, while HAVING filters groups after GROUP BY and aggregate calculations.

Choosing the correct filtering clause improves query clarity, correctness, and often performance.

First filter active employees, then return departments having more than five active employees.

SQL
SELECT
    Department,
    COUNT(*) AS EmployeeCount
FROM Employees
WHERE Status = 'Active'
GROUP BY Department
HAVING COUNT(*) > 5;

This pattern is common in business reporting, customer analysis, sales reporting, and operational dashboards.

  • WHERE filters rows.
  • HAVING filters groups.
  • WHERE normally occurs before GROUP BY logically.
  • HAVING normally occurs after grouping.
  • Use WHERE for row-level filtering whenever possible.
Which should be used to filter rows before grouping?

WHERE should be used for row-level filtering before grouping.

Which should be used to filter aggregate results?

HAVING should be used to filter groups based on aggregate results.

Have you finished this lesson?

Introduction to SQL – All Lessons