MySQL Aggregate Functions
Aggregate functions calculate one value from many rows.
| Function | Returns |
|---|---|
COUNT() | Number of rows |
SUM() | Total of a column |
AVG() | Average of a column |
MIN() | Smallest value |
MAX() | Biggest value |
SELECT
COUNT(*) AS total_students,
SUM(marks) AS total_marks,
AVG(marks) AS average_marks,
MIN(marks) AS lowest,
MAX(marks) AS highest
FROM students;
Result
| total_students | total_marks | average_marks | lowest | highest |
|---|---|---|---|---|
| 6 | 453 | 75.5000 | 45 | 92 |
COUNT(*) and COUNT(column)
SELECT COUNT(*) AS all_rows, COUNT(course_id) AS with_course FROM students;
Result
| all_rows | with_course |
|---|---|
| 6 | 5 |
COUNT(*) counts all rows. COUNT(column) counts only the rows where that column is not NULL. Vikram has no course, so he is not counted in the second one.
With WHERE
SELECT AVG(marks) AS delhi_average FROM students WHERE city = 'Delhi';
Result
| delhi_average |
|---|
| 75.0000 |
The average of Robin (85) and Vikram (65) is 75.
Note:
Aggregate functions ignore NULL values (except COUNT(*)). Use ROUND(AVG(marks), 2) to round the result to 2 decimals.
Summary
COUNT,SUM,AVG,MINandMAXgive one value for many rows.- Use them with
WHEREand with GROUP BY.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |