π SQL AVG() Function: Calculate the Average Value in SQL
The SQL AVG() function is an essential aggregate function used to calculate the average value of a numeric column. Whether you’re analyzing sales, ratings, or other performance metrics, AVG() helps you understand central tendencies in your data.
In this comprehensive guide, youβll learn:
- β
What the SQL
AVG()function does - π Syntax and usage
- π‘ Real-world examples for hands-on learning
- βοΈ Best practices and performance tips
π What is SQL AVG()?
The AVG() function returns the average of non-null numeric values in a column.
π§ Syntax:
SELECT AVG(column_name)
FROM table_name
WHERE condition;
π‘ Note: The AVG() function ignores NULL values during calculation.
π SQL AVG() Function Example
Example: Calculate the Average Salary
SELECT AVG(salary) AS average_salary
FROM employees;
π Explanation:
- This query returns the average salary of all employees in the
employeestable. AS average_salaryrenames the output column for clarity.
π― Use AVG() with GROUP BY
You can use AVG() alongside the GROUP BY clause to compute averages per category.
Example: Average Salary by Department
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id;
π This query shows the average salary for each department.
π₯ Combine AVG() with WHERE Clause
You can filter data before averaging.
Example: Average Salary of Employees in a Specific Department
SELECT AVG(salary) AS avg_sales_salary
FROM employees
WHERE department_id = 3;
β Exclude NULL Values
The AVG() function automatically excludes NULL values from its calculation.
Example: Safe Average Calculation
If some employees donβt have a salary entered:
SELECT AVG(salary) AS avg_salary
FROM employees;
β Only non-null salaries are used in the result.
π§ Real-World Use Cases
- π Average revenue per customer
- β Average product rating
- π Average exam score by subject
- π° Average order value in e-commerce
β οΈ Performance Tips
- Ensure the column youβre averaging is indexed if used with
WHERE. - Use
CAST()if you’re averaging integers and need decimal precision:
SELECT AVG(CAST(salary AS DECIMAL(10,2))) FROM employees;
π Summary
The SQL AVG() function is perfect for:
- Measuring central tendencies
- Summarizing numeric data
- Creating powerful dashboards and insights
Once you master AVG(), you can combine it with GROUP BY, JOIN, and other aggregate functions for even deeper analysis.