๐Ÿ”ข SQL Aggregate Functions
Estimated reading: 2 minutes 40 views

โž— 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() with GROUP BY
  • Filter averages using HAVING
  • Handle NULL values 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 outputLeaving unnamed aggregate results
Pair with GROUP BY for analysisAveraging raw rows without context
Use COALESCE() for NULL handlingAssuming 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 BY for segmented insights
  • Use HAVING to 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

โž— SQL AVG

Or Copy Link

CONTENTS
Scroll to Top