beginner

HAVING Clause

6 min readLast updated: 2026-07-23

Overview

The HAVING clause filters aggregated groups after they have been processed by a GROUP BY clause.

Learning Objectives

  • Distinguish between row-level filters (WHERE) and group-level filters (HAVING).
  • Write conditional checks on aggregate expressions.
  • Combine WHERE, GROUP BY, and HAVING in a single query.

Detailed Concept Explanation

  • WHERE: Filters rows before any grouping or aggregation takes place.
  • HAVING: Filters groups after rows are grouped and aggregated.

Because WHERE runs before grouping, it cannot reference aggregate values (e.g., WHERE COUNT(*) > 5 triggers a compilation error). To filter groups based on aggregate results, you must use HAVING.


Code Examples

SQL

sql
-- INCORRECT: Cannot filter aggregate in WHERE
SELECT dept, SUM(salary) 
FROM employees 
WHERE SUM(salary) > 500000 
GROUP BY dept;

-- CORRECT: Filter group aggregates using HAVING
SELECT dept, SUM(salary) AS total_payroll
FROM employees 
GROUP BY dept 
HAVING SUM(salary) > 500000;

-- Combined pipeline filter
SELECT country, COUNT(*) AS customer_count
FROM customers
WHERE status = 'Active' -- 1. Filter rows
GROUP BY country        -- 2. Group rows
HAVING COUNT(*) > 10;   -- 3. Filter groups

Best Practices

  • Filter Early: Use WHERE as much as possible to filter out rows before grouping them. This reduces the volume of data the database has to process and group, making queries much faster.

Interview Perspective

Note

Interview Question: What is the difference between WHERE and HAVING?

WHERE filters individual rows before grouping, whereas HAVING filters aggregated groups after the GROUP BY clause has been executed.


Interactive Challenges

Challenge 1: Departments with large salaries spending

Select 'department_id' and the sum of salary (alias 'payroll') from 'employees' grouped by 'department_id' having a payroll greater than 200000.


Summary

HAVING filters aggregated groups after grouping is completed. Use WHERE for row filters and HAVING for group filters.