MySQL GROUP BY
MySQL GROUP BY: Aggregating Rows by Category
The MySQL GROUP BY clause groups rows that share identical values in one or more columns into summary rows. You pair GROUP BY with aggregate functions like COUNT(), SUM(), AVG(), MIN(), and MAX() to build metrics per customer, day, or category.
Basic Syntax
List every non-aggregated SELECT column inside GROUP BY:
SELECT
group_column,
COUNT(*) AS total_rows,
SUM(numeric_column) AS total_sum
FROM table_name
WHERE row_filter
GROUP BY group_column
ORDER BY total_sum DESC;
Practical SQL Example
This query groups demo_orders by both customer_id and status so you see each customer's order count and spend per status:
SELECT
customer_id,
status,
COUNT(*) AS order_count,
SUM(total_amount) AS status_total
FROM demo_orders
WHERE created_at >= '2026-01-01'
GROUP BY customer_id, status
ORDER BY customer_id ASC, status_total DESC;
| customer_id | status | order_count | status_total |
|---|---|---|---|
| 101 | paid | 4 | 645.00 |
| 101 | pending | 1 | 49.00 |
| 104 | paid | 2 | 290.50 |
Common Mistakes and Best Practices
- Satisfy
ONLY_FULL_GROUP_BY: MySQL 8 enablesONLY_FULL_GROUP_BYby default. If you selectemailwhile grouping only bycity, MySQL rejects the query because multiple emails exist per city. Either addemailtoGROUP BY, wrap it inANY_VALUE(), or group by the primary keyc.id. - Remember SQL Clause Execution Order: MySQL evaluates clauses in order:
FROM,WHERE,GROUP BY,HAVING,SELECT,ORDER BY, andLIMIT. Always filter individual rows inWHEREbefore grouping begins. - Add Indexes on
GROUP BYColumns: Indexing foreign keys or status columns helps MySQL scan groups in order without building large temporary sort tables.
Frequently Asked Questions
How does GROUP BY handle NULL values?
MySQL puts all rows where the grouping column is NULL together into one single NULL group.
Can I group by a calculated expression or SELECT alias?
Yes, MySQL lets you group by expressions like DATE(created_at) or by a column alias defined in SELECT.
When should I use GROUP BY instead of SELECT DISTINCT?
Use GROUP BY whenever you need aggregate calculations (COUNT, SUM, AVG), and SELECT DISTINCT when you only want unique values.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.