Part 3 of 5 · 1 min read
Grouping with GROUP BY
Computing one aggregate value per group, instead of one for the whole table.
Think of sorting a pile of receipts into one stack per cashier, then totaling each stack separately instead of totaling everything together.
In plain words: GROUP BY splits a table's rows into groups sharing the same value in one or more columns. An aggregate function listed alongside GROUP BY then computes once per group, not once for the whole table. Every non-aggregated column in the SELECT list must appear in the GROUP BY clause, since otherwise the database would not know which row's value to show for a group containing many rows.
A worked example. The number of orders placed by each customer.
The key lines.
SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id;
GROUP BY
GROUP BY splits rows into groups sharing the same value in the given columns, so an aggregate function computes once per group rather than once overall.
Example: GROUP BY customer_id with COUNT(*) produces one row per customer, each showing that customer's own order count.