SQL Aggregate Function AVG()

ht‮www//:spt‬.theitroad.com

In SQL, the AVG() function is an aggregate function that calculates the average value of a set of numeric values. The function takes a single argument, which is the name of the column or expression to be averaged.

Here is an example of using the AVG() function to calculate the average salary of employees in a employees table:

SELECT AVG(salary) AS avg_salary FROM employees;

In this example, the AVG() function is used to calculate the average value of the salary column in the employees table. The result of the query is a single row with a single column, which contains the average salary value. The AS keyword is used to alias the column name as avg_salary.

The AVG() function can also be used with the GROUP BY clause to calculate the average value for each group in a table. For example, consider the following sales table:

+---------+-------+
| product | sales |
+---------+-------+
| A       | 100   |
| A       | 200   |
| B       | 150   |
| B       | 250   |
+---------+-------+

To calculate the average sales for each product, we can use the following query:

SELECT product, AVG(sales) AS avg_sales FROM sales GROUP BY product;

In this example, the AVG() function is used with the GROUP BY clause to calculate the average sales for each unique value in the product column. The result of the query is a table with two columns: product and avg_sales. The AVG() function is applied to the sales column for each group of rows that share the same product value.