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
Key Points
- Null values are ignored in the calculation.
- You can use it with
WHEREto filter rows before calculating the average. - It is commonly used with
GROUP BYfor grouped averages.
Examples
1. Basic Example
Calculate the average salary of all employees:
2. Using WHERE Clause
Calculate the average salary of employees in the "IT" department:
3. Using GROUP BY
Calculate the average salary for each department:
4. Combining with HAVING
Filter departments where the average salary is greater than $50,000:
Notes
- The result of
AVG()may include decimal places, depending on the column's data type. - If no rows match the criteria,
AVG()returnsNULL.
No comments:
Post a Comment