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(*).
- Category
- Aggregates
- Returns
numeric- In this category
- 3 of 52
Syntax
AVG(expression)
AVG(DISTINCT expression)
Each block is a separate form. The support table and the examples show which engine takes which.
Engine support
| Engine | Support | Notes |
|---|---|---|
| SQL Server | Yes | Supported under this name. |
| PostgreSQL | Yes | Supported under this name. |
| MySQL | Yes | Supported under this name. |
| SQLite | Yes | Supported under this name. |
| Oracle | Yes | Supported under this name. |
Examples
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;
Good to know
- 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.
Related on SQLly
- Moving average Snippet
- Profile a column: min, max, distinct Snippet
- Median per group Snippet
- Find outliers with z-scores Snippet
- SQL aggregation & HAVING interview questions Interview questions
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.