SkillByAIOpen interactive version →

Lesson 16 / 30

GROUP BY

Aggregate within groups using GROUP BY, and follow MySQL's rules about non-aggregated columns.

Grouping rows

GROUP BY buckets rows sharing a value, then aggregate functions run per bucket.

SELECT customer_id, COUNT(*) AS orders, SUM(amount) AS total
FROM orders
GROUP BY customer_id;

Output:

customer_id | orders | total
1           | 2      | 3200.00
2           | 1      | 1300.00

Non-aggregated columns

Every column in SELECT that isn't inside an aggregate function must appear in GROUP BY — MySQL enforces this in strict mode.