COUNT, SUM, AVG, MIN, MAX
087 min
“How many students are there?”, “what is the average score?”, “how much does the most expensive product cost?” — questions like these turn many rows into one number. That is what aggregate functions are for.
The five main functions
| Function | What it does |
|---|---|
COUNT(*) |
number of rows |
SUM(column) |
total |
AVG(column) |
average |
MIN(column) |
smallest |
MAX(column) |
largest |
Together with WHERE
Rows are picked first, then counted:
COUNT(*), COUNT(column) and COUNT(DISTINCT …)
COUNT(*)— every row;COUNT(phone)— only rows wherephoneis not empty;COUNT(DISTINCT city)— how many different cities.
Aggregates ignore NULL: AVG(scholarship) gives the average only over students who receive one.
An important rule
You cannot just put an aggregate next to a plain column:
SELECT city, COUNT(*) FROM students; -- error!The database does not know which city to show: the result is one row, but there are many cities. To count each city separately you need GROUP BY — the next lesson.
How many products does the store have, and what is their average price? Two columns: the count and the average price rounded to a whole number.
What is the total revenue (sum of fare) from completed (status = 'completed') trips?
Remember
COUNT,SUM,AVG,MIN,MAX— one value from many rows.- Aggregates skip
NULL;COUNT(*)counts every row. - Need a plain column and an aggregate together? Use
GROUP BY.