The SQL AVG function is used to calculate the average value of a set of numeric data values in a database table. It is a commonly used SQL aggregate function that can be applied to a single column or multiple columns of a table.
The syntax for the AVG function is as follows:
SELECT AVG(column_name) FROM table_name;
Here, column_name refers to the name of the column for which we want to find the average value, and table_name is the name of the table that contains the column.
For example, let’s say we have a table called Sales with columns Product, Price, and Quantity. We can use the AVG function to find the average price of all the products in the table as follows:
SELECT AVG(Price) FROM Sales;
This query will return a single result, which is the average value of the Price column.
It is also possible to use the AVG function with the GROUP BY clause to find the average value for each group of data based on a specific column. For example, let’s say we want to find the average price of each product in the Sales table. We can use the following query:
SELECT Product, AVG(Price) FROM Sales GROUP BY Product;
This query will return a result set with two columns: Product and AVG(Price). The AVG(Price) column will contain the average price for each product in the table.
In addition to the AVG function, SQL provides other aggregate functions like SUM, COUNT, MIN, and MAX, which can be used to perform various calculations on the data stored in a database table.