sql_func_avg
SQL AVG() Function
Section titled “SQL AVG() Function”The AVG() Function
Section titled “The AVG() Function”The AVG() function is an aggregate function that calculates the average value of a numeric column.
NULL values in the specified column are ignored by the AVG() function during calculation.
SQL AVG() Syntax
Section titled “SQL AVG() Syntax”SELECT AVG(column_name)FROM table_nameWHERE condition;The WHERE clause is optional. If omitted, AVG() calculates the average over all rows in the table for the specified column.
Demo Database
Section titled “Demo Database”For this tutorial, we’ll use the Northwind sample database, specifically the “Products” table.
Below is a selection from the “Products” table:
ProductIDProductNameSupplierIDCategoryIDUnitPrice
1Chais1110 boxes x 20 bags18.00
2Chang1124 - 12 oz bottles19.00
3Aniseed Syrup1212 - 550 ml bottles10.00
4Chef Anton's Cajun Seasoning2248 - 6 oz jars22.00
5Chef Anton's Gumbo Mix2236 boxes21.35Note: Prices are simplified for clarity in this example.
SQL AVG() Examples
Section titled “SQL AVG() Examples”- Calculate the average price of all products:
The following SQL statement calculates the average value of the “Price” column in the “Products” table.
SELECT AVG(Price) AS AverageProductPriceFROM Products;This query will return a single row with a single column named AverageProductPrice containing the calculated average.
- Calculate the average price for products from a specific category (e.g., CategoryID = 1):
SELECT AVG(Price) AS AverageCondimentPriceFROM ProductsWHERE CategoryID = 1;- Using AVG() in a Subquery:
The following SQL statement selects all products whose price is higher than the average price of all products.
SELECT ProductName, PriceFROM ProductsWHERE Price > (SELECT AVG(Price) FROM Products);In this example, the subquery (SELECT AVG(Price) FROM Products) is executed first to determine the average price. Then, the outer query selects products exceeding this average.
Practical Application:
AVG() is widely used in reporting and data analysis to find mean values, such as average sales, average scores, average response times, etc. It’s often used with the GROUP BY clause to calculate averages for different groups within the data (e.g., average price per product category).