Lesson 24: Aggregate Functions (COUNT, SUM, AVG, MIN, MAX)
Aggregate functions perform a calculation on a set of rows and return a single summary value. These are essential for reporting and analysis.
The Five Main Functions
- COUNT(): Counts the number of rows in the set.
- SUM(): Calculates the sum of values in a numeric column.
- AVG(): Calculates the average (mean) value of a numeric column.
- MIN(): Finds the smallest value in a column.
- MAX(): Finds the largest value in a column.
Example 1: Calculating Totals and Counts
Find the total number of products, the highest price, and the total value of stock.
sql SELECT COUNT(*) AS TotalProducts, -- Counts all rows MAX(Price) AS HighestPrice, SUM(Price * StockQuantity) AS TotalStockValue FROM Products;
COUNT(*) vs. COUNT(ColumnName)
COUNT(*): Counts every row, including those withNULLvalues in other columns.COUNT(ColumnName): Only counts rows where the specifiedColumnNameis NOT NULL.
Example 2: Counting Distinct Values
If you want to count how many unique departments exist, use DISTINCT.
sql SELECT COUNT(DISTINCT Department) FROM Employees;