…
…
SQL and Database Fundamentals · Lesson 21 / 41 · Subqueries
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.
The dean sent three questions: what is the average number of students per department, which students are above the GPA average of their own department, and which instructors teach at least one section this term. The first question asks for a summary of a summary, the second asks for a separate comparison for each student, and the third asks for a yes-or-no check. In this lesson you will learn a different subquery shape for each one.
In the previous lesson you used a subquery in WHERE in two ways: a subquery that returns one value (WHERE gpa > (SELECT AVG(gpa) FROM student)) and a subquery that returns a list (WHERE department_id IN (SELECT ...)). In both, the inner query runs once, hands its result to the outer query, and is done. The dean's three questions do not fit that pattern.
Let's sort the questions by shape, because the main skill in this lesson is reading the question before you pick a tool:
| Question | Shape | Tool in this lesson |
|---|---|---|
| Average number of students per department | First build a summary (a count per department), then take a summary of that summary (the average) | Subquery in FROM |
| Students above their own department's average | Compare each row with its own group | Correlated subquery |
| Instructors who teach this term | Does the other table have a match or not? | EXISTS / NOT EXISTS |
In this lesson you will:
Think through the dean's first question step by step. First you need the number of students in each department. You know this from lesson 12: SELECT department_id, COUNT(*) AS student_count FROM student GROUP BY department_id; returns 7 rows (not 8, because Data Science has no students). Then you need the average of those seven numbers. The first idea is to nest the two functions:
SELECT AVG(COUNT(*)) FROM student GROUP BY department_id;
Result: ERROR: aggregate function calls cannot be nested
The error message is right: SQL does not allow two layers of grouping in a single SELECT. COUNT(*) produces one number per department, and AVG would have to combine those numbers in another layer. The fix is to split the work into two queries and give the result of the first to the second as a table. The result of a SELECT is also a table with rows and named columns, so you can write it in FROM in parentheses, where a table name would go. This is called a derived table (a subquery in FROM).
Example 1 (case): A summary of a summary
SELECT ROUND(AVG(student_count), 2) AS avg_students, MAX(student_count) AS largest, MIN(student_count) AS smallest FROM (SELECT department_id, COUNT(*) AS student_count FROM student GROUP BY department_id) AS b;
| avg_students | largest | smallest |
|---|---|---|
| 17.14 | 24 | 10 |
(1 row)
The inner query produces an intermediate table of 7 rows: a department_id and a student_count for each department. The outer query reads this table like any ordinary table and takes the average, the maximum, and the minimum of the student_count column. The alias you gave in the inner query (COUNT(*) AS student_count) becomes the column name in the outer query; without a name, you could not easily refer to this column from outside. We also gave the intermediate table a name: AS b. PostgreSQL 16 and later do not require this name, but many other databases do, and a name makes it easier to see where each column comes from as the query grows. As a rule, give every derived table a name.
How many rows does the inner query produce, and how many rows does the outer query return?
SELECT ROUND(AVG(student_count), 2) AS average FROM (SELECT department_id, COUNT(*) AS student_count FROM student GROUP BY department_id) AS b;
A derived table is not only for taking an average. You can use it for any second step: you can filter it, regroup it, or join it with another table. The dean now asks: "How many students are in the largest class year of each department?" Again there are two layers. First, the number of students per department and class year (the first summary). Then the largest of those numbers within each department (the summary of the summary).
Example 2 (case): The largest class year of each department
SELECT department_id, MAX(student_count) AS largest_class FROM (SELECT department_id, year, COUNT(*) AS student_count FROM student GROUP BY department_id, year) AS t GROUP BY department_id ORDER BY department_id;
| department_id | largest_class |
|---|---|
| 1 | 8 |
| 2 | 7 |
| 3 | 3 |
| 4 | 7 |
| 5 | 6 |
| 6 | 4 |
| 7 | 9 |
(7 rows)
The inner query produces 25 rows: one row for each department and class year pair (some departments do not have all four years filled, which is why it is not 7 × 4 = 28). The outer query now groups these 25 rows by department only and takes the largest student_count in each group. For example, in department 1 the 1st year has 6 students and the 2nd year has 8; the outer query picks 8.
The safest habit when you write a subquery is, as in the previous lesson, to run the inner query on its own first. Try it in the cell below.
Try it now· not graded; doesn't affect progress
For the second task, if you write COUNT(*) instead of MAX(student_count), you count the rows in the intermediate table, which is the number of filled class years in each department: 2 for department 1, 3 for department 5, and 4 for the others.
Putting the parts of a derived table in the right place is a good way to learn the writing pattern. Put the short version of Example 1 in order.
Put the query that finds the average number of students per department in order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The dean's second question is different: "Which students are above the GPA average of their own department?" In the previous lesson you found the students above the overall average (2.45); there the inner query gave a single number for all students. Now the number to compare with changes from student to student: a Software Engineering student should be compared with the average of their own department, and a Psychology student with the average of theirs.
A subquery that does this is called a correlated subquery: the inner query refers to the row the outer query is currently examining, and it is calculated again for every outer row.
Example 3 (case): Students above their own department's average
SELECT s.student_no, s.department_id, s.gpa FROM student s WHERE s.gpa > (SELECT AVG(s2.gpa) FROM student s2 WHERE s2.department_id = s.department_id) ORDER BY s.department_id, s.gpa DESC;
| student_no | department_id | gpa |
|---|---|---|
| 202501001 | 1 | 3.57 |
| 202501007 | 1 | 3.24 |
| 202501005 | 1 | 2.95 |
| 202501004 | 1 | 2.74 |
| 202501003 | 1 | 2.59 |
| 202502007 | 2 | 4 |
(first 6 of 43 rows)
Read the query from one student's point of view. When the outer query reaches student 202501001, that student's department_id is 1. The inner query takes this value through s.department_id and asks, "What is the average GPA of the students in department 1?" Then the outer query moves to the next student; if that student is in department 4, the inner query now calculates the average of department 4. The same student table plays two roles: the outer s is the student being examined, and the inner s2 is their department mates. As in the self join of lesson 17, two roles need two aliases; without them you would write department_id = department_id, and it would not be clear which is which.
What makes this query dangerous is that it does not give an error when you delete one line.
What happens if the line WHERE s2.department_id = s.department_id is deleted from the inner query in Example 3?
SELECT s.student_no, s.department_id, s.gpa FROM student s WHERE s.gpa > (SELECT AVG(s2.gpa) FROM student s2);
Forgetting the correlation condition is the most common mistake in this lesson, because the result looks reasonable: 46 rows instead of 43 is not a big difference. The way to catch it is to compare the result with a number you found another way. That is exactly what comes next.
A correlated subquery says, in concept, "ask again for every row." You can also ask the same question in two steps: first calculate the average of each department in an intermediate table, then join this table to the students.
Example 4 (case): Finding the same number with a JOIN
SELECT COUNT(*) FROM student s JOIN (SELECT department_id, AVG(gpa) AS dept_avg FROM student GROUP BY department_id) AS b ON b.department_id = s.department_id WHERE s.gpa > b.dept_avg;
| count |
|---|
| 43 |
(1 row)
Both ways gave the same 43, which is good evidence that the correlation condition of the first query is correct. Which one should you choose? On small tables you will not feel a difference. On paper, a correlated subquery runs again for every row; in the JOIN version the department averages are calculated once. On large tables, and as queries get longer, the second way can be both faster and easier to read. In lesson 23 you will learn to give this intermediate table a name at the start of the query (a CTE), and the second way will look even tidier.
A correlated subquery works not only with > but also with =. The question "Who is the top student of each department?" means "the student whose GPA equals the highest GPA of their own department":
Example 5 (case): The top student of each department
SELECT s.department_id, s.first_name, s.last_name, s.gpa FROM student s WHERE s.gpa = (SELECT MAX(s2.gpa) FROM student s2 WHERE s2.department_id = s.department_id) ORDER BY s.department_id;
| department_id | first_name | last_name | gpa |
|---|---|---|---|
| 1 | Kenji | Park | 3.57 |
| 2 | Noor | García | 4 |
| 3 | Anika | Park | 3.65 |
| 4 | Zara | Larsen | 3.85 |
| 5 | Anika | Rivera | 3.88 |
| 6 | Ethan | Bianchi | 3.69 |
| 7 | Omar | Kim | 4 |
(7 rows)
Now write the same question the other way yourself and compare the row counts.
Try it now· not graded; doesn't affect progress
The JOIN version also returns 7 rows: JOIN (SELECT department_id, MAX(gpa) AS top_gpa FROM student GROUP BY department_id) AS b ON b.department_id = s.department_id WHERE s.gpa = b.top_gpa. If two students in one department had the same highest GPA, both ways would return both of them; there is no such tie in this data.
The dean's third question does not ask for a number or a comparison: "Who are the instructors with at least one section this term (2026-Fall, term_id = 3)?" For each instructor we want to know only one thing: in the course_offering table, is there at least one row that belongs to this instructor and this term?
EXISTS does exactly this: if the subquery in parentheses returns at least one row, it is true; if it returns no rows, it is false. It is almost always used with a correlated subquery, because the question "does this instructor have a row?" is asked separately for each instructor.
Example 6 (case): Instructors who teach this term
SELECT i.first_name, i.last_name FROM instructor i WHERE EXISTS (SELECT 1 FROM course_offering o WHERE o.instructor_id = i.id AND o.term_id = 3) ORDER BY i.last_name, i.first_name;
| first_name | last_name |
|---|---|
| Clara | Abara |
| Rosa | Bianchi |
| Diego | Costa |
| Tessa | Fernández |
| Greta | Kim |
| Fatima | Kowalski |
(first 6 of 15 rows)
Of the 20 instructors, 15 teach this term. If you write the same filter with a JOIN as in lesson 15 (FROM instructor i JOIN course_offering o ON o.instructor_id = i.id WHERE o.term_id = 3), you get 20 rows: Clara Abara appears twice and Noah Yamamoto three times, because a JOIN repeats each instructor once for every section (the row multiplication from lesson 18). EXISTS returns each instructor at most once: it knocks on the door, and when someone answers, it says "yes" and moves on to the next door. PostgreSQL really works this way; once it finds the first matching row, it stops searching for that instructor.
Notice that we wrote SELECT 1 in the subquery.
Why do people usually write SELECT 1 in EXISTS subqueries?
WHERE EXISTS (SELECT 1 FROM course_offering o WHERE o.instructor_id = i.id)
In the previous lesson, when you wrote WHERE i.id NOT IN (SELECT advisor_id FROM student) for "instructors who advise no one," you got 0 rows. The reason was that the advisor_id of 8 students is NULL: when the list contains a single NULL, NOT IN cannot say a definite "true" for any row. As a fix, you added WHERE advisor_id IS NOT NULL to the subquery.
NOT EXISTS never falls into this trap, because it does not compare values. It asks, "Is there a student row that names this instructor as advisor?" Rows with a NULL do not satisfy the condition s.advisor_id = i.id, so they simply match no instructor and do not spoil the result.
Example 7 (case): Instructors with no advisees, three ways
SELECT i.first_name, i.last_name FROM instructor i WHERE NOT EXISTS (SELECT 1 FROM student s WHERE s.advisor_id = i.id);
| first_name | last_name |
|---|---|
| Yuki | Cohen |
(1 row)
You can reach the same answer in three ways, and all three return 1 row:
| Way | Writing | Rows |
|---|---|---|
| NOT EXISTS | WHERE NOT EXISTS (SELECT 1 FROM student s WHERE s.advisor_id = i.id) | 1 |
| LEFT JOIN ... IS NULL (lesson 16) | LEFT JOIN student s ON s.advisor_id = i.id WHERE s.id IS NULL | 1 |
| NOT IN + NULL filter (lesson 20) | WHERE i.id NOT IN (SELECT advisor_id FROM student WHERE advisor_id IS NOT NULL) | 1 |
| NOT IN, without the filter | WHERE i.id NOT IN (SELECT advisor_id FROM student) | 0 (trap) |
Which one should you choose? NOT EXISTS states the intent most clearly: "an instructor with no students." You do not have to think about NULL. The LEFT JOIN pattern is useful when you also want to see or count the columns of the right table. NOT IN is safe only when you are sure the subquery will never return a NULL. The same pattern also answers the question "students with no enrollments": NOT EXISTS (SELECT 1 FROM enrollment e WHERE e.student_id = s.id) returns the three students from lesson 16 (Yuki Johansson, Mohammed Cohen, Hiro Kim).
Now match the four question shapes you have seen so far with their tools.
Choose the right tool for each question shape.
For each row, pick its match from the list, then check.
A correlated subquery can also sit in the SELECT list instead of WHERE; then it becomes a column calculated for each row. For example, you can get the number of students in each department, including the department with no students, like this:
Example 8 (case): The number of students in each department, inside SELECT
SELECT d.name, (SELECT COUNT(*) FROM student s WHERE s.department_id = d.id) AS students FROM department d ORDER BY students DESC, d.name;
| name | students |
|---|---|
| Business Administration | 24 |
| Psychology | 23 |
| Software Engineering | 20 |
| Management Information Systems | 17 |
| Computer Programming | 14 |
| Industrial Engineering | 12 |
| New Media and Communication | 10 |
| Data Science and Analytics | (guess it) |
(8 rows)
The outer query reads from the department table, so all 8 departments appear. You guess the last row.
The Data Science and Analytics department has no students. What does the students column show for this row in Example 8?
SELECT d.name, (SELECT COUNT(*) FROM student s WHERE s.department_id = d.id) AS students FROM department d;
The last row shows 0. You got the same list in lesson 16 with LEFT JOIN and COUNT(s.id); a subquery in SELECT reaches the same result without writing a join, and it makes a small count for each department.
In this lesson and the previous one you have seen six tools. Before you start a query, read the question with this table:
| If the question says | Tool | Pattern |
|---|---|---|
| "Above the overall average," "the highest" | Single-value subquery (lesson 20) | WHERE x > (SELECT AVG(x) FROM t) |
| "Those in this list" | IN (lesson 20) | WHERE id IN (SELECT ...) |
| "First make a summary, then take a summary of it" | Derived table | FROM (SELECT ... GROUP BY ...) AS t |
| "Compare each row with its own group" | Correlated subquery | WHERE x > (SELECT AVG(x2) ... WHERE inner.grp = outer.grp) |
| "Those with at least one match in the other table" | EXISTS | WHERE EXISTS (SELECT 1 FROM ... WHERE inner.fk = outer.id) |
| "Those with no match at all" | NOT EXISTS | WHERE NOT EXISTS (SELECT 1 FROM ... WHERE inner.fk = outer.id) |
A short note on speed: PostgreSQL turns EXISTS and NOT EXISTS into a join internally and runs them efficiently. A correlated subquery used in SELECT or in a > comparison, on the other hand, is often calculated row by row; if it gets slow on large tables, write the same question with a JOIN and a derived table, as in Example 4.
The same way of thinking works in every database. In the Earbud music app database (earbud.sql) that you will use in the last exercise, there are 8 artists and 30 songs; the song table stores the length of a song in seconds in the duration_sec column, and the song_like table shows which listener liked which song.
Example 9 (outside the case): Songs longer than their own artist's average
SELECT a.name AS artist, s.title AS song, s.duration_sec FROM song s JOIN artist a ON a.id = s.artist_id WHERE s.duration_sec > (SELECT AVG(s2.duration_sec) FROM song s2 WHERE s2.artist_id = s.artist_id) ORDER BY a.name, s.duration_sec DESC;
| artist | song | duration_sec |
|---|---|---|
| Asphalt Verse | Balcony at Five | 251 |
| Asphalt Verse | Blue Hour | 245 |
| Asphalt Verse | Silver Boat | 233 |
| Broken Compass | Wet Pavement | 263 |
| Broken Compass | Yellow Bus | 236 |
| Broken Compass | New Page | 226 |
(first 6 of 15 rows)
It is the same as the student and department question in the case: the outer s is the song being examined, and the inner s2 is the songs of the same artist. If you delete the correlation condition, every song is compared with the average of all songs (226.9 seconds), and 13 rows come back. For example, Prairie Strings' songs are long folk pieces with an average of 298.8 seconds; compared with the overall average, all four look "long," but compared with their own average, only three do.
The second question is "songs that received at least one like": SELECT s.title FROM song s WHERE EXISTS (SELECT 1 FROM song_like b WHERE b.song_id = s.id); returns 27 rows. If you write the same question as song JOIN song_like, you get 71 rows, because each like is a separate row. The answer to "How many songs were liked?" is 27; 71 is the number of likes.
A derived table together with the single-value subquery from lesson 20: first the count of each department, then the average of those counts, and finally the departments above the average. To get the department name, we join the intermediate table to the department table.
SELECT d.name, t.student_count FROM (SELECT department_id, COUNT(*) AS student_count FROM student GROUP BY department_id) AS t JOIN department d ON d.id = t.department_id WHERE t.student_count > (SELECT AVG(student_count) FROM (SELECT COUNT(*) AS student_count FROM student GROUP BY department_id) AS t2) ORDER BY t.student_count DESC;
| name | student_count |
|---|---|
| Business Administration |
Forgetting the correlation condition in a correlated subquery. If you write this for "students above their own department's average":
SELECT s.student_no, s.gpa FROM student s WHERE s.gpa > (SELECT AVG(s2.gpa) FROM student s2);
Result: 46 rows.
The query gives no error and the result looks plausible, but the inner query no longer looks at the department; it compares everyone with the overall average (2.45). The correct query returns 43 rows. Always look for the condition that ties the inner query to the outer row (WHERE s2.department_id = s.department_id); if the two aliases (s and s2) do not both appear in the inner query, the subquery is not correlated. To be sure, also find the number with a JOIN and a derived table, as in Example 4.
AVG(COUNT(*)) cannot be written, so you split the work into two layers. Always give the intermediate table a name.Next lesson: You will learn to stack the results of two queries and find what they share and what differs, with set operations (UNION, INTERSECT, EXCEPT).
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.
| Psychology | 23 |
| Software Engineering | 20 |
(3 rows)
Because the average is 17.14, Management Information Systems with 17 students does not make the list.
SELECT s.title, s.duration_sec FROM song s WHERE NOT EXISTS (SELECT 1 FROM song_like b WHERE b.song_id = s.id) ORDER BY s.title;
| title | duration_sec |
|---|---|
| Morning Train | 216 |
| Smell of Earth | 309 |
| Stone Wall | 274 |
(3 rows)
27 of the 30 songs received at least one like; the remaining 3 songs are here. EXISTS and NOT EXISTS split the same table into two parts: 27 + 3 = 30.