…
…
SQL and Database Fundamentals · Lesson 11 / 41 · Grouping and aggregation
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
For the annual report, the provost's office wants four numbers: how many students there are, for how many of them a GPA has been entered, what the overall GPA is, and what the total capacity of the sections offered this term is. The answers to these questions are not individual rows but summary values calculated from rows.
Every query you have written so far returned rows. You filtered with WHERE, sorted with ORDER BY, and cut with LIMIT, but the result always consisted of rows of the table itself. If you filter 120 students, you are still left with a list of students. The provost's questions are different: the answer to "How many students are there?" is not a list but a single number. Printing the list and counting the rows by hand is tiring even with 120 rows, and error-prone in the 781-row enrollment table. In this lesson you will tell the database to count, add up, and average the rows itself.
In this lesson you will:
Functions that take many rows and return a single value are called aggregate functions. SQL has five basic aggregate functions:
| Function | What it does | Question in the case |
|---|---|---|
COUNT(*) | Counts rows | How many students are there? |
COUNT(column) | Counts rows where the column is filled (not NULL) | For how many students has a GPA been entered? |
SUM(column) | Adds up the values | What is the total capacity? |
AVG(column) | Takes the average of the values | What is the overall GPA? |
MIN(column), MAX(column) | Find the smallest and the largest value | What are the lowest and highest GPAs? |
The simplest example is the number of students. SELECT COUNT(*) FROM student; gives a one-row, one-column result: 120. In one query you can write several aggregate functions side by side, separated by commas; all of them are calculated over the same rows, and the result is still one row. The AS you learned in lesson 3 matters even more here: if you give no name, the result columns get names like count, avg, and max, and when two COUNT columns sit side by side, you cannot tell which is which.
Example 1: Student summary. Let's answer three of the provost's questions in one query:
SELECT COUNT(*) AS students, COUNT(gpa) AS with_gpa, COUNT(DISTINCT city) AS cities, ROUND(AVG(gpa), 2) AS avg_gpa, MIN(gpa) AS lowest, MAX(gpa) AS highest FROM student;
| students | with_gpa | cities | avg_gpa | lowest | highest |
|---|---|---|---|---|---|
| 120 | 88 | 12 | 2.45 | 0.14 | 4 |
(1 row)
Six columns, one row. There are 120 students, 88 of them have a GPA entered, the students come from 12 different cities, and the overall GPA is 2.45. ROUND rounds the average to two decimal places; we will look at it shortly. First, match each question with the function that answers it.
Which expression answers each question?
For each row, pick its match from the list, then check.
Two numbers stand out in Example 1: there are 120 students, but COUNT(gpa) said 88. The difference comes from NULLs. In lesson 7 you saw that NULL is "an unknown value". The first-year students who enrolled this year have no grades yet, so their gpa columns are empty. The most important rule of aggregate functions is this: all aggregate functions skip NULL. COUNT(column) counts only the filled values; SUM, AVG, MIN, and MAX also include only the filled values in the calculation. The one exception is COUNT(*): it does not look at a column, it counts rows; if a row exists, it is counted.
The table has 120 students; 32 of them have a NULL gpa. What does this query return?
SELECT COUNT(gpa) FROM student;
Before you write COUNT, ask yourself a single question: what am I counting? There are three answers, and each has its own form:
COUNT(*): "how many students", "how many enrollments", "how many sections".COUNT(column): "how many have an email", "how many have an advisor assigned".COUNT(DISTINCT column): "how many different cities", "how many different advisors". In lesson 6, DISTINCT dropped repeated rows; here it does the same job inside COUNT, dropping the repeats before counting. NULL is not counted here either.Seeing the three side by side on the same table is the best way to show the difference.
Example 2: The same table, three counts.
SELECT COUNT(*) AS total_rows, COUNT(email) AS email_filled, COUNT(DISTINCT city) AS distinct_cities, COUNT(advisor_id) AS with_advisor FROM student;
| total_rows | email_filled | distinct_cities | with_advisor |
|---|---|---|---|
| 120 | 111 | 12 | 112 |
(1 row)
Four different numbers came out of the same 120 rows. 9 students have no email, 8 students have no advisor assigned yet, and the 120 students come from only 12 different cities. None of them is wrong; each answers a different question. What is wrong is mixing up the question and the form. In the cell below the query is ready. First run it as it is, then try two tasks:
1. Add the column COUNT(DISTINCT advisor_id) AS advisors to the query: how many different advisors do the 112 students have? (The answer should be 19.)
2. Add the column COUNT(*) - COUNT(email) AS no_email: how many students have no email? (The answer should be 9.)
Try it now· not graded; doesn't affect progress
The subtraction in the second task is a useful pattern: since COUNT(*) gives all rows and COUNT(column) gives the filled ones, their difference is the number of empty ones. You arrive at the same answer as WHERE email IS NULL from lesson 7, but this way you see the filled and empty counts in the same row.
The rule of skipping NULL makes the most difference in an average. AVG(gpa) adds the 88 filled values and divides by 88. But what if we counted NULLs as 0? The COALESCE(gpa, 0) you learned in lesson 7 turns every NULL into 0. That way the 32 students without a GPA also enter the calculation.
Example 3: Two averages.
SELECT ROUND(AVG(gpa), 2) AS filled_avg, ROUND(AVG(COALESCE(gpa, 0)), 2) AS with_zeros FROM student;
| filled_avg | with_zeros |
|---|---|
| 2.45 | 1.8 |
(1 row)
Why is the second column smaller?
SELECT ROUND(AVG(gpa), 2) AS filled_avg, ROUND(AVG(COALESCE(gpa, 0)), 2) AS with_zeros FROM student; -- Result: 2.45 | 1.8
Which one is correct? It is not SQL but the business question that decides. If the provost's office asks "what is the average achievement of our students?", the right answer is 2.45: a student who has not taken an exam yet has not scored 0; their grade is unknown. 1.8 shows the first-year students as failing, unfairly. On the other hand, in some questions an empty value really means zero: if you count an order with no tip left at a café as a $0 tip, you find the average tip per order. The rule: before you turn NULL into 0, ask "is this blank really zero, or is it unknown?"
Aggregate functions work together with WHERE. In lesson 9 you saw the execution order: first FROM brings the table, then WHERE filters the rows, and last SELECT calculates. Because aggregate functions sit in SELECT, they are calculated on the rows that remain after filtering. The provost's fourth question is exactly like this: not all sections, but the total capacity of only this term's sections (2026-Fall, term_id = 3).
Example 4: This term's section summary.
SELECT SUM(capacity) AS total_capacity, ROUND(AVG(capacity), 1) AS average, COUNT(*) AS sections FROM course_offering WHERE term_id = 3;
| total_capacity | average | sections |
|---|---|---|
| 870 | 43.5 | 20 |
(1 row)
The course_offering table has 54 sections offered over three terms. WHERE first kept the 20 sections of 2026-Fall; SUM, AVG, and COUNT worked on these 20 rows. If you removed the WHERE line, you would get the total of the three terms (2400). Put the lines of the query in the order they are written.
Put the lines of the "this term's section summary" query in the right order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
SUM and AVG work only with numbers; you cannot add up text. MIN and MAX, however, work on anything that can be sorted: smallest and largest for numbers, oldest and newest for dates, first and last in the alphabet for text. For example, MAX(birth_date) gives the birth date of the latest-born, that is, the youngest student; MIN(enrollment_date) gives the date of the first enrollment. For text, the alphabetical order rules you saw in lesson 6 apply.
What happens if WHERE removes all the rows? The Data Science and Analytics department (department_id = 8) was founded this year and has no students yet. Let's ask for a summary of this department.
Example 5: A department without students.
SELECT COUNT(*) AS students, SUM(gpa) AS total, AVG(gpa) AS avg_gpa, MAX(gpa) AS highest FROM student WHERE department_id = 8;
| students | total | avg_gpa | highest |
|---|---|---|---|
| 0 | NULL | NULL | NULL |
(1 row)
The result is still one row; a query with an aggregate function writes the summary row even when no rows are left. But the values behave differently. COUNT returns 0, because there are no rows to count and "none" means 0. SUM, AVG, MIN, and MAX return NULL: there is nothing to add or average, and "the average of no values" is something unknown. If you want to see 0 instead of an empty cell in the report, wrap the result in COALESCE: COALESCE(SUM(gpa), 0) returns 0 for this department. Still, ask yourself: are "no data" and "zero" the same thing? Not for an average; the GPA of a department with no students is not 0, it does not exist.
Section number 48 of this term (Academic Writing) has 79 enrollments; the final exams have not been entered yet, so final_exam is NULL in all 79. What does this query return?
SELECT ROUND(AVG(final_exam), 1) FROM enrollment WHERE offering_id = 48;
The provost's office now asks how many students have a scholarship and how many pay. The first way that comes to mind is two separate queries: one with WHERE has_scholarship, the other with WHERE NOT has_scholarship. Both work, but the results come in two separate tables, and you merge them into the report by hand. WHERE filters the rows of the whole query; it cannot filter separately for two different conditions in the same query. What we want is for each column to count with its own condition. There are two ways to do it.
The first way is PostgreSQL's FILTER clause: COUNT(*) FILTER (WHERE has_scholarship) says "count the rows, but only the ones with a scholarship". The condition applies only to that function; the neighboring columns are not affected. The second way is the CASE from lesson 8: SUM(CASE WHEN NOT has_scholarship THEN 1 ELSE 0 END) gives 1 to every row that meets the condition and 0 to every row that does not, and adds them up; the total is the number of rows that meet the condition. FILTER is shorter and easier to read; CASE works in every database. Know both.
Example 6: Scholarship, paying, total.
SELECT COUNT(*) FILTER (WHERE has_scholarship) AS scholarship, SUM(CASE WHEN NOT has_scholarship THEN 1 ELSE 0 END) AS paying, COUNT(*) AS total FROM student;
| scholarship | paying | total |
|---|---|---|
| 28 | 92 | 120 |
(1 row)
Three numbers in one row: 28 with a scholarship, 92 paying, 120 in total. The third column had no FILTER, so it counted all rows. You can summarize letter grades with the same pattern. The cell below counts how many grades in the enrollment table are failing grades (F+ or F), how many are A, and how many letter grades were entered in total. Run it; then add an a_minus column that counts the A- grades (it should be 54).
Try it now· not graded; doesn't affect progress
The result is 45 failing, 85 A, and 471 graded enrollments. Of the 781 enrollments, only 471 have a letter grade; the remaining 310 belong to this term, and their grades have not been entered yet. In the last column we used COUNT(letter_grade), because the question is "how many grades were entered", and that is a count of filled values.
Everyone who meets aggregate functions for the first time tries this at some point: "Next to the number of students, let me see the names too."
What does this query do?
SELECT first_name, COUNT(*) FROM student;
The message PostgreSQL gives is this:
Outputcolumn "student.first_name" must appear in the GROUP BY clause or be used in an aggregate functionRead the message the way you learned in lesson 9: "the student.first_name column must either appear in the GROUP BY clause or be used inside an aggregate function." You already know the second option: if you write MIN(first_name), you get the first name in the alphabet (Adaeze), because now you want a single value. The first option, GROUP BY, is the subject of the next lesson.
The same rules apply on every table. Think of the eight orders of a small café today. The orders table has the product, category, amount ($), and tip ($). For some orders where no tip was left, the cashier wrote 0, and for others left the field empty:
| id | product | category | amount | tip |
|---|---|---|---|---|
| 1 | Latte | drink | 4.25 | 0.50 |
| 2 | Tea | drink | 1.00 | NULL |
| 3 | Bagel | food | 1.25 | NULL |
| 4 | Latte | drink | 4.25 | 0.25 |
| 5 | Toastie | food | 4.50 | 0.50 |
| 6 | Tea | drink | 1.00 | 0.00 |
| 7 | Cookie | dessert |
Example 7: The day's summary.
SELECT COUNT(*) AS orders, COUNT(tip) AS tips_entered, SUM(tip) AS tip_total, AVG(tip) AS avg_tip, AVG(COALESCE(tip, 0)) AS per_order, COUNT(DISTINCT product) AS products, SUM(amount) AS revenue FROM orders;
| orders | tips_entered | tip_total | avg_tip | per_order | products | revenue |
|---|---|---|---|---|---|---|
| 8 | 5 | 2 | 0.4 | 0.25 | 5 | 22.75 |
(1 row)
There are eight orders, but the tip field is filled in only five of them. The total of these five is $2.00. AVG(tip) divides 2.00 by 5: $0.40. AVG(COALESCE(tip, 0)) counts the blanks as 0 and divides 2.00 by 8: $0.25. Five different products were sold in eight orders (Latte, Tea, Bagel, Toastie, Cookie), and the day's revenue is $22.75.
The café owner asks, "What is the average tip on the orders where a tip was entered?" Which number?
SELECT AVG(tip) FROM orders;
The subtle point here is order number 6: the tip was written as 0. 0 is a value; COUNT(tip) counts it, and AVG includes it. The three orders left blank are not counted. If the cashier writes 0 one day and leaves it blank the next, the average changes. That is why it matters that the people entering the data follow the same rule.
MIN and MAX also work on text. The summary of all the sections offered over three terms, with the smallest and largest room codes:
SELECT COUNT(*) AS sections, SUM(capacity) AS total_capacity, MIN(capacity) AS smallest, MAX(capacity) AS largest, MIN(room) AS first_room, MAX(room) AS last_room FROM course_offering;
| sections | total_capacity | smallest | largest | first_room | last_room |
|---|---|---|---|---|---|
| 54 | 2400 | 30 | 60 | A-106 | C-419 |
(1 row)
Room codes are text; MIN gave the first in the alphabet (A-106), and
Mixing up the row count and the filled-value count. For the question "How many students have an email?", this gets written:
SELECT COUNT(*) AS with_email FROM student;
| with_email |
|---|
| 120 |
(1 row)
The query runs without an error, but the answer is wrong: COUNT(*) never looks at the email; it counts rows. The right form is COUNT(email), and the answer is 111. The reverse is also a mistake: if you write COUNT(email) for "how many students are there?", you lose the 9 students with an empty email. Since no error message appears, you catch this mistake only by asking yourself "am I counting rows or filled values?"
COUNT, SUM, AVG, MIN, and MAX reduce many rows to a single value; WHERE runs first, and the summary comes from the remaining rows. If no rows are left, COUNT returns 0 and the others return NULL.COUNT(*) counts rows, COUNT(column) counts filled values, and COUNT(DISTINCT column) counts distinct filled values; AVG is the average of the filled values only, and counting NULL as 0 (COALESCE) is done only if the business question calls for it.COUNT(*) FILTER (WHERE ...) or SUM(CASE WHEN ... THEN 1 ELSE 0 END); a non-aggregated column cannot be written next to an aggregate function on its own.Next lesson: You took a single summary of the whole table; with GROUP BY, you will produce a separate summary row for each department, each year, and each term.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
| 2.00 |
| NULL |
| 8 | Toastie | food | 4.50 | 0.75 |
MAXSUM(room)FILTER works not only with COUNT but with every aggregate function. How many drinks were sold at the café, how much revenue came from drinks, the total revenue, and the cheapest and priciest orders:
SELECT COUNT(*) FILTER (WHERE category = 'drink') AS drinks, SUM(amount) FILTER (WHERE category = 'drink') AS drink_revenue, SUM(amount) AS revenue, MIN(amount) AS cheapest, MAX(amount) AS priciest FROM orders;
| drinks | drink_revenue | revenue | cheapest | priciest |
|---|---|---|---|---|
| 4 | 10.5 | 22.75 | 1 | 4.5 |
(1 row)
Four of the eight orders are drinks, and $10.50 of the $22.75 revenue came from drinks. The first two columns were calculated with their own condition, and the last three with all rows.