SQL AVG() Function โ Calculate Averages in SQL
Introduction โ What is SQL AVG()?
The AVG() function in SQL is used to calculate the average (arithmetic mean) of values in a numeric column. It’s ideal for understanding trends, measuring performance, and generating insights from data.
In this guide, you’ll learn how to:
- Use
AVG()in queries - Combine
AVG()withGROUP BY - Filter averages using
HAVING - Handle
NULLvalues correctly
1. Basic AVG() Syntax
SELECT AVG(column_name) FROM table_name;
Returns the average of all non-NULL numeric values in the specified column.
2. Example โ Average Salary
SELECT AVG(salary) AS average_salary
FROM employees;
Calculates the average salary of all employees.
3. AVG() with GROUP BY
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department;
Shows the average salary per department.
4. Filtering AVG() with HAVING
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
HAVING AVG(salary) > 60000;
Filters groups to only include departments with an average salary above 60,000.
5. NULL Handling in AVG()
AVG()ignores NULLs automatically- Use
COALESCE()to treat NULLs as zero:
SELECT AVG(COALESCE(sales, 0)) FROM performance;
Ensures a value is included even if some rows are missing data.
Best Practices
| Do This | Avoid This |
|---|---|
| Use aliases for readable output | Leaving unnamed aggregate results |
Pair with GROUP BY for analysis | Averaging raw rows without context |
Use COALESCE() for NULL handling | Assuming NULLs are counted as 0 |
Summary โ Recap & Next Steps
The SQL AVG() function is essential for calculating average metrics in datasets. From salary trends to product ratings, AVG() gives you reliable arithmetic means.
Key Takeaways:
- Use
AVG(column)to compute average values - Pair with
GROUP BYfor segmented insights - Use
HAVINGto filter based on averages - Handle NULLs using
COALESCE()if needed
Real-World Relevance:
Used in performance analytics, rating systems, market analysis, and sales reporting.
Next: Explore MIN() and MAX() to find range boundaries.
FAQ โ SQL AVG Function
What does SQL AVG() do?
It returns the arithmetic mean of all non-NULL values in a numeric column.
Does AVG() ignore NULLs?
Yes. Only non-NULL values are considered.
How do I get average per group?
Use GROUP BY. Example:
SELECT city, AVG(price) FROM hotels GROUP BY city;
Can I filter average values?
Yes. Use HAVING to filter on aggregate values.
Can AVG() work with expressions?
Yes. Example:
SELECT AVG(score * 1.5) FROM reviews;
Share Now :
