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 to find the Average Cost of laptops present in your Store, then you can use this one.
MySQL Avg Function Syntax
The basic syntax of the MySQL AVG Function is as shown below:
SELECT AVG([Column_Name]) FROM [Source]
For finding Average with an example, we are going to use the below-shown data
MySQL 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 total number records present in Yearly_Income column from the customerdetails table.
SELECT AVG(Yearly_Income) AS `Average Income` FROM customerdetails;
MySQL AVG Function Group By Example
In general, we use it to check for Average product price belongs 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)
AVG Distinct Example
It allows you to use the DISTINCT keyword along with the MySQL 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.
USE company; SELECT Education, AVG(DISTINCT Yearly_Income) FROM customerdetails GROUP BY Education;
The above query find Unique number of records (by removing duplicates) present in Yearly_Income column, and then calculates the average of them