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.

25 min 3 practice tasks
Advanced Aggregate Functions in SQL (GROUP BY, HAVING vs. WHERE) by Becoming a Data Scientist on YouTube

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:

  1. FROM: pick the table
  2. WHERE: drop rows
  3. GROUP BY: form groups
  4. HAVING: drop groups
  5. SELECT: compute the output columns
  6. ORDER BY: sort
  7. LIMIT: 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, HAVING and WHERE work 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.

1

Orders by status

For 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?
  1. Add GROUP BY status so you get one row per status instead of one row overall.
  2. Sort on the count: ORDER BY COUNT(*) DESC (or use its alias).
SQL · SQLite
SELECT status, COUNT(*)
FROM orders;
Tables in this database
advertisers (12 rows)
id, name, industry, country
campaigns (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders (900 rows)
id, customer_id, campaign_id, order_date, amount, status
ab_test (4,000 rows)
user_id, variant, device, time_on_page_sec, converted, revenue
2

New customers by country and segment

Marketing 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?
  1. Filter individual customers by signup date with WHERE, before grouping.
  2. Group by both columns: GROUP BY country, segment, and sort by both too.
SQL · SQLite
SELECT country, segment, COUNT(*) AS customers
FROM customers
GROUP BY country
ORDER BY country;
Tables in this database
advertisers (12 rows)
id, name, industry, country
campaigns (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders (900 rows)
id, customer_id, campaign_id, order_date, amount, status
ab_test (4,000 rows)
user_id, variant, device, time_on_page_sec, converted, revenue
3

Campaigns that spent over 40k

Which 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?
  1. WHERE can't see totals because it runs before grouping. Filter groups with HAVING.
  2. HAVING SUM(spend) > 40000 goes after GROUP BY and before ORDER BY.
SQL · SQLite
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)
id, name, industry, country
campaigns (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders (900 rows)
id, customer_id, campaign_id, order_date, amount, status
ab_test (4,000 rows)
user_id, variant, device, time_on_page_sec, converted, revenue