AVG
Overview
The AVG()
function lets you calculate the average value of records.
The input and return types we support can be seen in the table below.
💡Special cases: Returns NaN if the input contains a NaN.
Examples
In this example, we will use an orders table that stores details of the purchase transactions:
The above query will show the following table:
#Case 1: AVG()
with a single expression
In the first example, we want to calculate the average amount of all orders that customers have paid:
It will return the following output:
#Case 2: AVG()
with a GROUP BY
clause
The following example uses the AVG()
function and GROUP BY
clause to calculate the average amount paid by each customer:
-
First, the
GROUP BY
clause divides orders into groups based on customers -
Then, the
AVG
function is applied to each group.
It will display the output as shown below:
💡 You can use the cast operator like::NUMERIC(10,2)
to add two decimal numbers after the comma:
The result will trim and round two numbers after the comma: