In SQL, the
AVG() function is an aggregate function used to calculate the average (mean) value of a specified column or a set of numerical values. The
AVG() function computes the sum of all values in the specified column and then divides the sum by the number of rows.
The basic syntax of the
AVG() function is as follows:
AVG(column_name): This calculates the average value of the non-NULL values in the specified
table_name: This is the name of the table from which you want to retrieve the data.
condition: This is an optional condition that specifies which rows to include in the average calculation.
- Calculating Average Salary
Consider a table named
employees with a
salary column. To calculate the average salary of all employees, you can use:
This query will return the average salary of all employees in the
- Calculating Average Based on a Condition
To calculate the average salary of employees in the 'IT' department, you can use:
WHERE department = 'IT'
This query will return the average salary of employees who belong to the 'IT' department.
AVG() function ignores
NULL values in the specified column when calculating the average. If a column contains
NULL values, they are excluded from the calculation.