Sub topic 5
Grouping by more than one column
This chapter assumes you can write basic SELECT ... FROM ... WHERE ... ORDER BY queries and have read the earlier chapters on aggregate functions, NULL handling, and single-column GROUP BY. All examples use an orders table with the columns order_id, customer_id, status, amount, and shipped_at.
What a multi-column group is
A single-column GROUP BY puts rows into the same group when they share one value. A multi-column GROUP BY puts rows into the same group only when they share the same value in every listed column. Each distinct combination of values becomes one group, and the query returns one output row per group.
SELECT customer_id,
status,
COUNT(*) AS order_count
FROM orders
GROUP BY customer_id, status;Suppose the table holds these rows:
| order_id | customer_id | status | amount |
|---|---|---|---|
| 1 | 10 | paid | 100 |
| 2 | 10 | paid | 250 |
| 3 | 10 | refunded | 100 |
| 4 | 11 | paid | 400 |
| 5 | 11 | pending | 75 |
The query forms four groups: (10, paid), (10, refunded), (11, paid), and (11, pending). Customer 10 appears in two groups because they have two different statuses. The result is:
| customer_id | status | order_count |
|---|---|---|
| 10 | paid | 2 |
| 10 | refunded | 1 |
| 11 | paid | 1 |
| 11 | pending | 1 |
Column order does not change the groups
GROUP BY customer_id, status and GROUP BY status, customer_id produce the same groups. The set of combinations is identical, so the aggregate values are identical too. Two things can differ:
- The order in which rows come back. Without
ORDER BY, SQL guarantees no row order at all. Some engines return rows sorted by the grouping columns as a side effect of how they work, but you must not rely on that. - The performance of the query. If an index exists on
(customer_id, status), the engine may use it to avoid a separate sort or hash step. The index column order matters there, even though the logical result does not.
Always add an explicit ORDER BY when the order of the output matters.
SELECT customer_id,
status,
COUNT(*) AS order_count,
SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id, status
ORDER BY customer_id, status;Granularity: choosing how fine the groups are
Each column you add to GROUP BY makes the groups finer. The number of groups can never decrease when you add a column, and it is at most the number of rows in the table. Think of the grouping columns as defining the grain of the result: "one row per customer per status".
Compare what the same data gives at different grains:
| Grouping | Groups from the sample data | Meaning of one row |
|---|---|---|
| (none) | 1 | the whole table |
| `customer_id` | 2 | one customer |
| `status` | 3 | one status |
| `customer_id, status` | 4 | one customer and status |
| `order_id` | 5 | one order (no collapsing) |
Grouping by a unique column such as order_id gives one group per row, so the aggregates just echo the original rows. That is almost never useful. If a query returns about as many rows as the table has, check whether you included a column that is too fine for your question.
NULL values form their own group
For grouping purposes, SQL treats NULLs as equal to each other, even though NULL = NULL is not true in a WHERE clause. All rows with NULL in a grouping column land in one group, and that group's key is displayed as NULL.
With several columns, a NULL in any one position is part of the combination. The combinations (10, NULL) and (10, 'paid') are different groups, and every row with (10, NULL) is in the same group.
SELECT status,
COUNT(*) AS order_count
FROM orders
GROUP BY status;If some orders have a NULL status, this query returns one extra row with status shown as NULL. Often you want to label that row. COALESCE is the usual tool, but it must appear in both the SELECT list and the GROUP BY clause, or you must group by the labelled expression:
SELECT COALESCE(status, 'unknown') AS status_label,
COUNT(*) AS order_count
FROM orders
GROUP BY COALESCE(status, 'unknown');A side effect: orders whose status really is the text 'unknown' are merged with the NULL orders. Choose a label that cannot collide with real data.
Combining several aggregates over several keys
Multi-column grouping works with any number of aggregates, and each aggregate is computed independently inside every group. This query reports, for each customer and status, the volume and the date range of shipments:
SELECT customer_id,
status,
COUNT(*) AS order_count,
COUNT(shipped_at) AS shipped_count,
SUM(amount) AS total_amount,
AVG(amount) AS avg_amount,
MAX(shipped_at) AS last_shipped
FROM orders
GROUP BY customer_id, status
ORDER BY customer_id, status;Remember the NULL rules from earlier chapters. COUNT(shipped_at) skips orders that were never shipped, AVG(amount) ignores NULL amounts in both the sum and the divisor, and MAX(shipped_at) is NULL for a group where no order shipped.
Filtering and sorting multi-column groups
WHERE still runs before grouping and HAVING runs after it. You can sort by any grouping column or by an aggregate, including an alias in most engines.
SELECT customer_id,
status,
COUNT(*) AS order_count,
SUM(amount) AS total_amount
FROM orders
WHERE amount > 0
GROUP BY customer_id, status
HAVING COUNT(*) >= 2
ORDER BY total_amount DESC, customer_id, status;The last two ORDER BY keys break ties so that the output is deterministic. Without them, two groups with the same total may swap places between runs.
Counting the groups themselves
A common question is "how many distinct (customer, status) combinations exist?" You cannot nest an aggregate directly inside another (COUNT(COUNT(*)) is invalid in standard SQL). Instead, wrap the grouped query in a subquery:
SELECT COUNT(*) AS combination_count
FROM (
SELECT customer_id, status
FROM orders
GROUP BY customer_id, status
) AS combos;Some databases accept COUNT(DISTINCT customer_id, status) (MySQL does), but PostgreSQL and SQL Server do not. The subquery form works everywhere. Note also that multi-column COUNT(DISTINCT ...) in MySQL skips any row where one of the listed columns is NULL, whereas GROUP BY keeps those rows as their own groups. The two approaches can give different counts.
Common mistakes with multiple columns
- Forgetting a column in
GROUP BY. Ifstatusis in theSELECTlist and is not inside an aggregate, it must be inGROUP BY. Strict engines raise an error. Older MySQL configurations withoutONLY_FULL_GROUP_BYreturn an arbitrary value from the group, which produces wrong results without any warning. - Adding a column "just to see it". Putting
order_idor a timestamp intoGROUP BYmakes every group tiny. The aggregates still compute, but they no longer summarize anything. - Grouping by a column that varies in time. Grouping by a full timestamp, when you meant a day, creates one group per distinct instant. Group by an expression such as a date truncated to the day instead. The chapter on grouping by expressions covers this.
- Reading the result at the wrong grain. Summing the
total_amountcolumn across rows of a (customer, status) result is valid forSUM, but averaging theavg_amountcolumn is not. The average of group averages differs from the overall average unless every group has the same size. Recompute fromSUMandCOUNTinstead.
Checking your result
Use two quick checks whenever you change the grain of a query:
- Add up a summable column across the output and compare it with the ungrouped total. For example,
SUM(total_amount)over the grouped result should equalSUM(amount)over the table, provided the sameWHEREfilter applies. For counts, the sum oforder_countshould equal the number of filtered rows. - Look for unexpected NULL keys. A NULL row in the output tells you the source column contains missing values you may want to label or exclude.
SELECT SUM(total_amount) AS grouped_total,
(SELECT SUM(amount) FROM orders) AS table_total
FROM (
SELECT customer_id, status, SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id, status
) AS g;If grouped_total and table_total differ, something filtered or duplicated rows. Because the inner query has no WHERE, they should match exactly.
Exercise
The orders table has 1,000 rows, 50 distinct customerid values, and 4 distinct status values (none NULL). What is the smallest and the largest number of rows that `GROUP BY customerid, status` can return? Then explain what the largest possible value would tell you about the data.
Show answer
The minimum is 50, reached when every customer has orders in only one status (each customer forms exactly one group, and 4 statuses do not force more groups). Strictly, it can also be lower bounded by 50 because every customer appears at least once. The maximum is 200 (50 customers times 4 statuses), reached when every customer has at least one order in every status; the table has 1,000 rows, so 200 combinations is possible. A result of 200 would show that every customer has used every status, so the grain is fully populated.
Exercise
A query returns status and AVG(amount) per (customerid, status). A colleague computes the overall average order amount by averaging the avgamount column. Why is this wrong, and what should they compute instead?
Show answer
Groups with different numbers of orders contribute different weights to the true average, but averaging the avg_amount column gives every group the same weight. They should compute SUM(total amount of all groups) divided by SUM(order counts of all groups), or simply run AVG(amount) over the original table with the same WHERE filter.