SQL Server AVG() Function

In SQL Server, the AVG() function is an aggregate function used to calculate the average value of all values in a specified column.

Syntax

The basic syntax of the AVG() function is as follows:

AVG(expression)

where expression is the column or expression for which to calculate the average value.

Usage

The AVG() function is typically used to calculate the average value of columns with numeric data types, such as integers, decimals, or floats. For example, in a sales table, you can use the AVG() function to calculate the average sales amount.

Examples

Here are two examples of using the AVG() function.

Example 1

Suppose you have a student score table as follows:

id name score
1 Tom 85
2 Jack 90
3 Alice 80
4 Bob 95

You can use the following SQL statement to calculate the average score of the students:

SELECT AVG(score) AS avg_score
FROM student_scores;

The result is:

avg_score
87.5

Example 2

Suppose you have an order table as follows:

order_id customer_id order_total
1 1001 50
2 1002 75
3 1001 100
4 1003 125

You can use the following SQL statement to calculate the average order total:

SELECT AVG(order_total) AS avg_total
FROM orders;

The result is:

avg_total
87.5

Conclusion

By using the AVG() function, we can easily calculate the average value of a column or expression.