Wednesday, December 18, 2024

SQL AVG() Function

 The SQL AVG() function is used to calculate the average (arithmetic mean) of a numeric column's values. It is often used with the GROUP BY clause to calculate averages for specific groups of rows.

Syntax

SELECT AVG(column_name) FROM table_name WHERE condition;

Key Points

  • Null values are ignored in the calculation.
  • You can use it with WHERE to filter rows before calculating the average.
  • It is commonly used with GROUP BY for grouped averages.

Examples

1. Basic Example

Calculate the average salary of all employees:

SELECT AVG(salary) AS average_salary FROM employees;

2. Using WHERE Clause

Calculate the average salary of employees in the "IT" department:

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

3. Using GROUP BY

Calculate the average salary for each department:

SELECT department, AVG(salary) AS average_salary FROM employees GROUP BY department;

4. Combining with HAVING

Filter departments where the average salary is greater than $50,000:

SELECT department, AVG(salary) AS average_salary FROM employees GROUP BY department HAVING AVG(salary) > 50000;

Notes

  • The result of AVG() may include decimal places, depending on the column's data type.
  • If no rows match the criteria, AVG() returns NULL.

No comments:

Post a Comment