Careeroza
Aggregate Functions
SQL Aggregate Functions
An aggregate function performs a calculation on a set of values and returns a single value.
| Function | Returns |
|---|---|
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
| Orders | Revenue | AvgOrder | Smallest | Largest |
|---|---|---|---|---|
| 8 | 1499.8 | 187.47 | 27 | 412 |
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
| AllRows | WithStock | TotalStock |
|---|---|---|
| 6 | 5 | 545 |
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
| Department | Staff | TopSalary |
|---|---|---|
| Finance | 1 | 80000 |
| Sales | 3 | 72000 |
| Support | 2 | 67000 |