Aggregate Functions

SQL Aggregate Functions

An aggregate function performs a calculation on a set of values and returns a single value.

FunctionReturns
COUNT()the number of rows
SUM()the total of a numeric column
AVG()the average of a numeric column
MIN()the smallest value
MAX()the largest value

All Together

Example

Summary of all orders:

SELECT COUNT(*)        AS Orders,
       SUM(Amount)     AS Revenue,
       ROUND(AVG(Amount), 2) AS AvgOrder,
       MIN(Amount)     AS Smallest,
       MAX(Amount)     AS Largest
FROM Orders;

Result: 1 row

OrdersRevenueAvgOrderSmallestLargest
81499.8187.4727412

Aggregates Ignore NULL

Every aggregate except COUNT(*) skips NULL values.

Example

There are 6 products, but only 5 have a stock value:

SELECT COUNT(*) AS AllRows, COUNT(Stock) AS WithStock, SUM(Stock) AS TotalStock
FROM Products;

Result: 1 row

AllRowsWithStockTotalStock
65545

With GROUP BY

Aggregates are most useful with GROUP BY, which returns one result per group instead of one for the whole table (see the Grouping Data module).

Example

Number of employees and the highest salary in each department:

SELECT Department, COUNT(*) AS Staff, MAX(Salary) AS TopSalary
FROM Employees
GROUP BY Department;

Result: 3 rows

DepartmentStaffTopSalary
Finance180000
Sales372000
Support267000