TExcelTAD
Home › MySQL › MySQL GROUP BY

MySQL GROUP BY

Aggregate functions on their own summarise all rows into one. GROUP BY splits the rows into groups with the same value in one or more columns and computes the aggregates per group: orders per status, revenue per product, average salary per job title.

sql
SELECT group_column, AGGREGATE(expr)
FROM table_name
WHERE row_condition
GROUP BY group_column
ORDER BY ...;
mysql · try it yourself
SELECT status, COUNT(*) AS orders
FROM orders
GROUP BY status
ORDER BY orders DESC, status;
+------------+--------+
| status     | orders |
+------------+--------+
| delivered  |     15 |
| processing |      3 |
| cancelled  |      2 |
| shipped    |      2 |
+------------+--------+

The result has one row per distinct status. Each aggregate in the select list is computed over the rows of that group only.

The golden rule

Every column in the select list must either be in the GROUP BY or be inside an aggregate function. Otherwise the question has no single answer: if you group orders by status, which of the fifteen delivered orders' order_date should the "delivered" row show?

sql
SELECT status, order_date, COUNT(*) FROM orders GROUP BY status;
-- MySQL 8: ERROR 1055 (42000): Expression #2 of SELECT list is not in GROUP BY clause
--          and contains nonaggregated column 'shop.orders.order_date' ...

MySQL 8 enforces this rule with its default ONLY_FULL_GROUP_BY SQL mode. MariaDB (and MySQL before 5.7) doesn't enable that mode by default and silently returns the value from some row of the group. Write queries that follow the rule and they behave the same everywhere. If you really want an arbitrary value, say so with ANY_VALUE(order_date) in MySQL, or ask for a specific one with MIN(order_date).

Grouping with joins

Group after joining to report on related tables. Revenue per category:

mysql · try it yourself
SELECT cat.name AS category,
       SUM(d.quantity) AS units,
       ROUND(SUM(d.quantity * d.unit_price * (1 - d.discount)), 2) AS revenue
FROM order_details AS d
JOIN products   AS p   ON p.product_id = d.product_id
JOIN categories AS cat ON cat.category_id = p.category_id
GROUP BY cat.category_id, cat.name
ORDER BY revenue DESC;
+-----------+-------+---------+
| category  | units | revenue |
+-----------+-------+---------+
| Beverages |    23 |  224.31 |
| Dairy     |    25 |   79.86 |
| Bakery    |    23 |   79.20 |
| Snacks    |    26 |   69.64 |
| Household |     9 |   58.51 |
| Produce   |    21 |   44.43 |
+-----------+-------+---------+

Grouping by cat.category_id (the key) as well as cat.name is a good habit: two categories might share a name, but never an id.

Several grouping columns

Group by two columns to get one row per combination. Orders per employee and status:

mysql · try it yourself
SELECT e.first_name AS employee, o.status, COUNT(*) AS orders
FROM orders AS o
JOIN employees AS e ON e.employee_id = o.employee_id
GROUP BY e.employee_id, e.first_name, o.status
ORDER BY e.first_name, o.status;
+----------+------------+--------+
| employee | status     | orders |
+----------+------------+--------+
| Linus    | cancelled  |      1 |
| Linus    | delivered  |      5 |
| Linus    | processing |      1 |
| Linus    | shipped    |      1 |
| Maya     | delivered  |      6 |
| Maya     | processing |      2 |
| Omar     | cancelled  |      1 |
| Omar     | delivered  |      4 |
| Omar     | shipped    |      1 |
+----------+------------+--------+

Grouping by an expression

You can group by any expression, for example the month of a date:

mysql · try it yourself
SELECT DATE_FORMAT(order_date, '%Y-%m') AS month, COUNT(*) AS orders
FROM orders
GROUP BY month
ORDER BY month;
+---------+--------+
| month   | orders |
+---------+--------+
| 2025-01 |      4 |
| 2025-02 |      4 |
| 2025-03 |      4 |
| 2025-04 |      4 |
| 2025-05 |      4 |
| 2025-06 |      2 |
+---------+--------+

MySQL lets you use the select-list alias (month) in GROUP BY. Standard SQL would require repeating the expression.

Always add ORDER BY

Old MySQL versions (and MariaDB to this day) return grouped rows sorted by the grouping columns. MySQL 8 does not: the groups come out in whatever order the server finds convenient. If the order matters, write ORDER BY.

GROUP_CONCAT and WITH ROLLUP

GROUP_CONCAT is a MySQL aggregate that joins the values of a group into one string. WITH ROLLUP adds a super-aggregate row (with NULL in the grouping column) for the totals:

mysql · try it yourself
SELECT category_id,
       COUNT(*) AS products,
       GROUP_CONCAT(product_id ORDER BY product_id SEPARATOR ',') AS ids
FROM products
WHERE category_id <= 3
GROUP BY category_id WITH ROLLUP;
+-------------+----------+----------------------------+
| category_id | products | ids                        |
+-------------+----------+----------------------------+
|           1 |        4 | 1,2,3,4                    |
|           2 |        4 | 5,6,7,8                    |
|           3 |        4 | 9,10,11,12                 |
|        NULL |       12 | 1,2,3,4,5,6,7,8,9,10,11,12 |
+-------------+----------+----------------------------+

Test yourself

With ONLY_FULL_GROUP_BY, which column may appear in the SELECT list of ... GROUP BY status?

  1. Any column
  2. status, and other columns only inside aggregates
  3. Only aggregates
  4. Only primary keys

Are the rows of a GROUP BY query sorted by the grouping column in MySQL 8?

  1. Yes, always
  2. No, add ORDER BY if you need an order
  3. Only with DESC
  4. Only for text columns

What does GROUP_CONCAT do?

  1. Concatenates two columns
  2. Joins the values of a group into one string
  3. Groups by several columns
  4. Counts distinct strings