Overview

The AVG() window function calculates the average (arithmetic mean) of a set of numeric values within a window. This function allows you to compute averages over a set of rows that are related to the current row, such as rows within a partition of ordered set.

Syntax

The syntax for this function is as follows:

AVG(expression) OVER (
  [PARTITION BY partition_expression]
  ORDER BY sort_expression
)

Parameters

  • expression: column or expression that the function operates on (must be of numeric type)

Example

For the needs of this section, we will use a simplified version of the film table from the Pagila database, containing only the title, length and rating columns. The complete schema for the film table can be found on the Pagila database website.

DROP TABLE IF EXISTS film;
CREATE TABLE film (
  title text NOT NULL,
  rating int,
  length int
);
INSERT INTO film(title, length, rating) VALUES
  ('ATTRACTION NEWTON', 83, 5),
  ('CHRISTMAS MOONSHINE', 150, 7),
  ('DANGEROUS UPTOWN', 121, 4),
  ('KILL BROTHERHOOD', 54, 3),
  ('HALLOWEEN NUTS', 47, 5),
  ('HOURS RAGE', 122, 7),
  ('PIANIST OUTFIELD', 136, 7),
  ('PICKUP DRIVING', 77, 3),
  ('INDEPENDENCE HOTEL', 157, 7),
  ('PRIVATE DROP', 106, 4),
  ('SAINTS BRIDE', 125, 3),
  ('FOREVER CANDIDATE', 131, 7),
  ('MILLION ACE', 142, 5),
  ('SLEEPY JAPANESE', 137, 4),
  ('WRATH MILE', 176, 7),
  ('YOUTH KICK', 179, 7),
  ('CLOCKWORK PARADISE', 143, 5);

The query below uses the AVG() function to calculate the rolling average of length as rows are ordered by rating:

SELECT
    rating,
    length,
    AVG(length) OVER (ORDER BY rating) AS RollingAverageLength
FROM film
WHERE length IS NOT NULL
ORDER BY rating;

By executing the above query, we will get the following output:

 rating | length | rollingaveragelength 
--------+--------+----------------------
      3 |     77 |    85.33333333333333
      3 |    125 |    85.33333333333333
      3 |     54 |    85.33333333333333
      4 |    121 |   103.33333333333333
      4 |    106 |   103.33333333333333
      4 |    137 |   103.33333333333333
      5 |     83 |                103.5
      5 |    142 |                103.5
      5 |     47 |                103.5
      5 |    143 |                103.5
      7 |    157 |   122.70588235294117
      7 |    179 |   122.70588235294117
      7 |    176 |   122.70588235294117
      7 |    131 |   122.70588235294117
      7 |    136 |   122.70588235294117
      7 |    122 |   122.70588235294117
      7 |    150 |   122.70588235294117
(17 rows)