Sub topic 4
Grouping rows with `GROUP BY`
Assume you know basic SELECT, FROM, WHERE, and ORDER BY syntax. You should also understand tables, rows, columns, and NULL. This chapter uses an orders table with order_id, customer_id, status, and amount columns.
An aggregate function reduces several input rows to one value. COUNT counts rows, SUM adds values, and AVG calculates an average. Without GROUP BY, the whole table is one group:
SELECT COUNT(*) AS order_count,
SUM(amount) AS total_amount
FROM orders;This query returns one row for the entire table. GROUP BY divides the input rows into groups before the aggregate functions run.
One group for each value
To calculate totals per customer, group by customer_id:
SELECT customer_id,
COUNT(*) AS order_count,
SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id
ORDER BY total_amount DESC;The database performs these steps conceptually:
- Read rows from
orders. - Put rows with the same
customer_idinto one group. - Calculate
COUNT(*)andSUM(amount)separately for each group. - Return one output row per group.
- Sort the result by
total_amount.
If customer 17 has three orders, that customer produces one result row. The row contains 3 for order_count and the sum of those three amounts for total_amount.
A grouping column does not have to be numeric. You can group by a status:
SELECT status,
COUNT(*) AS order_count,
SUM(amount) AS total_amount,
AVG(amount) AS average_amount
FROM orders
GROUP BY status;Each distinct status creates one group. For example, paid, pending, and refunded might produce three rows.
What can appear in the SELECT list?
In a grouped query, every selected expression must be one of these:
- A column or expression listed in
GROUP BY. - An aggregate expression such as
SUM(amount). - In some database systems, an expression functionally dependent on a grouped key.
This query is invalid in standard SQL:
SELECT customer_id, order_id, SUM(amount)
FROM orders
GROUP BY customer_id;A customer can have many order_id values. The group therefore has no single order_id to display. You must either add order_id to the grouping:
SELECT customer_id, order_id, SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id, order_id;or summarize it, perhaps with MIN(order_id) or COUNT(DISTINCT order_id).
The following table shows the difference:
| Query shape | Result |
|---|---|
| `GROUP BY customer_id` | One row per customer |
| `GROUP BY customer_id, status` | One row per customer and status combination |
| No `GROUP BY` | One row for the whole filtered input |
Common checks
When a grouped result looks wrong, check the grouping key first. A hidden difference, such as trailing spaces or different letter case, can create separate groups. Check whether NULL values are expected. All NULL values in a grouping column normally belong to one group.
Also compare the number of result rows with the number of distinct grouping keys:
SELECT COUNT(DISTINCT customer_id) AS expected_groups
FROM orders;This count should usually match the number of customer groups, except when filters or database-specific behavior change the input.
Exercise
Which query returns one row per customer and status pair?
Show answer
SELECT customerid, status, COUNT(*) AS ordercount FROM orders GROUP BY customer_id, status;