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.
ℹ️ If the input type is 32-bit, then the result will be 64-bit.
💡Special cases: Returns NaN if the input contains a NaN.
In this example, we will use an orders table that stores details of the purchase transactions:
The above query will show the following table:
In the first example, we want to calculate the average amount of all orders that customers have paid:
It will return the following output:
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: