AVG

Beginner

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.

Basic syntax

The basic syntax of the AVG() function is as follows:

SELECT AVG(column_name)
FROM table_name
WHERE condition
  • AVG(column_name): This calculates the average value of the non-NULL values in the specified column_name.
  • 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.

Examples

  1. Calculating Average Salary

Consider a table named employees with a salary column. To calculate the average salary of all employees, you can use:

SELECT AVG(salary)
FROM employees

This query will return the average salary of all employees in the employees table.

  1. Calculating Average Based on a Condition

To calculate the average salary of employees in the 'IT' department, you can use:

SELECT AVG(salary)
FROM employees
WHERE department = 'IT'

This query will return the average salary of employees who belong to the 'IT' department.

Remember

The 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.