MySQL AVG Function

MySQL AVG is one of the Aggregate Functions, which is useful to calculate the average of total rows (or records) selected by the SELECT Statement. For example, If you want to find the Average Sales in your Area or find the Average Cost of laptops present in your Store, then you can use this one.

Syntax

The basic syntax of the AVG Function is as shown below:

SELECT AVG([Column_Name])
FROM [Source]

For finding the Average with an example, we are going to use the below-shown data

Source Table 1

AVG Example

The Avg function in MySQL returns the average of total records present in the specified column. For example, The following query calculates the average of the total number of records present in the Yearly_Income column from the customerdetails table.

SELECT AVG(Yearly_Income) AS `Average Income`
FROM customerdetails;
Calculating Average of whole table 1

MySQL AVG Function Group By Example

In general, we use it to check for Average product price belonging to a particular color or category, etc. In this situation, we can use Group By Clause to group the products by color or category. Next, we use the Average Function to find the average of each group. Let us see the Aggregate Function Example.

USE company;
SELECT  Education,
        AVG(Yearly_Income)
FROM customerdetails
GROUP BY Education;

The above query group the Customers by their education. And then finds the average income of each group (education qualification)

MySQL AVG Function Group By Example 2

AVG Distinct Example

It allows you to use the DISTINCT keyword along with the AVG function in the SELECT Statement. The distinct keyword along with AVG calculates the average of the Unique number of records present in the table.

TIP: In MySQL, DISTINCT Keyword removes the Duplicates from the specified SELECT Statement column Name.

USE company;
SELECT  Education,
        AVG(DISTINCT Yearly_Income)
FROM customerdetails
GROUP BY Education;

The above query finds a Unique number of records (by removing duplicates) present in the Yearly_Income column, then calculates their average.

Distinct Example 3