← All lessons
Combining and summarizing · Lesson 2 of 10

GROUP BY

COUNT(*) on its own gives one number for the whole table. GROUP BY sorts the rows into groups that share a value, like sorting cards into piles, and the aggregates then work on each pile separately. You get one result row per group:

SELECT category, COUNT(*) AS products
FROM products
GROUP BY category
ORDER BY category;
Returns
category | products
---------+---------
Books    | 2
Clothing | 2
Garden   | 3
Outdoors | 1
(4 rows)

Any aggregate works per group. The average price in each category:

SELECT category, ROUND(AVG(price), 2) AS avg_price, MAX(price) AS dearest
FROM products
GROUP BY category
ORDER BY avg_price DESC;
Returns
category | avg_price | dearest
---------+-----------+--------
Outdoors | 120       | 120
Clothing | 49.5      | 59
Garden   | 27.33     | 45.5
Books    | 13.88     | 18
(4 rows)

The rule to remember: every column in the SELECT list must either be in the GROUP BY or be inside an aggregate. SELECT category, name, COUNT(*) … GROUP BY category makes no sense, because Garden has three products and its one row can only show one name. PostgreSQL and most databases refuse that query. SQLite (and MySQL with some settings) let it through and quietly show the name from one of the rows, which looks right and isn't, so keep to the rule yourself.

NULLs are put together in a group of their own:

SELECT city, COUNT(*) AS customers
FROM customers
GROUP BY city
ORDER BY customers DESC, city;
Returns
city   | customers
-------+----------
Austin | 3
Boston | 2
Denver | 2
NULL   | 1
(4 rows)

You can group by more than one column: you get one row for each combination that appears. And WHERE still works, filtering the rows before they're put into groups. Shipped orders per customer:

SELECT customer_id, COUNT(*) AS shipped
FROM orders
WHERE status = 'shipped'
GROUP BY customer_id
ORDER BY customer_id;
Returns
customer_id | shipped
------------+--------
1           | 3
2           | 2
3           | 1
4           | 1
6           | 1
(5 rows)

Practice

How many customers live in each city? The city and the count.

The tables
  • customers (id, name, city, joined)
  • products (id, name, category, price)
  • orders (id, customer_id, ordered_on, status)
  • order_items (order_id, product_id, qty)
  • signups (id, email, name, signed_up_at)
  • payments (id, order_id, amount, currency, paid_at)
  • events (id, received_at, payload (JSON text))
  • staff (id, name, role, manager_id, salary, hired)
  • logins (customer_id, day)
More info

Quick reference

GROUP BY aOne result row per value of a.
GROUP BY a, bOne row per combination of a and b.
The ruleEvery SELECT column is grouped or inside an aggregate.
WHERE … GROUP BY …WHERE filters rows before they're grouped.

The other AI and data engineering courses