MySQL Aggregates, GROUP BY, HAVING and WITH ROLLUP

MySQL 60 min min read Updated: Nov 27, 2026 Beginner
MySQL Aggregates, GROUP BY, HAVING and WITH ROLLUP
Beginner Topic 1 of 3

Aggregate Functions

sql SELECT COUNT(*) AS products, SUM(stock) AS units, ROUND(AVG(price), 2) AS avg_price, MIN(price) AS cheapest, MAX(price) AS dearest FROM products;

Result:

productsunitsavg_pricecheapestdearest
8980251.063.50899.00

COUNT(*) counts rows. COUNT(email) counts rows where email is not NULL, and COUNT(DISTINCT city) counts different cities:

sql SELECT COUNT(*) AS all_rows, COUNT(email) AS with_email, COUNT(DISTINCT city) AS cities FROM customers;

Result:

all_rowswith_emailcities
654

GROUP BY

sql SELECT category, COUNT(*) AS products, ROUND(AVG(price), 2) AS avg_price FROM products GROUP BY category ORDER BY category;

Result:

categoryproductsavg_price
Electronics3525.67
Furniture3141.00
Stationery24.25

HAVING Filters Groups

WHERE filters rows before grouping. HAVING filters groups after grouping:

sql SELECT customer_id, COUNT(*) AS orders FROM orders WHERE status <> 'cancelled' GROUP BY customer_id HAVING COUNT(*) >= 2 ORDER BY customer_id;

Result:

customer_idorders
13
22
32

ONLY_FULL_GROUP_BY

MySQL 5.7 and 8.0 enable the SQL mode ONLY_FULL_GROUP_BY, so a selected column must be grouped or aggregated:

sql SELECT category, name, COUNT(*) FROM products GROUP BY category;
Error

ERROR 1055: Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'shop.products.name' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

Fix it by grouping the column, aggregating it, or picking one with ANY_VALUE() when you do not care which row:

sql SELECT category, ANY_VALUE(name) IS NOT NULL AS has_name, COUNT(*) AS n FROM products GROUP BY category ORDER BY category;

Result:

categoryhas_namen
Electronics13
Furniture13
Stationery12
Do not turn the mode off Older tutorials tell you to remove ONLY_FULL_GROUP_BY. Then MySQL returns an arbitrary row's value for the unlisted column, which is a silent bug.

GROUP_CONCAT: A List in One Cell

sql SELECT category, GROUP_CONCAT(name ORDER BY name SEPARATOR ', ') AS product_names FROM products GROUP BY category ORDER BY category;

Result:

categoryproduct_names
ElectronicsHeadphones, Laptop, Phone
FurnitureChair, Desk, Lamp
StationeryNotebook, Pen Pack

The result is cut at group_concat_max_len (1024 bytes by default). Raise it with SET SESSION group_concat_max_len = 100000; for long lists.

Grouping by Date Parts

sql SELECT DATE_FORMAT(order_date, '%Y-%m') AS month, COUNT(*) AS orders FROM orders GROUP BY DATE_FORMAT(order_date, '%Y-%m') ORDER BY month;

Result:

monthorders
2025-011
2025-022
2025-032
2025-042
2025-052
2025-061

WITH ROLLUP: Subtotals and a Grand Total

sql SELECT category, COUNT(*) AS products, SUM(stock) AS units FROM products GROUP BY category WITH ROLLUP;

Result:

categoryproductsunits
Electronics3145
Furniture335
Stationery2800
NULL8980

The extra last row, with category NULL, is the grand total. Use GROUPING() (MySQL 8.0.1+) to tell a rollup NULL from a real NULL:

sql SELECT IF(GROUPING(category), 'ALL CATEGORIES', category) AS category, COUNT(*) AS products FROM products GROUP BY category WITH ROLLUP;

Result:

categoryproducts
Electronics3
Furniture3
Stationery2
ALL CATEGORIES8
Syntax differs from other databases MySQL writes GROUP BY a, b WITH ROLLUP. PostgreSQL and SQL Server use ROLLUP(a, b).

Order of Work

  1. FROM and JOIN: build the rows
  2. WHERE: remove rows
  3. GROUP BY: make groups
  4. HAVING: remove groups
  5. SELECT: compute columns and aliases
  6. ORDER BY and LIMIT

Common Beginner Mistakes

MistakeWhat happensFix
Selecting a column not in GROUP BYError 1055Group it, aggregate it or use ANY_VALUE()
Aggregates in WHEREErrorUse HAVING
COUNT(col) expecting all rowsNULLs skippedUse COUNT(*)
GROUP_CONCAT truncated silentlyMissing itemsRaise group_concat_max_len
Disabling ONLY_FULL_GROUP_BYRandom valuesKeep it on

Practice

  1. Count orders per status.
  2. List customers with total spend above 500, using a join and HAVING.
  3. Show each city with a GROUP_CONCAT of customer names.
  4. Add WITH ROLLUP to the per-category report.

Conclusion

Aggregates summarize, GROUP BY makes groups, HAVING filters them, GROUP_CONCAT builds lists, and WITH ROLLUP adds subtotals. Keep ONLY_FULL_GROUP_BY on.

Quick Summary: COUNT, SUM, AVG, GROUP BY, HAVING, ONLY_FULL_GROUP_BY, GROUP_CONCAT, WITH ROLLUP.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators