In SQL, the AVG()
function is an aggregate function used to calculate the average value of a set of values in a column. It operates on a column of numerical data and returns the average of all the values in that column.
Here's the syntax for using the AVG()
function:
SELECT AVG(column_name) FROM table_name;
Example:
Let's say we have a table called sales
with a column named amount
representing the sales amount for each transaction. We want to find the average sales amount:
SELECT AVG(amount) AS average_sales_amount FROM sales;
In this example:
AVG(amount)
calculates the average of all values in the amount
column.AS average_sales_amount
assigns a name to the calculated average, which can be used to reference the result.The AVG()
function can also be combined with other clauses such as GROUP BY
to calculate averages for groups of rows based on certain criteria.
Example:
Let's say we want to find the average sales amount for each product category:
SELECT product_category, AVG(amount) AS average_sales_amount FROM sales GROUP BY product_category;
In this example:
GROUP BY product_category
groups the rows by the product_category
column.AVG(amount)
calculates the average sales amount for each group of rows within each product category.