SQL AVG() Function
The AVG()
function in SQL calculates the average (mean) of a set of numeric values. It's a fundamental aggregate function, used to summarize numerical data.
AVG(): Definition and Usage
AVG()
is incredibly useful for understanding the central tendency of your data. It works on a set of values (typically from a single column in a table), ignoring any NULL
values. The result is a single number representing the average of the non-null values.
Syntax
Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
Example Database: Products Table
The following examples use this sample 'Products' table:
ProductID | ProductName | SupplierID | CategoryID | Unit | Price |
---|---|---|---|---|---|
1 | Chais | 1 | 1 | 10 boxes x 20 bags | 18 |
2 | Chang | 1 | 1 | 24 - 12 oz bottles | 19 |
3 | Aniseed Syrup | 1 | 2 | 12 - 550 ml bottles | 10 |
4 | Chef Anton's Cajun Seasoning | 2 | 2 | 48 - 6 oz jars | 22 |
5 | Chef Anton's Gumbo Mix | 2 | 2 | 36 boxes | 21.35 |
Examples
Calculating the Average Price of All Products
This query calculates the average price of all products.
Syntax
SELECT AVG(Price) FROM Products;
Output
17.67
Calculating the Average Price with a Condition
This calculates the average price for products in category 1.
Syntax
SELECT AVG(Price) FROM Products WHERE CategoryID = 1;
Output
18.5
Using an Alias
This gives the average price a more descriptive name.
Syntax
SELECT AVG(Price) AS "Average Price" FROM Products;
Output
Average Price
-------------
17.67
Finding Products Above Average Price
This uses AVG()
in a subquery to identify products priced above average.
Syntax
SELECT * FROM Products WHERE price > (SELECT AVG(price) FROM Products);
Output
ProductID | ProductName | SupplierID | CategoryID | Unit | Price
---------------------------------------------------------------------------------
4 | Chef Anton's Cajun Seasoning | 2 | 2 | 48 - 6 oz jars | 22
5 | Chef Anton's Gumbo Mix | 2 | 2 | 36 boxes | 21.35
Using AVG() with GROUP BY
This calculates the average price for each category.
Syntax
SELECT AVG(Price) AS AveragePrice, CategoryID
FROM Products
GROUP BY CategoryID;
Output
AveragePrice | CategoryID
-------------|------------
18.5 | 1
16.675 | 2