MySQL Aggregate Functions
MySQL Aggregate Functions: Summarizing Datasets
MySQL aggregate functions combine values from multiple rows into a single summary result. The five standard SQL aggregate functions are COUNT(), SUM(), AVG(), MIN(), and MAX(), while GROUP_CONCAT() joins group text values into one delimited string.
Core Aggregate Functions at a Glance
| Function | Purpose | Empty Set / All-NULL Result |
|---|---|---|
COUNT(*) |
Count all matching rows | 0 |
COUNT(col) |
Count non-NULL values |
0 |
SUM(col) |
Add numeric values | NULL |
AVG(col) |
Mean of non-NULL numbers |
NULL |
MIN(col) |
Smallest non-NULL value |
NULL |
MAX(col) |
Largest non-NULL value |
NULL |
GROUP_CONCAT(col) |
Join non-NULL strings |
NULL |
Practical SQL Example
This reporting query summarizes customer orders in demo_orders per status in one pass:
SELECT
status,
COUNT(*) AS order_count,
COALESCE(SUM(total_amount), 0.00) AS total_revenue,
ROUND(COALESCE(AVG(total_amount), 0.00), 2) AS avg_order,
MIN(total_amount) AS smallest_order,
MAX(total_amount) AS largest_order
FROM demo_orders
GROUP BY status
HAVING COUNT(*) >= 2
ORDER BY total_revenue DESC;
| status | order_count | total_revenue | avg_order | smallest_order | largest_order |
|---|---|---|---|---|---|
| paid | 85 | 12450.00 | 146.47 | 19.99 | 499.00 |
| pending | 12 | 980.50 | 81.71 | 24.50 | 210.00 |
Common Mistakes and Best Practices
- Respect
ONLY_FULL_GROUP_BY: Every non-aggregated column inSELECTmust appear inGROUP BYso MySQL never picks an arbitrary row value from a group. - Filter Early with
WHERE, Later withHAVING: Narrow down individual rows withWHEREbefore grouping so MySQL aggregates fewer records, then filter group totals withHAVING. - Know
GROUP_CONCAT()Length Limits:GROUP_CONCAT()truncates strings atgroup_concat_max_len(default 1024 bytes); increase the session limit for large lists or format lists in application code. - Handle Empty Filtered Tables: Remember
SUM()andAVG()returnNULLwhen zero rows match, whereasCOUNT()returns0.
Frequently Asked Questions
Can I nest aggregate functions like MAX(SUM(total_amount))?
No, SQL forbids nesting aggregates directly; compute SUM() inside a CTE or subquery first, then apply MAX() in the outer query.
Why do SUM() and AVG() return NULL when zero rows match?
SQL defines arithmetic aggregates over empty groups as NULL (except COUNT, which returns 0); wrap them in COALESCE(..., 0) when needed.
What is the difference between GROUP BY and window functions (OVER)?
GROUP BY collapses rows into one summary row per group, whereas OVER () keeps every individual row while adding the aggregate alongside it.
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.