SQL GROUP BY With HAVING: Filter Aggregated Results
GROUP BY With HAVING is a SQL query that group by aggregates employees by department. Formula Genius generates and validates this formula automatically from a plain-English prompt.
WHERE filters rows before grouping. HAVING filters groups after aggregation. Know when to use each.
The Formula
"Find departments where total salary exceeds 500,000"
SELECT department, COUNT(*) AS headcount, SUM(salary) AS total_salary
FROM employees
GROUP BY department
HAVING SUM(salary) > 500000
ORDER BY total_salary DESC;
GROUP BY aggregates employees by department. HAVING filters to only departments where the SUM of salaries exceeds 500,000. WHERE couldn't do this because the sum doesn't exist until after grouping.
Step-by-Step Breakdown
- SELECT department, COUNT(*), SUM(salary) — what to show per group
- FROM employees — source table
- GROUP BY department — create one row per department
- HAVING SUM(salary) > 500000 — filter groups by aggregate condition
- ORDER BY total_salary DESC — show highest-spending departments first
Edge Cases & Warnings
- HAVING without GROUP BY treats the entire table as one group
- Column aliases (total_salary) may not work in HAVING in some databases — use the full expression
- NULL values in GROUP BY column create their own group
- Multiple HAVING conditions: use AND/OR like in WHERE
Examples
"Engineering: 10 people, $1.2M total"
Included (>500K)
"HR: 3 people, $250K total"
Excluded (<500K)
Frequently Asked Questions
What's the difference between WHERE and HAVING?
WHERE filters individual rows BEFORE grouping. HAVING filters groups AFTER aggregation. You can't use SUM() in WHERE because the sum hasn't been calculated yet.
Can I use WHERE and HAVING together?
Yes. WHERE filters rows first, GROUP BY groups the remaining rows, then HAVING filters the groups. Example: WHERE hire_date > '2025-01-01' HAVING COUNT(*) > 5.
Can't find what you need?
Describe any formula in plain English and Formula Genius will generate, explain, and validate it — instantly.