โ 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 :
