// aggregates reference

SQL AVG function

Averages the non-null values of an expression across a group. AVG ignores NULLs entirely, so the denominator is the count of non-null values, not COUNT(*).

Categoría
Aggregates
Returns
numeric
In this category
3 of 52

Sintaxis

AVG(expression)
AVG(DISTINCT expression)

Each block is a separate form. The support table and the examples show which engine takes which.

Soporte del motor

MotorSupportNotas
SQL Server Sí Supported under this name.
PostgreSQL Sí Supported under this name.
MySQL Sí Supported under this name.
SQLite Sí Supported under this name.
Oracle Sí Supported under this name.

Ejemplos

Any engine

SELECT customer_id, AVG(amount) AS avg_order
FROM orders
GROUP BY customer_id;

SQL Server

SELECT AVG(CAST(duration_seconds AS DECIMAL(10,2))) AS avg_duration
FROM runs;

Conviene saberlo

  • AVG ignores NULLs: a column with values 10, 20 and NULL averages to 15, not 10.
  • On SQL Server, AVG of an int column returns int, truncated: AVG of 1 and 2 is 1. Cast to a decimal type for a real average. PostgreSQL returns numeric, MySQL DECIMAL and SQLite a float, so 1.5 there.
  • AVG(DISTINCT x) averages the distinct values only: 1, 1 and 4 give 2.5, not 2.

Questions about AVG

Does AVG count NULL values?

No. NULLs are excluded from both the sum and the count. To treat NULL as zero, write AVG(COALESCE(x, 0)), but think first whether that is really the average you mean.

Why is my AVG of whole numbers a whole number?

Integer input gives integer output on SQL Server, with the fraction dropped. CAST the column to DECIMAL, or average x * 1.0. PostgreSQL, MySQL, SQLite and Oracle already return a fractional result.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.