SQL Aggregate Functions
Aggregate functions take many rows and return one value, such as a count, a total or an average.
The Five Main Functions
| Function | Returns |
|---|---|
COUNT() | How many rows or values |
SUM() | The total of a number column |
AVG() | The average of a number column |
MIN() | The smallest value |
MAX() | The largest value |
COUNT
COUNT(*) counts all rows:
Example
SELECT COUNT(*) AS total_students
FROM students;| total_students |
|---|
| 6 |
COUNT(column) counts only the rows where that column is not NULL:
Example
SELECT COUNT(course_id) AS with_course
FROM students;| with_course |
|---|
| 5 |
The answer is 5, not 6, because Hamza's course_id is NULL.
MIN and MAX
Example
SELECT MIN(marks) AS lowest, MAX(marks) AS highest
FROM students;| lowest | highest |
|---|---|
| 64 | 92 |
MIN and MAX also work on text (alphabetical order) and on dates (earliest and latest).
SUM and AVG
Example
SELECT SUM(marks) AS total, AVG(marks) AS average
FROM students;| total | average |
|---|---|
| 477 | 79.5 |
All the marks add up to 477, and 477 divided by 6 students is 79.5. Some databases show more decimal places, like 79.5000.
Aggregates with WHERE
WHERE filters the rows first, then the function runs on what is left. This finds the average marks of students from Karachi, rounded to 2 decimal places:
Example
SELECT ROUND(AVG(marks), 2) AS karachi_average
FROM students
WHERE city = 'Karachi';| karachi_average |
|---|
| 70.67 |
Ali (78), Bilal (64) and Hamza (70) add up to 212, and 212 / 3 is about 70.67.
How NULL Is Treated
Aggregate functions skip NULL values, except COUNT(*), which counts whole rows. If a student had no marks yet, AVG(marks) would be the average of the other students only, not a zero for the missing one.
You cannot put an aggregate function inside WHERE. A query like WHERE marks > AVG(marks) gives an error. To filter on an aggregate result, use HAVING (see GROUP BY and HAVING), or a subquery: WHERE marks > (SELECT AVG(marks) FROM students).
The subquery version works well:
Example
SELECT name, marks
FROM students
WHERE marks > (SELECT AVG(marks) FROM students);| name | marks |
|---|---|
| Ayesha Siddiqui | 85 |
| Fatima Noor | 92 |
| Sana Iqbal | 88 |
These are the students who scored above the class average of 79.5.
Exercise
Exercise
The students table has 6 rows, and one student has course_id NULL. What does SELECT COUNT(course_id) FROM students; return?
