Skip to content
Bronze 6 min read · Aggregation 3 practice problems ↓

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

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

restaurantamount
Spice Route420
Spice Route310
Spice Route540
Wok Inn280
Wok Inn190
Wok Inn360

Output

restaurantordersrevenue
Spice Route31270
Wok Inn3830

Three Spice Route rows become one row with their count and their sum.

Spark SQL · Orders and revenue per restaurant

Input: orders

order_idcustomer_idrestaurantcityamountstatusplaced_at
1011Spice RoutePune420delivered2026-03-01 12:10:00
1022Pizza LabDelhi650cancelled2026-03-01 19:40:00
1031Pizza LabPunenullNULL: 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 →delivered2026-03-02 13:05:00
1043Spice RoutePune310null2026-03-03 20:15:00
1052Wok InnDelhi280delivered2026-03-04 21:00:00
1064Spice RoutePune540delivered2026-03-05 13:30:00
1079Wok InnMumbai190delivered2026-03-05 20:45:00
1081Wok InnPune360refunded2026-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:

Spark SQL · Fails: which city should a restaurant row 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:

  1. FROM

    orders

  2. WHERE

    rows in

  3. GROUP BY

    make groups

  4. HAVING

    groups out

  5. SELECT

    one row each

Spark SQL · Restaurants with at least two delivered orders

Input: orders

order_idcustomer_idrestaurantcityamountstatusplaced_at
1011Spice RoutePune420delivered2026-03-01 12:10:00
1022Pizza LabDelhi650cancelled2026-03-01 19:40:00
1031Pizza LabPunenulldelivered2026-03-02 13:05:00
1043Spice RoutePune310null2026-03-03 20:15:00
1052Wok InnDelhi280delivered2026-03-04 21:00:00
1064Spice RoutePune540delivered2026-03-05 13:30:00
1079Wok InnMumbai190delivered2026-03-05 20:45:00
1081Wok InnPune360refunded2026-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.

Tip: A condition that does not use an aggregate belongs in WHERE, even though HAVING would accept it. Filtering rows before grouping means less data to group, which on a large table is the difference between seconds and minutes.

Grouping by an expression

You can group by anything you can compute. Daily revenue groups by the date part of the timestamp:

Spark SQL · Revenue per day

Input: orders

order_idcustomer_idrestaurantcityamountstatusplaced_at
1011Spice RoutePune420delivered2026-03-01 12:10:00
1022Pizza LabDelhi650cancelled2026-03-01 19:40:00
1031Pizza LabPunenulldelivered2026-03-02 13:05:00
1043Spice RoutePune310null2026-03-03 20:15:00
1052Wok InnDelhi280delivered2026-03-04 21:00:00
1064Spice RoutePune540delivered2026-03-05 13:30:00
1079Wok InnMumbai190delivered2026-03-05 20:45:00
1081Wok InnPune360refunded2026-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:

Spark SQL · Customers per city

Input: customers

customer_idnamecitysignup_datereferred_by
1AshaPune2026-01-05null
2RaviDelhi2026-01-201
3Meeranull2026-02-021
4KabirPune2026-02-142
5ZoyaMumbai2026-03-01null
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(*) or sum(...) 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 filters rows before grouping; HAVING filters groups after grouping, so only HAVING can test an aggregate. Example: restaurants with at least two delivered orders: 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?"
Yes. The whole table is then one group: 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."
Group by customer and day, then filter the groups: 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?"
No. In Spark and PostgreSQL it does not even run, because name is neither grouped nor aggregated. Old MySQL would run it and return an arbitrary name, not the one with the max salary. Use a window function (rank within dept) or max_by(name, salary) in Spark.

Check yourself

4 questions

Which 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 read
Conditional 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

Previous: CASE WHEN and expressions

Primary sources: GROUP BY clause · HAVING clause