GROUP BY and HAVING
"Revenue per restaurant", "orders per city", "average basket per customer": most business questions summarise many rows into a few. GROUP BY does that. This lesson shows how rows become groups, what a grouped query may select, and how HAVING filters the groups.
Foundations · SQL for data engineers · Bronze · Summarising, lesson 1 of 2
On this page
Read first: SELECT, WHERE and ORDER BY (skip if you know it)
In plain words first
Picture a pile of receipts from three restaurants. To get each restaurant's total, you sort the receipts into three piles, one per restaurant, then add up each pile. You end with three numbers, one per pile; the individual receipts are gone.
GROUP BY is the sorting into piles, and sum, count and avg are the adding up. WHERE throws receipts away before sorting; HAVING throws whole piles away after adding up.
One row per group
GROUP BY puts rows with the same value in a column into one group, then turns each group into a single row. Aggregate functions, count, sum, avg, min and max, summarise the rows of each group.
Input
| restaurant | amount |
|---|---|
| Spice Route | 420 |
| Spice Route | 310 |
| Spice Route | 540 |
| Wok Inn | 280 |
| Wok Inn | 190 |
| Wok Inn | 360 |
Output
| restaurant | orders | revenue |
|---|---|---|
| Spice Route | 3 | 1270 |
| Wok Inn | 3 | 830 |
Three Spice Route rows become one row with their count and their sum.
Input: orders
| order_id | customer_id | restaurant | city | amount | status | placed_at |
|---|---|---|---|---|---|---|
| 101 | 1 | Spice Route | Pune | 420 | delivered | 2026-03-01 12:10:00 |
| 102 | 2 | Pizza Lab | Delhi | 650 | cancelled | 2026-03-01 19:40:00 |
| 103 | 1 | Pizza Lab | Pune | nullNULL: A missing or unknown value. It is not 0 or an empty string, and any comparison with it is unknown instead of true or false. Learn more → | delivered | 2026-03-02 13:05:00 |
| 104 | 3 | Spice Route | Pune | 310 | null | 2026-03-03 20:15:00 |
| 105 | 2 | Wok Inn | Delhi | 280 | delivered | 2026-03-04 21:00:00 |
| 106 | 4 | Spice Route | Pune | 540 | delivered | 2026-03-05 13:30:00 |
| 107 | 9 | Wok Inn | Mumbai | 190 | delivered | 2026-03-05 20:45:00 |
| 108 | 1 | Wok Inn | Pune | 360 | refunded | 2026-03-06 19:10:00 |
SELECT restaurant, count(*) AS orders, sum(amount) AS revenue, round(avg(amount), 1) AS avg_amount FROM orders GROUP BY restaurant ORDER BY revenue DESC
Pizza Lab has 2 orders but its average is 650: order 103 has no amount, and AVG skips NULLs. COUNT(*) still counts that order.
The rule for SELECT
After GROUP BY, each output row stands for a whole group. So every item in SELECT must have one value per group: either a column you grouped by, or an aggregate over the group. A column that differs inside a group has no single value to show:
SELECT restaurant, city, count(*) FROM orders GROUP BY restaurant
Error
[MISSING_AGGREGATION] The non-aggregating expression "city" is based on columns which are not participating in the GROUP BY clause.
Wok Inn has orders in Delhi, Mumbai and Pune, so city has three values in that group. Fix it by grouping by both columns (one row per restaurant and city), or by aggregating it, for example count(DISTINCT city). MySQL used to allow this query and pick a city at random; Spark, PostgreSQL and the SQL standard refuse.
WHERE filters rows, HAVING filters groups
WHERE runs before grouping and decides which rows go into the groups. HAVING runs after grouping and decides which groups to keep, so it can test an aggregate:
-
FROM
orders
-
WHERE
rows in
-
GROUP BY
make groups
-
HAVING
groups out
-
SELECT
one row each
Input: orders
| order_id | customer_id | restaurant | city | amount | status | placed_at |
|---|---|---|---|---|---|---|
| 101 | 1 | Spice Route | Pune | 420 | delivered | 2026-03-01 12:10:00 |
| 102 | 2 | Pizza Lab | Delhi | 650 | cancelled | 2026-03-01 19:40:00 |
| 103 | 1 | Pizza Lab | Pune | null | delivered | 2026-03-02 13:05:00 |
| 104 | 3 | Spice Route | Pune | 310 | null | 2026-03-03 20:15:00 |
| 105 | 2 | Wok Inn | Delhi | 280 | delivered | 2026-03-04 21:00:00 |
| 106 | 4 | Spice Route | Pune | 540 | delivered | 2026-03-05 13:30:00 |
| 107 | 9 | Wok Inn | Mumbai | 190 | delivered | 2026-03-05 20:45:00 |
| 108 | 1 | Wok Inn | Pune | 360 | refunded | 2026-03-06 19:10:00 |
SELECT restaurant, count(*) AS delivered FROM orders WHERE status = 'delivered' GROUP BY restaurant HAVING count(*) >= 2
WHERE first throws away the cancelled, refunded and unknown orders. Then each restaurant is counted, and HAVING keeps Spice Route and Wok Inn with 2 each; Pizza Lab has 1. WHERE count(*) >= 2 would fail: when WHERE runs, there are no groups to count yet.
Grouping by an expression
You can group by anything you can compute. Daily revenue groups by the date part of the timestamp:
Input: orders
| order_id | customer_id | restaurant | city | amount | status | placed_at |
|---|---|---|---|---|---|---|
| 101 | 1 | Spice Route | Pune | 420 | delivered | 2026-03-01 12:10:00 |
| 102 | 2 | Pizza Lab | Delhi | 650 | cancelled | 2026-03-01 19:40:00 |
| 103 | 1 | Pizza Lab | Pune | null | delivered | 2026-03-02 13:05:00 |
| 104 | 3 | Spice Route | Pune | 310 | null | 2026-03-03 20:15:00 |
| 105 | 2 | Wok Inn | Delhi | 280 | delivered | 2026-03-04 21:00:00 |
| 106 | 4 | Spice Route | Pune | 540 | delivered | 2026-03-05 13:30:00 |
| 107 | 9 | Wok Inn | Mumbai | 190 | delivered | 2026-03-05 20:45:00 |
| 108 | 1 | Wok Inn | Pune | 360 | refunded | 2026-03-06 19:10:00 |
SELECT to_date(placed_at) AS day, count(*) AS orders, sum(amount) AS revenue FROM orders GROUP BY to_date(placed_at) ORDER BY day
2 March has one order with no amount, so its revenue is NULL, not 0: SUM over nothing but NULLs is NULL. Reports usually want coalesce(sum(amount), 0). Days with no orders at all do not appear; filling those gaps needs a calendar table, which the Silver lesson on dates covers.
NULL keys form one group
NULL never equals NULL in a comparison, but GROUP BY puts all NULL keys into a single group, as does DISTINCT:
Input: customers
| customer_id | name | city | signup_date | referred_by |
|---|---|---|---|---|
| 1 | Asha | Pune | 2026-01-05 | null |
| 2 | Ravi | Delhi | 2026-01-20 | 1 |
| 3 | Meera | null | 2026-02-02 | 1 |
| 4 | Kabir | Pune | 2026-02-14 | 2 |
| 5 | Zoya | Mumbai | 2026-03-01 | null |
SELECT city, count(*) AS customers FROM customers GROUP BY city ORDER BY customers DESC, city
Meera has no city and becomes a group of her own. Keep that group in data quality reports, since it shows how much data is missing; label it with coalesce(city, 'unknown') if people will read it.
Common mistakes
- Selecting a column that is not grouped — Every SELECT item must be a GROUP BY column or an aggregate. Group by it too, or aggregate it.
- Filtering on an aggregate in WHERE — WHERE runs before groups exist. Conditions on
count(*)orsum(...)go in HAVING. - Putting row filters in HAVING — It works, but groups more data than needed. Plain row conditions belong in WHERE.
- Expecting SUM over NULLs to be 0 — SUM of a group with only NULLs is NULL. Wrap it in
coalesce(sum(x), 0)when a report needs a number.
Key takeaways
- GROUP BY turns each group of rows into one row; aggregates summarise the group.
- Every SELECT item is either grouped or aggregated.
- WHERE filters rows before grouping; HAVING filters groups after, and can use aggregates.
- NULL keys form one group, and SUM over only NULLs is NULL.
Interview prep
THE QUESTION
"What is the difference between WHERE and HAVING? Give an example where you need both."
WHERE status = 'delivered' GROUP BY restaurant HAVING count(*) >= 2. The status test must be in WHERE, because after grouping there is no single status per restaurant; the count test must be in HAVING. Mention that row filters belong in WHERE for performance even when HAVING would accept them.Avoid: "They are the same thing, HAVING is just WHERE for GROUP BY." The point is when each runs: WHERE before the groups exist, HAVING after.
Follow-ups · answer out loud, then open
Follow-up"Can you use HAVING without GROUP BY?"
SELECT count(*) FROM orders HAVING count(*) > 100 returns one row or none. It is rare, but it shows you know HAVING filters groups.Scenario"Find the customers who placed more than one order on the same day."
SELECT customer_id, to_date(placed_at) AS day, count(*) FROM orders GROUP BY customer_id, to_date(placed_at) HAVING count(*) > 1. Grouping by an expression is fine; repeat it in SELECT so each output row shows its day.Trap"SELECT dept, name, max(salary) FROM emp GROUP BY dept returns each department's best-paid employee. Correct?"
max_by(name, salary) in Spark.Check yourself
4 questionsWhich clause can test count(*) > 5?
Show the answer
HAVING. Aggregates exist only after grouping, so the test goes in HAVING.
A query groups by restaurant and selects restaurant, city. When does it fail?
Show the answer
Always. Spark rejects any ungrouped, unaggregated column, whatever the data holds.
Three customers have no city. How many rows does GROUP BY city give them?
Show the answer
1. GROUP BY puts all NULL keys into one group.
Every amount in a group is NULL. What is sum(amount)?
Show the answer
NULL. SUM skips NULLs; with nothing left to add it returns NULL.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · Summarising · lesson 2 of 2 · 6 min readConditional aggregates and COUNT DISTINCT
Count and sum only some rows inside one GROUP BY with FILTER, CASE and count_if, and count unique values.
Related lessons
NULL and three-valued logicSQL for data engineers · 7 min read
Inner and outer joins
Previous: CASE WHEN and expressions
Primary sources: GROUP BY clause · HAVING clause