The MySQL AVG() aggregate function calculates the arithmetic mean of all non-NULL numeric values in a column or expression. It divides the sum of non-NULL entries by the count of non-NULL entries.
SELECT AVG(column_name) AS average_value
FROM table_name
WHERE condition;
Like SUM(), AVG() returns NULL when no rows match or when every value in the column is NULL.
This query computes the average product price per category in demo_products and formats it to two decimal places with ROUND():
SELECT
category,
COUNT(*) AS product_count,
ROUND(AVG(price), 2) AS avg_price
FROM demo_products
WHERE is_active = 1
GROUP BY category
ORDER BY avg_price DESC;
| category | product_count | avg_price |
|---|---|---|
| Furniture | 6 | 284.50 |
| Electronics | 14 | 92.35 |
You can also compare individual rows against the table average using a scalar subquery:
SELECT id, product_name, price
FROM demo_products
WHERE price > (SELECT AVG(price) FROM demo_products);
NULL Exclusion in Averages: AVG(rating) divides by the number of rated rows, ignoring unrated NULL rows. If unrated rows should count as zero in your business rule, write AVG(COALESCE(rating, 0)).ROUND(): AVG() on DECIMAL(10, 2) returns extra decimal digits (e.g., 92.357143), so wrap it in ROUND(AVG(price), 2) for clean financial summaries.SUM(total) / COUNT(*) from raw rows.AVG() treat NULL as zero?No, AVG() ignores NULL rows completely in both the numerator and denominator unless you explicitly wrap the column in COALESCE(col, 0).
AVG(DISTINCT price)?Yes, AVG(DISTINCT price) averages each unique price once, discarding duplicate values before dividing.
Put (SELECT AVG(col) FROM table_name) in a WHERE col > ... filter or use a window function AVG(col) OVER ().
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.