The MySQL AVG function is an aggregate function that is used to calculate the average value of a numeric column within a specified table. This function is particularly useful when you want to obtain the average of a set of values, such as grades, prices, or any other numerical data stored in a MySQL database.
Syntax
Here is the basic syntax of the AVG function:
SELECT AVG(column_name) FROM table_name;
column_name: The name of the column for which you want to calculate the average.
table_name: The name of the table from which the data is retrieved.
Example
For example, let’s say you have a table named grades with a column named score, and you want to find the average score:
SELECT AVG(score) FROM grades;
This query will return a single value, which is the average score from the grades table.
It’s important to note that the AVG function only works with numeric columns, and it ignores NULL values during the calculation. If there are non-numeric values in the specified column, the AVG function will produce an error.
Additionally, you can use the AVG function in combination with other SQL clauses. For instance, you might want to calculate the average for a specific group of data using the GROUP BY clause:
SELECT department, AVG(salary) FROM employees GROUP BY department;
In this example, the query calculates the average salary for each department in the employees table.
In summary, the MySQL AVG function is a powerful tool for obtaining the average value of numeric data within a database, providing a quick and efficient way to analyze and summarize numerical information.