Definition, Use of Group by and Having Clause
Estimated study time: 12 minutes. Group your data, then filter the groups themselves.
GROUP BY and HAVING work together to summarize data by category and then filter those summaries — something a plain WHERE clause can't do on its own.
What GROUP BY Does
Groups rows that share the same value in one or more columns, so aggregate functions can be applied per group instead of across the whole table.
SELECT department, COUNT(*) AS total_employees FROM employees GROUP BY department;
What HAVING Does
HAVING filters groups after aggregation, unlike WHERE, which filters individual rows before grouping happens.
SELECT department, COUNT(*) AS total_employees FROM employees GROUP BY department HAVING COUNT(*) > 10;
Using WHERE and HAVING Together
SELECT department, AVG(salary) AS avg_salary FROM employees WHERE hire_date > '2020-01-01' GROUP BY department HAVING AVG(salary) > 60000;
Here, WHERE filters out employees hired before 2020 first, then GROUP BY groups the remaining rows, and finally HAVING keeps only departments whose average salary exceeds 60,000.
COUNT() inside a WHERE clause — that's exactly why HAVING exists.Common Mistakes
- Trying to filter on an aggregate using
WHEREinstead ofHAVING - Selecting a column that isn't in
GROUP BYor wrapped in an aggregate function - Forgetting that
HAVINGruns after grouping, so it can reference aggregate results directly
How MySQL Processes a Grouped Query
Seeing the steps in order makes GROUP BY and HAVING much easier to reason about. Take this sample orders table:
| order_id | city | status | amount |
|---|---|---|---|
| 1 | Delhi | paid | 1200 |
| 2 | Delhi | paid | 800 |
| 3 | Pune | paid | 500 |
| 4 | Pune | cancelled | 900 |
| 5 | Jaipur | paid | 2500 |
SELECT city, COUNT(*) AS orders, SUM(amount) AS revenue
FROM orders
WHERE status = 'paid'
GROUP BY city
HAVING SUM(amount) >= 1000
ORDER BY revenue DESC;
- WHERE removes order 4 because it is cancelled.
- GROUP BY forms three groups: Delhi (1200, 800), Pune (500) and Jaipur (2500).
- Aggregates are calculated per group: Delhi 2000, Pune 500, Jaipur 2500.
- HAVING drops Pune because its total is below 1000.
- ORDER BY sorts the remaining groups, giving Jaipur first, then Delhi.
Grouping by Several Columns and Adding Subtotals
You can group by more than one column, which creates one group for every unique combination:
SELECT city, status, COUNT(*) AS orders
FROM orders
GROUP BY city, status;
MySQL also supports WITH ROLLUP, which adds subtotal rows and a grand total. The subtotal rows show NULL in the grouped column:
SELECT city, SUM(amount) AS revenue
FROM orders
GROUP BY city WITH ROLLUP;
To count distinct values inside each group, use COUNT(DISTINCT customer_id), which is a common way to find unique buyers per city.
ONLY_FULL_GROUP_BY and Why Queries Suddenly Fail
Modern MySQL versions enable the ONLY_FULL_GROUP_BY SQL mode by default. Under this mode, a query like the one below is rejected because order_id is neither grouped nor aggregated:
SELECT city, order_id, SUM(amount)
FROM orders
GROUP BY city; -- error under ONLY_FULL_GROUP_BY
This is protective: MySQL would otherwise return an arbitrary order_id from each group. Fix the query by aggregating the column (for example MAX(order_id)), adding it to the GROUP BY, or using ANY_VALUE(order_id) when any value is genuinely acceptable. Turning the mode off hides the problem rather than solving it.
When to Use HAVING and When Not To
- Filter plain column values in WHERE. It runs before grouping, so fewer rows are processed and indexes can help.
- Use HAVING only for conditions on aggregates, such as totals, averages or counts.
- If you need a per-row value next to group totals without collapsing rows, a window function such as
SUM(amount) OVER (PARTITION BY city)is the better tool.
Practice task: find customers who placed at least three paid orders and spent more than 5000 in total. You will need WHERE, GROUP BY and a HAVING clause with two conditions joined by AND.