Microsoft SQL Server Documentation

SQL Aggregate Functions

Aggregate functions perform a calculation on a set of values and return a single scalar value. Aggregate functions are often used with the GROUP BY clause and the HAVING clause of SQL statements.

Common Aggregate Functions

AVG(expression)

Returns the average value of a column.

COUNT(expression | *)

Returns the number of rows or non-null values in a column.

MAX(expression)

Returns the largest value in a set of values.

MIN(expression)

Returns the smallest value in a set of values.

SUM(expression)

Returns the sum of values in a column.

STDEV(expression)

Returns the standard deviation of a column.

VAR(expression)

Returns the variance of a column.

Syntax and Usage

Aggregate functions operate on a set of rows. When used without a GROUP BY clause, they operate on all rows selected by the query. When used with a GROUP BY clause, they operate on each group separately.

Example: Calculating Average Salary by Department

Consider a table named Employees with columns Department and Salary.


SELECT Department, AVG(Salary) AS AverageSalary
FROM Employees
GROUP BY Department;
            

Example: Counting Employees in Each Department


SELECT Department, COUNT(*) AS NumberOfEmployees
FROM Employees
GROUP BY Department
HAVING COUNT(*) > 10;
            

More Aggregate Functions

SQL Server also provides more specialized aggregate functions:

Key Concepts

For detailed information on each aggregate function, including specific syntax and examples, please refer to the official SQL Server Transact-SQL reference.