What GROUP BY and INNER JOIN do together
An INNER JOIN pairs rows from two tables when a condition matches. GROUP BY then collects those pairs into groups, and an aggregate function such as COUNT(), SUM() or AVG() works out one value for each group. The result is one row per customer instead of one row per order.
The join always runs before the grouping. Rows without a match are dropped by the INNER JOIN before GROUP BY sees them, and that is the detail that often surprises people.
Beginners who ask “Is SQL hard to learn?” often find that joins and GROUP BY are where it starts to click.
Sample tables
The examples use two small tables. Each customer can have many orders, and each order points back to one customer through customer_id.
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT NOT NULL,
order_total DECIMAL(10, 2) NOT NULL,
FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
);
INSERT INTO customers (customer_id, name) VALUES
(1, 'Ana'),
(2, 'Ben'),
(3, 'Chen');
INSERT INTO orders (order_id, customer_id, order_total) VALUES
(101, 1, 25.00),
(102, 1, 40.00),
(103, 2, 15.50);
In orders, customer_id is a foreign key that points to customers. If the terms primary key and foreign key are new to you, “What is a PK and FK?” is a good place to start.
Total orders per customer
SELECT c.name,
COUNT(o.order_id) AS order_count,
SUM(o.order_total) AS total_spent
FROM customers AS c
INNER JOIN orders AS o
ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name
ORDER BY total_spent DESC;
The result has two rows:
| name | order_count | total_spent |
|---|---|---|
| Ana | 2 | 65.00 |
| Ben | 1 | 15.50 |
Ana has two orders, 25.00 and 40.00, for a total of 65.00. Chen has no orders, so the INNER JOIN removes that row before grouping starts.
Listing c.name in GROUP BY as well as in the select list keeps the query valid under MySQL’s default settings. The section on selecting columns that are not grouped explains why.
The order of clauses
You write a query as SELECT, FROM, JOIN, WHERE, GROUP BY, HAVING, ORDER BY and LIMIT. The database works through the steps in a different sequence:
- FROM and JOIN combine the tables and keep the matching rows.
- WHERE filters individual rows.
- GROUP BY collects the remaining rows into groups.
- HAVING filters the groups.
- SELECT chooses the output columns and expressions.
- ORDER BY sorts the result, and LIMIT trims it last.
This is the logical order. The optimizer can run the steps differently inside, but the result matches this sequence.
A question many learners have is “Which goes first, GROUP BY or ORDER BY?” GROUP BY does, and ORDER BY comes near the end.
Because WHERE runs before grouping, it can’t use aggregate functions such as SUM(). HAVING runs after grouping, so it can. To keep only customers whose orders total more than 20, add a HAVING clause:
SELECT c.name,
COUNT(o.order_id) AS order_count,
SUM(o.order_total) AS total_spent
FROM customers AS c
INNER JOIN orders AS o
ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name
HAVING SUM(o.order_total) > 20
ORDER BY total_spent DESC;
Only Ana’s row remains, because Ben’s total of 15.50 doesn’t pass the test.
Keeping customers with no orders
To keep Chen in the output, switch to a LEFT JOIN. A customer with no match still gets a row, and the columns from orders are NULL in that row.
SELECT c.name,
COUNT(o.order_id) AS order_count,
COALESCE(SUM(o.order_total), 0.00) AS total_spent
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name
ORDER BY c.name;
Chen now appears with 0 orders and a total of 0.00. Two details matter here. COUNT(o.order_id) counts only non-NULL values, so Chen’s NULL order ID gives 0. COUNT(*) counts the row regardless, so it would return 1. COALESCE() replaces the NULL from SUM() with 0.00.
Whether to use an INNER JOIN or a LEFT JOIN depends on whether rows without a match should appear. “When to use left, right, or inner join?” looks at that choice in more depth.
Selecting columns that are not grouped
Every column in the SELECT list must either appear in GROUP BY or sit inside an aggregate function. MySQL enforces this when the ONLY_FULL_GROUP_BY mode is on, which is the default. Breaking the rule causes error 1055:
-- Error 1055: each customer has several order totals
SELECT c.name, o.order_total, COUNT(o.order_id)
FROM customers AS c
INNER JOIN orders AS o
ON o.customer_id = c.customer_id
GROUP BY c.name;
Ana has two different order totals, so MySQL can’t pick one to show for her group. You have two ways to fix this. You can wrap the column in an aggregate, such as MAX(o.order_total), or add it to GROUP BY, which changes the grouping so each group holds a single total.
Grouping by a primary key, such as c.customer_id, also lets MySQL accept other columns from that same table, because each group holds one customer. ANY_VALUE() silences the error as well, but MySQL then picks any one value from each group. Use it only when the values are the same within a group.
Sorting the grouped results
MySQL 8.0 doesn’t sort the output of GROUP BY on its own. Older versions often returned groups in sorted order, so a query could look sorted without an ORDER BY. The GROUP BY … DESC form of sorting was also removed in MySQL 8.0.13. Add an ORDER BY whenever the order matters.
Common mistakes
- Leaving out the ON condition. MySQL then pairs every row from one table with every row from the other. The result is a Cartesian product, with many rows that mean nothing and wrong totals.
- Summing across extra joins. If you join orders to a table of order items, each order appears once per item, so SUM(o.order_total) counts the same order several times. Aggregate before the extra join, or sum the value from the table where it lives.
- Mixing up COUNT(*) and COUNT(column). After a LEFT JOIN, COUNT(*) counts unmatched rows too. Count a column from the joined table when you want only real matches.