Sub topic 4
Grouping rows with GROUP BY
This chapter assumes you can write SELECT ... FROM ... WHERE ... ORDER BY queries and that you know the aggregate functions COUNT, SUM, AVG, MIN and MAX from the earlier chapters. You should also know that NULL means "missing value". Joins are not needed here.
What GROUP BY does
An aggregate function without GROUP BY summarizes the whole table and returns one row. GROUP BY splits the rows into groups first. The database then computes each aggregate once per group and returns one output row per group.
A group is a set of rows that share the same value in the grouping column. Every row belongs to exactly one group.
A sample table
The examples below use this small table. The statements run on PostgreSQL, MySQL and SQLite.
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER,
amount DECIMAL(10,2) NOT NULL
);
INSERT INTO orders (order_id, customer_id, amount) VALUES
(1, 101, 250.00),
(2, 102, 80.00),
(3, 101, 120.00),
(4, 103, 350.00),
(5, 102, 60.00),
(6, 101, 30.00),
(7, NULL, 15.00);Order 7 has no customer. That row is deliberate, because it shows how NULL behaves in grouping.
Your first grouped query
This query reports order count and total per customer, largest total first.
SELECT customer_id,
COUNT(*) AS order_count,
SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id
ORDER BY total_amount DESC;The result looks like this. Number formatting differs between database systems.
| customer_id | order_count | total_amount |
|---|---|---|
| 101 | 3 | 400.00 |
| 103 | 1 | 350.00 |
| 102 | 2 | 140.00 |
| NULL | 1 | 15.00 |
The seven input rows became four output rows. One row exists for each distinct value of customer_id, including NULL.
How the database forms groups
You do not control how the database builds the groups, but knowing the two usual strategies explains some behavior you will see.
- Hash aggregation. The database keeps a hash table keyed by the grouping value. For each row it finds the entry for that key and updates the running aggregates, such as a count and a sum. The output order is arbitrary.
- Sort aggregation. The database sorts the rows by the grouping columns, or reads them from an index that is already sorted. It then walks through them and emits a result each time the key changes. The output tends to come out sorted, but you must not rely on that.
Because the strategy is the optimizer's choice, a grouped query has no guaranteed row order. If the order matters, add ORDER BY. The query above uses ORDER BY total_amount DESC for this reason.
Groups and NULL
GROUP BY treats all NULLs as equal, so they land in one group. This differs from a comparison such as customer_id = customer_id, which is not true for NULL. In the result above, order 7 forms its own group with customer_id NULL.
This has a practical consequence. If a column can be NULL, you will get a NULL row in the output. Decide whether that row is wanted. You can drop it with WHERE customer_id IS NOT NULL, or label it for display:
SELECT COALESCE(CAST(customer_id AS VARCHAR(20)), 'unknown') AS customer,
COUNT(*) AS order_count
FROM orders
GROUP BY customer_id;The query still groups by the raw column. COALESCE only changes the label in the output. MySQL does not accept VARCHAR in CAST; use CHAR there instead.
GROUP BY without aggregates
You can use GROUP BY with no aggregate function in the select list. The query then returns each distinct value once:
SELECT customer_id
FROM orders
GROUP BY customer_id;This returns the same rows as SELECT DISTINCT customer_id FROM orders. Use DISTINCT when you only want unique values, because it states the intent more clearly. Use GROUP BY when you need aggregates as well.
Grouping by an alias or a position
The GROUP BY clause is normally written with column names or expressions. Some databases also let you refer to the select list by alias or by position:
SELECT customer_id AS cust,
COUNT(*) AS order_count
FROM orders
GROUP BY 1;PostgreSQL, MySQL and SQLite accept GROUP BY 1 (the first select item) and, in most cases, an output alias. SQL Server does not accept either. Positions break silently when someone reorders the select list, so prefer column names in code that will be maintained.
Edge cases
An empty input
Aggregates behave differently on empty input depending on whether GROUP BY is present.
-- Returns one row: order_count = 0, total_amount = NULL
SELECT COUNT(*) AS order_count, SUM(amount) AS total_amount
FROM orders
WHERE amount > 10000;
-- Returns zero rows
SELECT customer_id, COUNT(*) AS order_count
FROM orders
WHERE amount > 10000
GROUP BY customer_id;Without GROUP BY the whole input is one group, and a group always produces a row, even when it is empty. With GROUP BY there are no groups to report, so there are no rows. If a report must show a zero for a missing group, you need a different approach, such as a LEFT JOIN from a table that lists every group. The joins chapter covers that.
Case, spaces and types
Groups are formed by the database's equality rules for the column's type. For text columns the collation decides whether 'Paid' and 'paid' are the same value. MySQL's default collations are case-insensitive, so they merge those two. PostgreSQL's defaults are case-sensitive, so they produce two groups. Trailing spaces and inconsistent spelling also create separate groups. When a result shows two groups that look identical, check the raw values with a query like SELECT DISTINCT status, LENGTH(status) FROM orders.
Many groups
The number of output rows equals the number of distinct grouping values. Grouping by a near-unique column such as order_id gives one group per row, which does no summarizing. If the group count is close to the row count, ask whether you chose the right column.
A first look at the select list rule
In a grouped query, each item in the select list must be either an aggregate or a value that is the same for every row in a group. This query fails in standard SQL:
SELECT customer_id, amount, COUNT(*)
FROM orders
GROUP BY customer_id;A customer has several amounts, so the database cannot pick one for the output row. PostgreSQL reports column "orders.amount" must appear in the GROUP BY clause or be used in an aggregate function. The next chapters cover the rule in full. For now, remember that GROUP BY decides what one output row means.
Checking your grouped result
Two quick checks catch most mistakes:
- The group counts should add up.
SUM(order_count)across all groups must equalCOUNT(*)for the table, here 7. - The group totals should add up. The sum of
total_amountacross groups must equal the plainSUM(amount), here 905.00.
The sample output passes both checks: 3 + 1 + 2 + 1 is 7, and 400 + 350 + 140 + 15 is 905. If a check fails, the cause is usually a filter you forgot about, or a join that duplicated rows.
Exercise
A table tickets(ticket_id, team, closed_at) holds 40 rows, and 5 of them have team set to NULL. You run SELECT team, COUNT(*) FROM tickets GROUP BY team, and the table has 4 distinct non-NULL teams. How many rows does the result have, and what does the row for NULL show?
Show answer
The result has 5 rows: one per non-NULL team plus one group for NULL, because GROUP BY puts all NULLs together. The NULL row shows a count of 5.
Exercise
What does SELECT COUNT(*), SUM(amount) FROM orders WHERE amount > 10000 return on the sample table, and what does the same query return if you add GROUP BY customer_id?
Show answer
Without GROUP BY it returns one row with 0 and NULL, because the empty input is a single group. With GROUP BY customer_id it returns zero rows, because no rows survive the WHERE clause and so no groups exist.
Exercise
Write a query that returns each distinct customer_id from orders along with the largest single amount that customer has ordered, sorted by that amount from high to low.
Show answer
SELECT customerid, MAX(amount) AS largest FROM orders GROUP BY customerid ORDER BY largest DESC;