✅ Aggregate functions are special SQL functions that:
Take multiple input values (from rows) and return a single value as a summary.
- They work on a set of rows — not just one row at a time.
- Used commonly with
GROUP BY
to summarize data.
Common Aggregate Functions
Function | What It Does |
---|---|
COUNT() | Counts the number of rows. |
SUM() | Adds up values. |
AVG() | Calculates the average (mean) value. |
MIN() | Finds the minimum value. |
MAX() | Finds the maximum value. |
Quick Examples
Assume a table Sales
:
sale_id | amount |
---|---|
1 | 100 |
2 | 150 |
3 | 200 |
1. COUNT()
Count how many sales there are:
SELECT COUNT(*) FROM Sales;
Result: 3
2. SUM()
Total sales amount:
SELECT SUM(amount) FROM Sales;
Result: 450
(100 + 150 + 200)
3. AVG()
Average sale amount:
SELECT AVG(amount) FROM Sales;
Result: 150.00
4. MIN()
Smallest sale:
SELECT MIN(amount) FROM Sales;
Result: 100
5. MAX()
Largest sale:
SELECT MAX(amount) FROM Sales;
Result: 200
Other Useful Aggregate Functions
Function | Description |
---|---|
COUNT(DISTINCT col) | Count unique values only. |
GROUP_CONCAT(col) (MySQL) | Concatenates values into a string (e.g., "A,B,C" ) |
STRING_AGG(col, ', ') (PostgreSQL, SQL Server) | Newer SQL standard for string concatenation. |
VAR_SAMP() / STDDEV() | Variance / standard deviation for statistical summaries. |
Where Are Aggregate Functions Commonly Used?
GROUP BY
summaries:
SELECT department, SUM(salary)
FROM Employees
GROUP BY department;
- Reports — totals, averages, counts.
- Data analytics — distributions, trends.
In Short
Aggregate functions summarize multiple rows into a single result — essential for reporting, analytics, and grouped summaries.