10. GROUP BY: a summary for each group

Split the rows into groups and sum up each one: customers per city, sales per product, per month.

Splitting rows into groups with GROUP BY

In the last chapter count(*) found 10 customers. To know how many live in each city, the database has to split the rows into groups by city first, then count inside each group. That is what GROUP BY does:

SELECT city, count(*) AS customers
FROM customer
GROUP BY city;
citycustomers
Bangkok4
Chiang Mai2
Khon Kaen2
Phuket2
4 rows

Rows with the same city go into one group, and each group comes out as one row. The 10 customers become 4 rows: Bangkok has 4, and Chiang Mai, Khon Kaen and Phuket 2 each.

Now city beside count(*) means something: inside a group, city has just one value.

Orders by status:

SELECT status, count(*) AS orders
FROM orders
GROUP BY status;
statusorders
cancelled2
paid8
shipped5
3 rows

8 paid, 5 shipped, 2 cancelled: 15 orders in all.

Several summaries for each group

Every aggregate from chapter 9 works on groups, and you can use several at once. The products of each category:

SELECT category_id, count(*) AS products, min(price), max(price), sum(stock) AS in_stock
FROM product
GROUP BY category_id;
category_idproductsmin(price)max(price)in_stock
1340.055.0200
2335.0120.050
3325.0150.0265
4315.030.0375
4 rows

Each category has 3 products. Category 3 (snacks) has the widest spread of prices, from 25 to 150 baht.

Sales per product, from order_item, best first with ORDER BY (which comes after GROUP BY):

SELECT product_id, sum(qty) AS sold, sum(qty * price) AS sales
FROM order_item
GROUP BY product_id
ORDER BY sales DESC, product_id;
product_idsoldsales
1018540.0
1135525.0
17385.0
63360.0
84360.0
92300.0
711275.0
25225.0
46210.0
53180.0
3280.0
11 rows

Product 10 (Notebook) made the most money, 540 baht, but product 11 (Pen) sold the most items, 35. Product 12 doesn't appear at all: it never sold, so order_item has no row of it to group.

Products 6 and 8 both sold 360 baht, so product_id follows in ORDER BY to make the order certain every time. Without it, rows with equal values may come in any order.

Grouping by several columns, or by an expression

GROUP BY takes several columns; rows share a group when every one of them matches. How many orders of each status each customer has:

SELECT customer_id, status, count(*) AS orders
FROM orders
GROUP BY customer_id, status;
customer_idstatusorders
1paid2
1shipped1
2paid1
2shipped1
3cancelled1
3paid1
4cancelled1
4paid1
5shipped1
6paid1
6shipped1
7paid2
8shipped1
13 rows

Customer 1 has two rows: 2 paid and 1 shipped. The 15 orders make 13 groups.

An expression works too. By month, cutting the date down with strftime('%Y-%m', ...) from chapter 8:

SELECT strftime('%Y-%m', ordered) AS month, count(*) AS orders
FROM orders
GROUP BY month;
monthorders
2026-094
2026-106
2026-115
3 rows

4 in September, 6 in October, 5 in November. Note that GROUP BY month uses the name given with AS: SQLite and Phai SQL allow it. For SQL that may move to another database, repeat the whole expression in GROUP BY instead.

Sales per month and per category

Sales per month need two tables: the date is in orders, the quantity and price in order_item. Putting two tables together is a JOIN, which chapter 11 explains step by step. For now, just see that GROUP BY works on a join's result as it does on one table:

SELECT strftime('%Y-%m', o.ordered) AS month, sum(i.qty * i.price) AS sales
FROM orders AS o
JOIN order_item AS i ON i.order_id = o.id
WHERE o.status <> 'cancelled'
GROUP BY month;
monthsales
2026-09820.0
2026-101450.0
2026-11940.0
3 rows

Leaving out cancelled orders: 820 baht in September, 1,450 in October, 940 in November.

Sales per category, with the category's name from category:

SELECT c.name AS category, sum(i.qty * i.price) AS sales
FROM order_item AS i
JOIN product AS p ON p.id = i.product_id
JOIN category AS c ON c.id = p.category_id
GROUP BY c.name
ORDER BY sales DESC;
categorysales
Stationery1065.0
Snacks935.0
Bakery750.0
Drinks690.0
4 rows

Stationery sold the most, 1,065 baht, and drinks the least, 690 baht (this one doesn't leave out cancelled orders).

HAVING: filtering groups

WHERE filters rows, before the grouping. HAVING filters groups, after the summing up, so it can use aggregates. Orders worth 300 baht or more:

SELECT order_id, sum(qty * price) AS total
FROM order_item
GROUP BY order_id
HAVING sum(qty * price) >= 300;
order_idtotal
4300.0
8390.0
9490.0
11300.0
15375.0
5 rows

5 orders; order 9 is the largest, at 490 baht.

Both can be in one statement. Customers with 2 or more orders, not counting cancelled ones:

SELECT customer_id, count(*) AS orders
FROM orders
WHERE status <> 'cancelled'
GROUP BY customer_id
HAVING count(*) >= 2;
customer_idorders
13
22
62
72
4 rows

WHERE drops the cancelled orders (2 of them) first; then the groups are counted; last, HAVING keeps the groups that counted 2 or more. That leaves 4 customers. Customers 3 and 4 drop out, because their other order was cancelled.

A condition that has nothing to do with a summary belongs in WHERE, not HAVING. The result is the same, but WHERE drops the rows at the start, so the database does less work, and the statement is easier to read. A condition on count, sum and the like can only go in HAVING.

The order you write and the order it works

A SELECT's parts are always written in this order, but the database works them out in another:

WrittenWorked outWhat it does
1. SELECT5picks columns, works out expressions, names them
2. FROM1reads the tables (and JOINs)
3. WHERE2filters rows
4. GROUP BY3groups and sums up
5. HAVING4filters groups
6. ORDER BY6sorts
7. LIMIT7keeps only some rows

The working order explains a lot: WHERE can't use count(*) because nothing is grouped yet; ORDER BY can use the names given in SELECT because it comes after; and LIMIT cuts after the sorting, so you get the right "top few". The 3 best-selling products:

SELECT product_id, sum(qty * price) AS sales
FROM order_item
GROUP BY product_id
ORDER BY sales DESC
LIMIT 3;
product_idsales
10540.0
11525.0
1385.0
3 rows

A bare column in a grouped query

Standard SQL's rule: in a statement with GROUP BY, every column in SELECT must be one of the grouping columns or sit inside an aggregate. SQLite and Phai SQL don't enforce it:

SELECT customer_id, ordered, count(*) AS orders
FROM orders
GROUP BY customer_id;
customer_idorderedorders
12026-09-023
22026-09-052
32026-09-202
42026-10-012
52026-10-031
62026-10-152
72026-10-222
82026-11-021
8 rows

Customer 1 ordered 3 times (2 and 12 September, 28 October), but ordered shows only 2026-09-02: the value of some row in the group, not the first or latest date chosen on purpose.

Don't rely on a bare column like this. It isn't an error, so nothing warns you, but the value means nothing, and other databases refuse the statement. For the latest order date, say so: max(ordered).

SELECT customer_id, min(ordered) AS first_order, max(ordered) AS last_order, count(*) AS orders
FROM orders
GROUP BY customer_id;
customer_idfirst_orderlast_orderorders
12026-09-022026-10-283
22026-09-052026-10-102
32026-09-202026-11-182
42026-10-012026-11-052
52026-10-032026-10-031
62026-10-152026-11-112
72026-10-222026-11-252
82026-11-022026-11-021
8 rows
  1. Count the products of each category (category_id), only those still in stock (stock > 0).
  2. How many items (sum(qty)) each order has, most first; equal ones by order number.
  3. Which cities have more than 2 customers?
  4. Sales per product (product_id), only products that sold 300 baht or more altogether.
Show the answer
SELECT category_id, count(*) FROM product WHERE stock > 0 GROUP BY category_id;
SELECT order_id, sum(qty) AS items FROM order_item GROUP BY order_id ORDER BY items DESC, order_id;
SELECT city, count(*) FROM customer GROUP BY city HAVING count(*) > 2;
SELECT product_id, sum(qty * price) AS sales FROM order_item GROUP BY product_id HAVING sales >= 300;
category_idcount(*)
12
23
33
42
4 rows
order_iditems
823
415
1515
98
67
117
14
24
73
123
32
142
51
101
131
15 rows
citycount(*)
Bangkok4
1 row
product_idsales
1385.0
6360.0
8360.0
9300.0
10540.0
11525.0
6 rows

Phai (bamboo), given as a gift of knowledge: free to use, learn from and pass on · every example on this page was run on Phai SQL and checked against SQLite when the page was made