Table of Contents
ToggleWelcome to our SQL tutorial! Today, we’re exploring the SQL AVG() function, which is widely used to calculate the average value of a numeric column in a database. Whether you’re a student in Bengaluru or a budding data analyst in Delhi, understanding this function will take your SQL skills to the next level.
The AVG() function returns the average value of a numeric column, ignoring any NULL values. This is especially useful for summarizing data in Indian business contexts, such as calculating the average salary of employees, the average price of products, or even the average temperature in various cities.
SELECT AVG(column_name)
FROM table_name
WHERE condition;
Consider the following example where we calculate the average price of all products:
SELECT AVG(Price)
FROM Products;
Note: NULL values are ignored in this calculation.
Here are some examples relevant to India:
SELECT AVG(Price)
FROM Products
WHERE CategoryID = 1;
SELECT *
FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);
This example calculates the average price for each product category:
SELECT AVG(Price) AS AveragePrice, CategoryID
FROM Products
GROUP BY CategoryID;
The SQL AVG() function is a powerful tool for analyzing data. From e-commerce to education, its applications are vast and particularly relevant to India’s growing digital economy. Practice these examples on a database to master the function!
Now, calculate the average price of all products using the SQL AVG() function:
SELECT AVG(Price) AS AveragePrice
FROM Products;
Output: The query will return the average price of all products. For the sample data, the result will be:
| AveragePrice |
|---|
| 20.10 |
Calculate the average price of products grouped by category:
SELECT CategoryID, AVG(Price) AS AveragePrice
FROM Products
GROUP BY CategoryID;
Output: This will return the average price for each category:
| CategoryID | AveragePrice |
|---|---|
| 1 | 23.33 |
| 2 | 15.25 |
