Section 2 · Lesson 2
GROUP BY and HAVING
Compute a summary per channel, per status or per customer group, then filter those groups with HAVING.
An aggregate on its own gives you one number for the whole table. Real questions are almost
always per something: spend per channel, orders per status, customers per country.
GROUP BY splits the rows into groups and runs the aggregate once for each group.
SELECT channel,
COUNT(*) AS campaigns,
AVG(daily_budget) AS avg_budget
FROM campaigns
GROUP BY channel;
Think of it as sorting the rows into piles by channel, then writing one summary line per pile.
Four channels in the data means four rows in the result.
The golden rule
Every column in the SELECT must be either in the GROUP BY or inside an aggregate
function. SELECT channel, name, COUNT(*) ... GROUP BY channel makes no sense: each channel
has many names, so which one should appear? PostgreSQL and SQL Server reject it. SQLite allows
it and silently picks a value from some row in the group, which is worse, because you get a
plausible-looking but meaningless answer.
Grouping by several columns
List more columns to get finer groups, one row per combination that actually occurs:
SELECT channel, objective, COUNT(*) AS campaigns
FROM campaigns
GROUP BY channel, objective
ORDER BY channel, objective;
WHERE vs HAVING
Both filter, but at different moments:
WHERE |
HAVING |
|
|---|---|---|
| Filters | individual rows | whole groups |
| Runs | before grouping | after grouping |
| Can use aggregates? | no | yes |
-- Only completed orders, then keep customers who spent over 300 in total
SELECT customer_id, SUM(amount) AS total_spent
FROM orders
WHERE status = 'completed' -- row filter
GROUP BY customer_id
HAVING SUM(amount) > 300 -- group filter
ORDER BY total_spent DESC;
Writing WHERE SUM(amount) > 300 fails with “misuse of aggregate”, because at the time WHERE
runs, no sums exist yet. A good habit: filter as much as possible with WHERE (it shrinks the
data early) and use HAVING only for conditions on aggregates.
The order SQL actually runs your query
You write clauses in one order, but the database evaluates them in another:
FROM: pick the tableWHERE: drop rowsGROUP BY: form groupsHAVING: drop groupsSELECT: compute the output columnsORDER BY: sortLIMIT: cut
This explains a lot of error messages. It’s why ORDER BY can use a column alias defined in
SELECT (sorting happens after), while WHERE can’t. SQLite is relaxed and also lets you use
aliases in GROUP BY and HAVING, but PostgreSQL won’t accept an alias in HAVING, so
repeating the expression (HAVING SUM(spend) > 40000) is the portable choice.
Sorting by an aggregate
SELECT campaign_id, SUM(conversions) AS conversions
FROM daily_stats
GROUP BY campaign_id
ORDER BY conversions DESC
LIMIT 5;
That’s the shape of most “top N by something” reports you’ll ever write: group, aggregate, sort descending, limit.
About the video: it uses the Northwind sample database, but
GROUP BY,HAVINGandWHEREwork exactly as shown.
Practice
Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.
Orders by status
DoneFor each order status, return three columns: the status, the number of orders, and the total amount rounded to 2 decimals. Sort by the number of orders, highest first.
Need a hint?
- Add
GROUP BY statusso you get one row per status instead of one row overall. - Sort on the count:
ORDER BY COUNT(*) DESC(or use its alias).
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
SELECT status, COUNT(*)
FROM orders;
Tables in this database
advertisers (12 rows)campaigns (40 rows)daily_stats (1,561 rows)customers (300 rows)orders (900 rows)ab_test (4,000 rows)New customers by country and segment
DoneMarketing wants the mix of customers who signed up in 2026 (signup_date on or after 2026-01-01). Return country, segment and the number of such customers for every country/segment combination that has at least one. Sort by country A to Z, then segment A to Z.
Need a hint?
- Filter individual customers by signup date with
WHERE, before grouping. - Group by both columns:
GROUP BY country, segment, and sort by both too.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
SELECT country, segment, COUNT(*) AS customers
FROM customers
GROUP BY country
ORDER BY country;
Tables in this database
advertisers (12 rows)campaigns (40 rows)daily_stats (1,561 rows)customers (300 rows)orders (900 rows)ab_test (4,000 rows)Campaigns that spent over 40k
DoneWhich campaigns have spent more than 40,000 USD in total? Using daily_stats, return campaign_id, the total spend rounded to 2 decimals, and the number of days with data (rows), for campaigns whose total spend is above 40,000. Sort by total spend, highest first.
Need a hint?
WHEREcan't see totals because it runs before grouping. Filter groups withHAVING.HAVING SUM(spend) > 40000goes afterGROUP BYand beforeORDER BY.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
SELECT campaign_id,
ROUND(SUM(spend), 2) AS total_spend,
COUNT(*) AS days
FROM daily_stats
GROUP BY campaign_id
ORDER BY total_spend DESC;
Tables in this database
advertisers (12 rows)campaigns (40 rows)daily_stats (1,561 rows)customers (300 rows)orders (900 rows)ab_test (4,000 rows)