
202 views
MySQL avg()
The AVG()
function in MySQL is an aggregate function used to calculate the average (arithmetic mean) of values in a numeric column. It is commonly used to generate summary statistics about a dataset. The basic syntax of the AVG()
function is as follows:
AVG(expression)
expression
: This should be a numeric column or a numeric expression from which you want to calculate the average.
Here are some common ways to use the AVG()
function:
- Calculate the Average of Values in a Column:
To calculate the average of all values in a numeric column, useAVG(column_name)
.
SELECT AVG(score) FROM test_scores;
- Calculate the Average of Values Based on a Condition:
You can calculate the average of values that meet specific conditions by using theAVG()
function with aWHERE
clause.
SELECT AVG(price) FROM products WHERE category = 'Electronics';
- Calculate the Average of Distinct Values in a Column:
If you want to calculate the average of distinct (unique) values in a numeric column, you can use theAVG(DISTINCT column_name)
syntax.
SELECT AVG(DISTINCT temperature) FROM weather_data;
- Calculate the Average of Values Grouped by a Column:
When you want to calculate the average of values for each group within a dataset, you can use theGROUP BY
clause with theAVG()
function.
SELECT department, AVG(salary) FROM employees GROUP BY department;
The AVG()
function returns a numeric result, representing the arithmetic mean of the values in the specified column. It is a useful tool for calculating the average value of a dataset, such as average test scores, average prices, or average salaries in a specific department.