SQL Aggregates
SQL AVG
Calculating Averages with AVG
AVG computes the mean of numeric values, handling NULLs automatically.
Introduction to SQL AVG
The SQL AVG function is used to calculate the average (mean) value of a numeric column in a dataset. It is an aggregate function that conveniently handles NULL
values by ignoring them in the calculation, ensuring accurate results.
Basic Syntax of SQL AVG
The basic syntax for using the AVG function in SQL is as follows:
Example: Calculating Average Price
Consider a table named Products
with the following columns: ProductID
, ProductName
, and Price
. To find the average price of all products, you can use the AVG function as shown below:
Handling NULL Values
The AVG function automatically ignores NULL
values in the column it computes. This means that only non-null values are considered in the average calculation, ensuring that the presence of NULL
does not affect the result.
Using AVG with GROUP BY
The AVG function can be used in conjunction with the GROUP BY
clause to calculate averages for distinct groups within a dataset. For example, if you want to find the average price of products by category, you would use the following query:
AVG with WHERE Clause
You can also use the AVG function with a WHERE
clause to filter records before calculating the average. For instance, to calculate the average price of products priced above $100, use the following query:
Conclusion
The SQL AVG function is a powerful tool for data analysis, allowing you to compute the average of numeric data efficiently. Its ability to handle NULL
values automatically and its compatibility with other SQL clauses like GROUP BY
and WHERE
makes it a versatile function for various analytical needs. In the next post, we'll explore how to use the MIN and MAX functions to find minimum and maximum values in datasets.
SQL Aggregates
- Previous
- SUM
- Next
- MIN and MAX