Skip to the content

Lesson 216 of 296

GROUP BY, HAVING and aggregates

What you will learn

  • Aggregate functions
  • Grouping rows with GROUP BY
  • Filtering groups with HAVING
  • WHERE vs HAVING
  • COUNT(*) vs COUNT(column), and a LEFT JOIN trap
  • FILTER for conditional aggregates
On this page

Aggregate functions

An aggregate turns many rows into one value:

FunctionReturns
COUNT(*)Number of rows
COUNT(column)Number of non-NULL values in that column
COUNT(DISTINCT column)Number of different non-NULL values
SUM, AVG, MIN, MAXTotal, average, smallest, largest (all ignore NULLs)
STRING_AGG(name, ', '), ARRAY_AGG(...)Join values into one string or array
SQL
SELECT COUNT(*) AS customers, COUNT(city) AS with_city FROM customers;
customerswith_city
54

COUNT(city) skips Dara's NULL city.

GROUP BY

GROUP BY splits rows into groups with the same value, then calculates an aggregate per group:

SQL
SELECT status, COUNT(*) AS orders FROM orders GROUP BY status ORDER BY status;
statusorders
cancelled1
paid4
pending1

The rule: every column in SELECT must either be in GROUP BY or inside an aggregate. SELECT status, ordered_at, COUNT(*) ... GROUP BY status is an error: which ordered_at would it show for a group of four orders? (PostgreSQL allows other columns of a table when you group by that table's primary key, as below.)

Total spent per customer on paid orders:

SQL
SELECT c.name,
       COUNT(DISTINCT o.id) AS paid_orders,
       SUM(oi.quantity * oi.unit_price_pence) AS spent_pence
FROM customers c
JOIN orders o ON o.customer_id = c.id AND o.status = 'paid'
JOIN order_items oi ON oi.order_id = o.id
GROUP BY c.id, c.name
ORDER BY spent_pence DESC;
namepaid_ordersspent_pence
Chen Li27297
Aisha Khan25247

COUNT(DISTINCT o.id) is needed because the join to order_items gives one row per item (fan-out, Lesson 215); COUNT(*) would count items, not orders.

HAVING

WHERE filters rows before grouping. HAVING filters groups after grouping, so it can use aggregates:

SQL
SELECT c.name, SUM(oi.quantity * oi.unit_price_pence) AS spent_pence
FROM customers c
JOIN orders o ON o.customer_id = c.id
JOIN order_items oi ON oi.order_id = o.id
WHERE o.status = 'paid'
GROUP BY c.id, c.name
HAVING SUM(oi.quantity * oi.unit_price_pence) > 4000
ORDER BY spent_pence DESC;
namespent_pence
Chen Li7297
Aisha Khan5247

Interview answer: "WHERE filters rows and cannot use aggregates; HAVING filters groups and can." Put conditions that do not need aggregates in WHERE: fewer rows to group means a faster query.

Several aggregates per group

SQL
SELECT p.category,
       SUM(oi.quantity) AS units,
       ROUND(AVG(oi.unit_price_pence)) AS avg_price_pence,
       MIN(oi.unit_price_pence) AS cheapest,
       MAX(oi.unit_price_pence) AS dearest
FROM order_items oi
JOIN products p ON p.id = oi.product_id
JOIN orders o ON o.id = oi.order_id
WHERE o.status <> 'cancelled'
GROUP BY p.category
ORDER BY units DESC;
categoryunitsavg_price_pencecheapestdearest
Stationery67174501250
Kitchen4899899899
Home2299929992999

The LEFT JOIN COUNT trap

"How many orders does each customer have, including customers with none?"

SQL
SELECT c.name, COUNT(o.id) AS orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY c.id;
nameorders
Aisha Khan2
Ben Smith1
Chen Li2
Dara Patel1
Eve Jones0

If you write COUNT(*) instead of COUNT(o.id), Eve gets 1, because her LEFT JOIN row exists (with NULLs). COUNT(o.id) counts only non-NULL order IDs. A favourite "spot the bug" question.

Conditional aggregates with FILTER

SQL
SELECT COUNT(*) FILTER (WHERE status = 'paid') AS paid,
       COUNT(*) FILTER (WHERE status <> 'paid') AS not_paid,
       SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM orders;
paidnot_paidcancelled
421

FILTER is PostgreSQL (and the SQL standard); the SUM(CASE ...) form works in every database.

How to say it in an interview

"Aggregates like COUNT, SUM, AVG, MIN and MAX collapse rows into one value and ignore NULLs, except COUNT star, which counts rows. GROUP BY computes them per group, and every selected column must be grouped or aggregated. WHERE filters rows before grouping and cannot use aggregates; HAVING filters groups after. Two traps: joins fan out rows, so I use COUNT DISTINCT or pre-aggregate, and after a LEFT JOIN I count a column from the right table, not star, so customers without orders get zero."

Key words

WordMeaning
Aggregate functionCalculates one value from many rows
GROUP BYSplits rows into groups for aggregation
HAVINGFilters groups after aggregation
COUNT(*) vs COUNT(col)Counts rows vs counts non-NULL values
FILTERApplies a condition to one aggregate

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.