AVG

The AVG function returns the average value of an expression.

Syntax

-- As an aggregate
AVG( expr )

-- As a window function
AVG (expr) OVER (
  [ PARTITION BY value_expression [, ...] ] [ ORDER BY value_expression [ ASC | DESC ] [ NULLS { FIRST | LAST } ] [, ...] ] [ frame_clause ]
)

Arguments

Parameter

Description

expr

Numeric expression

Returns

Returns DOUBLE except for when the input is NUMERIC, in which case it returns NUMERIC.

Usage Note

  • NULL values are ignored

  • AVG relies on calculating the sum, which can very quickly overflow on large data sets. If the sum is over 231 for example, up-cast to a larger type like BIGINT: AVG(expr :: BIGINT)

Examples

For these examples, assume a table named nba, with the following structure:

CREATE TABLE nba
(
   "Name" TEXT,
   "Team" TEXT,
   "Number" TINYINT,
   "Position" TEXT,
   "Age" TINYINT,
   "Height" TEXT,
   "Weight" REAL,
   "College" TEXT,
   "Salary" FLOAT
 );

Simple Average

SELECT
  AVG("Age")
FROM
  nba;

Output:

avg
---
26

Combine AVG with Other Aggregates

SELECT
  "Age",
  AVG("Salary") as "Average salary",
  COUNT(*) as "Number of players"
FROM
  nba
GROUP BY
  1;

Output:

Age | Average salary | Number of players
----+----------------+------------------
 19 |        1930440 |                 2
 20 |        2725790 |                19
 21 |        2067379 |                19
 22 |        2357963 |                26
 23 |        2034746 |                41
 24 |        3785300 |                47
 25 |        3930867 |                45
 26 |        6866566 |                36
 27 |        6676741 |                41
 28 |        5110188 |                31
 29 |        6224177 |                28
 30 |        7061858 |                31
 31 |        8511396 |                22
 32 |        7716958 |                13
 33 |        3930739 |                14
 34 |        7606030 |                10
 35 |        3461739 |                 9
 36 |        2238119 |                10
 37 |       12777778 |                 4
 38 |        1840041 |                 4
 39 |        2517872 |                 2
 40 |        4666916 |                 3