AggregateSQL standard

AVG

Calculates the arithmetic mean of values from many rows.

Syntax

AVG(<expression>)

An aggregate function: it adds the values up and divides by their count. NULL counts neither in the sum nor in the count. The result usually has many decimal places, so it's often wrapped in ROUND.

Data for the examples

employees

namedepartmentsalarybonusphone
Emmabackend1200300+44 7700 900123
Liambackend1000NULLNULL
Oliviafrontend1350150+44 7700 900456
Noahfrontend950NULL+44 7700 900789
Sophiadesign1200200NULL

These tables already exist in the sandbox — the examples below use them. Want to try this in your own database? Copy the SQL.

The average salary
SELECT AVG(salary) AS average_salary
FROM employees;
average_salary
1140.0000000000000000
The average salary in each department
SELECT department,
ROUND(AVG(salary)) AS average_salary
FROM employees
GROUP BY department
ORDER BY department;
departmentaverage_salary
backend1100
design1200
frontend1150
The average bonus: with NULL and without
SELECT ROUND(AVG(bonus), 2) AS skip_nulls,
ROUND(AVG(COALESCE(bonus, 0)), 2) AS nulls_as_zero
FROM employees;
skip_nullsnulls_as_zero
216.67130.00

The first divides the sum of bonuses by 3 — only those who have one. The second counts a missing bonus as 0 and divides by 5.

Watch out

NULL isn't counted as zero: the average of 300, NULL and 150 is 225, not 150. If a missing value means zero, write AVG(COALESCE(bonus, 0)).

For integers the result is still fractional, with a pile of zeros: AVG(salary) gives 1140.0000000000000000. Round it: ROUND(AVG(salary), 2).

The average is sensitive to outliers: a single order of 10,000 makes the “average order value” unrealistic. The median shows a typical value better: PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY amount).

Related functions

Learn more in the course