MySQL AVG() Function
MySQL AVG() Function: Computing Averages Across Rows
The AVG() aggregate function calculates the arithmetic mean of non-NULL values in a column or expression. By default, it sums every non-NULL row in the group and divides by the count of non-NULL rows.
You can pair AVG() with GROUP BY to compute department salaries, category prices, or order totals per customer. Adding AVG(DISTINCT col) averages only unique values instead of counting duplicates multiple times.
Syntax
AVG([DISTINCT] expr)
DISTINCT: Optional keyword that removes duplicate values before averaging.expr: Numeric column or expression to average.
Practical Example
Suppose demo_employees stores staff salaries and optional annual bonuses by department. Notice how AVG(bonus) only divides by employees who have a non-NULL bonus, while AVG(COALESCE(bonus, 0)) spreads the total across everyone.
SELECT
department,
COUNT(*) AS headcount,
ROUND(AVG(salary), 2) AS avg_salary,
ROUND(AVG(bonus), 2) AS avg_non_null_bonus,
ROUND(AVG(COALESCE(bonus, 0)), 2) AS avg_all_staff_bonus
FROM demo_employees
GROUP BY department;
| department | headcount | avg_salary | avg_non_null_bonus | avg_all_staff_bonus |
|---|---|---|---|---|
| Engineering | 4 | 98500.00 | 8000.00 | 4000.00 |
| Sales | 3 | 64000.00 | 5500.00 | 5500.00 |
| Support | 2 | 52000.00 | NULL | 0.00 |
In Support, nobody received a bonus (NULL for both rows), so AVG(bonus) returns NULL. In Engineering, only two of four engineers had bonuses, changing the denominator from 4 to 2.
Common Mistakes & NULL Behavior
- NULLs are ignored, not zeroed:
AVG(col)skipsNULLrows completely. Ifcolhas values(10, NULL, 20),AVG(col)returns15, not10. - All NULL or empty set: If zero rows match your
WHEREclause or every value in the group isNULL,AVG()returnsNULLrather than0. - Filtering aggregates in WHERE: Writing
WHERE AVG(salary) > 70000throws an invalid group use error. Put aggregate filters in aHAVINGclause instead.
Frequently Asked Questions
What data type does MySQL AVG() return?
For exact numeric columns (INT, DECIMAL), AVG() returns a DECIMAL value with extra fractional digits. For floating-point columns (FLOAT, DOUBLE), it returns DOUBLE.
Can I use AVG() as a window function?
Yes, in MySQL 8.0+ you can write AVG(salary) OVER (PARTITION BY department) to keep individual employee rows alongside their department average.
How does AVG(DISTINCT price) behave?
It removes duplicate numbers before summing and counting. For values (10, 10, 20), AVG(DISTINCT price) averages 10 and 20, returning 15.
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.