Home/Blog/GROUP BY vs HAVING: What's the Difference?
SQL BasicsAggregation

GROUP BY vs HAVING: What's the Difference?

SQLab Team·2025-01-05·5 min read

GROUP BY and HAVING are two of the most misunderstood SQL clauses. Many beginners mix them up or don't know when to use each. This guide will clear up the confusion permanently.

Practice these queries in SQLab →
Real SQLite engine · 8 tables · No signup needed
Open Playground

GROUP BY

What does GROUP BY do?

GROUP BY collapses multiple rows into a single summary row per group. Every column in SELECT must either be in GROUP BY or wrapped in an aggregate function.

Example

SELECT department, COUNT(*) AS headcount, ROUND(AVG(salary), 0) AS avg_salary
FROM employees
GROUP BY department
ORDER BY avg_salary DESC;

HAVING

What does HAVING do?

HAVING filters groups AFTER GROUP BY has run. Think of it as WHERE for aggregate results. You cannot use WHERE to filter on COUNT(*) — you must use HAVING.

Example

SELECT department, COUNT(*) AS headcount
FROM employees
GROUP BY department
HAVING COUNT(*) > 10
ORDER BY headcount DESC;

-- Only departments with more than 10 employees

The key rule

WHERE runs BEFORE aggregation (filters rows). HAVING runs AFTER aggregation (filters groups). You can use both in the same query.

Ready to practice?

Run all the queries from this article in our free SQL playground.

Open SQL Playground →

Related Articles

Top 30 SQL Interview Questions (2025)12 min readSQL JOINs Explained with Real Examples8 min readSQL Window Functions: A Complete Guide10 min read