Lesson

MySQL GROUP BY

10 min reading
Free Course

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 enables ONLY_FULL_GROUP_BY by default. If you select email while grouping only by city, MySQL rejects the query because multiple emails exist per city. Either add email to GROUP BY, wrap it in ANY_VALUE(), or group by the primary key c.id.
  • Remember SQL Clause Execution Order: MySQL evaluates clauses in order: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, and LIMIT. Always filter individual rows in WHERE before grouping begins.
  • Add Indexes on GROUP BY Columns: 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.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum