GROUP BY, COUNT, SUM and HAVING in MySQL

Intermediate  Nov 3, 2026

Turn many rows into summaries: totals, averages and counts per group.

GROUP BY, COUNT, SUM and HAVING in MySQL
The steps of this tutorial at a glance.
The steps of this tutorial at a glance.

Sample data

CREATE TABLE sales (id INT AUTO_INCREMENT PRIMARY KEY, region VARCHAR(20), amount DECIMAL(8,2), sold_on DATE);
INSERT INTO sales (region, amount, sold_on) VALUES
 ('north', 100, '2026-01-05'), ('north', 250, '2026-02-10'),
 ('south', 80,  '2026-01-20'), ('south', 40,  '2026-03-02'), ('east', 500, '2026-03-15');
The table described by the SQL above.
The table described by the SQL above.
How the code in this section fits into the page.
How the code in this section fits into the page.

Aggregate functions

SELECT COUNT(*) AS orders, SUM(amount) AS total, AVG(amount) AS average,
       MIN(amount) AS smallest, MAX(amount) AS largest
FROM sales;

One result per group

SELECT region, COUNT(*) AS orders, SUM(amount) AS total
FROM sales
GROUP BY region
ORDER BY total DESC;

Filter the groups with HAVING

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

SELECT region, SUM(amount) AS total
FROM sales
GROUP BY region
HAVING SUM(amount) > 200;

Group by month

SELECT DATE_FORMAT(sold_on, '%Y-%m') AS month, SUM(amount) AS total
FROM sales
GROUP BY month
ORDER BY month;

Tip

Every column in SELECT must either be in GROUP BY or inside an aggregate function.

More tutorials