…
…
SQL and Database Fundamentals · Lesson 20 / 41 · Subqueries
PreviewIn this lesson you will
=/> or IN based on whether the inner query returns one value or a list, and recognize the NOT IN trap with NULLYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
The scholarship committee wants three lists: students above the overall GPA, students in the Faculty of Engineering, and students who took Databases I. For each question you first need to find a number or a list, then use it in the main query. The committee also gives a warning: last year someone typed "2.45" into a query by hand, and when the grades changed, the list quietly came out wrong.
The committee's first question looks simple: "Which students have a GPA above the overall average?" With what you have learned so far, you can solve it in two steps. First you find the overall average:
SELECT ROUND(AVG(gpa), 2) FROM student;
| round |
|---|
| 2.45 |
Then you type that number into a second query by hand:
SELECT COUNT(*) FROM student WHERE gpa > 2.45;
| count |
|---|
| 46 |
Today the result is right: 46 students. But this method is fragile. At the end of the term, grades are entered, GPAs change, and the overall average becomes 2.51, while your query still compares against 2.45. The query does not raise an error; it just returns the wrong list. On top of that, 2.45 is a rounded number: the real average is 2.4509... and keeps going. A student right at the border can land on the wrong side when compared with the rounded number. Every number you carry by hand is a chance for an error between two queries.
In this lesson you will:
> or IN.A subquery is a query placed inside another query, in parentheses. PostgreSQL runs the part inside the parentheses first, puts the result in place of the parentheses, and then runs the outer query. In other words, the database does the two steps you did by hand, and it recalculates the number every time. The query on the outside is called the outer query, and the one in parentheses is the inner query.
The safest way to write a subquery is also two steps. First you write the inner query on its own, run it, and look at the value it returns: is it a reasonable number like 2.45? Then you copy that query as it is and move it, in parentheses, into the WHERE of the outer query. This habit gives you two things: if the inner query has a mistake, you catch it while it is small, and you know exactly what the outer query is comparing against.
Example 1 (case): Students above the overall average
SELECT student_no, first_name, gpa FROM student WHERE gpa > (SELECT AVG(gpa) FROM student) ORDER BY gpa DESC;
| student_no | first_name | gpa |
|---|---|---|
| 202407009 | Omar | 4 |
| 202502007 | Noor | 4 |
| 202405001 | Anika | 3.88 |
| 202302001 | Camila | 3.88 |
| 202304004 | Zara | 3.85 |
(first 5 of 46 rows)
The same 46 students as the hand-written query came back, but this time the number is calculated inside the query. There is no ROUND in the inner query either: the comparison uses the real, unrounded average. When grades change, you rerun the query without touching it, and the list is up to date. The 32 students whose GPA is NULL (mostly first-years whose grades have not been entered yet) do not appear in the list; remember from lesson 7 that a comparison with NULL is never true.
Now try the two-step process yourself. The cell below holds the first five rows of Example 1. First run only the part inside the parentheses, SELECT AVG(gpa) FROM student, as the cell's only query, and look at the number. Then bring the query back, add AND year = 4 to the WHERE, and delete the LIMIT 5 line: how many fourth-year students are above the overall average?
Try it now· not graded; doesn't affect progress
On its own, the inner query returns 2.4509...: the unrounded overall average. With the fourth-year condition you get 13 rows: it starts with Camila at 3.88 and ends with Lucas at 2.55. Notice that the year = 4 condition went into the WHERE of the outer query; the inner query still calculates the average of all students. If you wanted "fourth-years above the fourth-year average," you would have to put the condition in the inner query too.
A subquery used with > or = makes a promise: it will return exactly one row and one column. This is called a single-value subquery (a scalar subquery); the outer query uses it like a number. Aggregate functions keep this promise most easily: AVG, MAX, MIN and COUNT written without GROUP BY return a single row no matter how many rows there are.
The committee's second request is "the student with the highest GPA." Here too, think about the inner query first: what is the highest GPA? SELECT MAX(gpa) FROM student gives it. Then you ask for "the students whose GPA equals that number."
Example 2 (case): Students with the highest GPA
SELECT student_no, first_name, last_name, gpa FROM student WHERE gpa = (SELECT MAX(gpa) FROM student);
| student_no | first_name | last_name | gpa |
|---|---|---|---|
| 202502007 | Noor | García | 4 |
| 202407009 | Omar | Kim | 4 |
(2 rows)
Two students scored 4.00, and both came back. In lesson 6 you found "the highest" by sorting and taking the first row. Would that approach give the same result here?
Does this query give the same result as the subquery version in Example 2?
SELECT student_no, first_name, last_name, gpa FROM student ORDER BY gpa DESC NULLS LAST LIMIT 1;
With "the highest," you do not know how many people share that value. A subquery answers this question correctly: "What is the highest value, and who is equal to it?" LIMIT 1 answers a different question, "Who comes first after sorting?", and silently drops ties.
A query with a subquery looks crowded at first glance. What makes it easier to read is writing the inner query on separate lines and indenting it: the parenthesis opens, the inner query sits on its own lines, the parenthesis closes, and the outer query continues where it left off. Put the lines of Example 1 in order using this layout.
Put the query that returns students above the overall average, highest to lowest, in order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The committee's third request: "Students of the Faculty of Engineering." The student table has no faculty name, only department_id. So you first need to find which departments belong to the Faculty of Engineering. Again, start by running the inner query on its own:
SELECT id FROM department WHERE faculty = 'Faculty of Engineering';
| id |
|---|
| 2 |
| 3 |
| 8 |
(3 rows)
This time the inner query returned not a single number but a list of three rows. What happens if you put it in with = out of habit?
The inner query returns 2, 3 and 8. What does this query do?
SELECT first_name FROM student WHERE department_id = ( SELECT id FROM department WHERE faculty = 'Faculty of Engineering' );
PostgreSQL gives this error:
OutputERROR: more than one row returned by a subquery used as an expressionAs you learned in lesson 9, read the error message piece by piece: "more than one row returned", "by a subquery", "used as an expression" (used like a single value). The message states the problem exactly: a list arrived where a single value was expected. The fix is IN, which you know from lesson 5. Just as you can write department_id IN (2, 3, 8), you can get the list from a subquery.
Example 3 (case): Students of the Faculty of Engineering
SELECT student_no, first_name, last_name, department_id FROM student WHERE department_id IN ( SELECT id FROM department WHERE faculty = 'Faculty of Engineering' ) ORDER BY student_no;
| student_no | first_name | last_name | department_id |
|---|---|---|---|
| 202302001 | Camila | Osei | 2 |
| 202302002 | Rosa | Haddad | 2 |
| 202302003 | Pablo | Müller | 2 |
| 202302004 | Aisha | Nguyen | 2 |
| 202303001 | Anika | Park | 3 |
(first 5 of 32 rows)
A subquery used with IN has a rule too: it must return a single column. The number of rows is free; it can be one, three or a hundred. The benefit of taking the list from a subquery instead of typing it is the same as before: if a new department is added to the faculty tomorrow, the query covers it automatically. Data Science and Analytics (8) is in the list but has no students; that is why IN returned only the students of departments 2 and 3.
A single-value subquery does not always return a number. If you ask for the average of Data Science and Analytics (8), which has no students, AVG finds no rows to calculate and returns NULL. What happens when this NULL reaches the outer query?
Data Science and Analytics (department_id = 8) has no students. How many rows does this query return? (Of the 120 students, 88 have a GPA.)
SELECT first_name, gpa FROM student WHERE gpa > ( SELECT AVG(gpa) FROM student WHERE department_id = 8 );
The result is 0 rows, and there is no error. Reading this result as "nobody is high enough" would be wrong: there was no value to compare against. If a query with a subquery unexpectedly comes back empty, run the inner query on its own; if you see NULL, you know the problem is in the inner query, not the outer one.
The committee's last request: "Students who took Databases I (CPR103)." This information is spread over four tables: a student is linked to an offering in enrollment, an offering is linked to a course in course_offering, and a course has a code in the course table. In lesson 17 you learned to build this chain with JOIN. You can put the same chain inside the inner query and select only the students in the outer query.
Example 4 (case): Students who took Databases I, with IN
SELECT student_no, first_name, last_name FROM student WHERE id IN ( SELECT e.student_id FROM enrollment e JOIN course_offering o ON o.id = e.offering_id JOIN course c ON c.id = o.course_id WHERE c.code = 'CPR103' ) ORDER BY student_no;
| student_no | first_name | last_name |
|---|---|---|
| 202501001 | Kenji | Park |
| 202501003 | Omar | Nguyen |
| 202501004 | Ayesha | Kowalski |
| 202501005 | Diego | Rossi |
| 202501006 | Diego | Haddad |
(first 5 of 12 rows)
If you ask the same question with a direct four-table JOIN, you get 15 rows, not 12. The difference is the row multiplication from lesson 18: three students took the course in both Fall 2025 and Fall 2026, so they have two rows in enrollment, and the JOIN returns them twice each. IN only asks each outer row "is this student's number in the list?"; even if a number appears twice in the list, the student comes back once. In the cell below the two queries sit one under the other. The cell shows only the result of the last query, so you see the JOIN version.
Try it now· not graded; doesn't affect progress
In the sorted result, Omar Nguyen, Diego Haddad and Liam Johansson each appear twice. When you write SELECT DISTINCT s.student_no, ..., the repeats disappear and you are back to 12 rows. Both ways can reach the right result; which one you choose depends on the question. For "who?", that is, when you only need the rows of one table, IN is natural and carries no multiplication risk. When the result also needs columns from the other table, for example the name of the course or the grade next to each student, you need JOIN, because the columns of a subquery are not carried to the outer query; IN only says "is it there or not."
The opposite of IN is NOT IN: it returns the rows that are not in the subquery's list. The committee is also curious about advising load: is there an instructor who advises no students at all? The first query that comes to mind is this:
Example 5 (case): Instructors who advise no one
SELECT first_name, last_name FROM instructor WHERE id NOT IN (SELECT advisor_id FROM student);
Result: 0 rows. No error.
In lesson 16 you solved the same question with LEFT JOIN and found Yuki Cohen. Why is the result empty here? The 8 students with no advisor assigned have a NULL advisor_id, and those NULLs are in the inner query's list too. For each instructor, NOT IN asks "is this id different from every value in the list?" If the list is, for example, (1, 4, 7, ..., NULL), the answer for Yuki Cohen goes like this: not equal to 1, not equal to 4 ... and equal to NULL? Unknown. In the three-valued logic of lesson 7, one "unknown" makes the whole answer "unknown": 5 NOT IN (1, 2, NULL) is not true, it is unknown. And unknown does not pass WHERE. As a result, no rows come back.
If the subquery's result contains a single NULL, how many rows does WHERE id NOT IN (subquery) return?
The danger of this trap is that it is silent: the query runs, you see 0 rows, and you write a report saying "nobody is without advisees." The fix is to filter out the NULLs in the inner query:
SELECT first_name, last_name FROM instructor WHERE id NOT IN ( SELECT advisor_id FROM student WHERE advisor_id IS NOT NULL );
| first_name | last_name |
|---|---|
| Yuki | Cohen |
(1 row)
The trap is set only if the inner query's column can contain NULL. In the question "courses that were never offered," course_offering.course_id is a column that cannot be left empty, so NOT IN works safely:
SELECT code, name FROM course WHERE id NOT IN (SELECT course_id FROM course_offering);
| code | name |
|---|---|
| NMC203 | Social Media Analytics |
(1 row)
The rule is simple: when you write NOT IN, look at the inner query's column; if it can be NULL, add IS NOT NULL. In lesson 21 you will see another way that NULL never affects: NOT EXISTS.
Since a single-value subquery behaves like a number, it can go anywhere you can write a number, and that includes the SELECT list. The committee wants to see, for the fourth-years, how far each student is from the overall average.
Example 6 (case): Difference from the overall average
SELECT first_name, gpa, ROUND(gpa - (SELECT AVG(gpa) FROM student), 2) AS diff FROM student WHERE year = 4 ORDER BY diff DESC;
| first_name | gpa | diff |
|---|---|---|
| Camila | 3.88 | 1.43 |
| Zara | 3.85 | 1.4 |
| Pablo | 3.77 | 1.32 |
| Anika | 3.65 | 1.2 |
(first 4 of 21 rows)
The subquery gives the same value (the overall average) in every row; it is subtracted from each student's GPA. A positive difference shows above the average, a negative one below. A subquery in SELECT must also return a single value; if it returns a list, you get the same "more than one row" error. Now match the four committee questions with the right form.
Match each question with the subquery form that answers it.
For each row, pick its match from the list, then check.
A subquery works the same way in every database. Look at the database of the Earbud music app (earbud.sql) that you will use in the last exercise. Two tables are enough here: artist(id, name, genre, city) holds 8 artists and song(id, title, artist_id, duration_sec, release_year) holds 30 songs. duration_sec is the length of a song in seconds, and the average length of the 30 songs is about 226.9 seconds.
Example 7 (outside the case): Songs longer than average, and songs by pop artists
SELECT title, duration_sec FROM song WHERE duration_sec > (SELECT AVG(duration_sec) FROM song) ORDER BY duration_sec DESC;
| title | duration_sec |
|---|---|
| Under the Lighthouse | 318 |
| Smell of Earth | 309 |
| Prairie Road | 302 |
| Quiet Harbor | 287 |
| Stone Wall | 274 |
(first 5 of 13 rows)
Now a subquery that returns a list, for "songs by pop artists": first SELECT id FROM artist WHERE genre = 'pop' returns 1 and 8 on its own (Salt Pier and Purple Tortoise), then you place it with IN.
SELECT title, duration_sec FROM song WHERE artist_id IN (SELECT id FROM artist WHERE genre = 'pop') ORDER BY title;
| title | duration_sec |
|---|---|
| Cloud Chaser | 222 |
| Coffee Stain | 187 |
| Downhill | 199 |
| Morning Train | 216 |
| Old Record Shop | 229 |
(first 5 of 8 rows)
What you did in the university database, you did here too: first you asked the small question (what is the average length, who are the pop artists), then you placed its answer inside the big question.
A subquery also works in the WHERE of a grouped query. Because WHERE runs before grouping, the students above the average are selected first, then counted by year.
SELECT year, COUNT(*) AS students FROM student WHERE gpa > (SELECT AVG(gpa) FROM student) GROUP BY year ORDER BY year;
| year | students |
|---|---|
| 2 | 19 |
| 3 | 14 |
| 4 | 13 |
(3 rows)
The total is 19 + 14 + 13 = 46: the same students as in Example 1. First-years are not in the list, because their grades have not been entered yet and their GPAs are NULL.
The list the committee cares about most: students with a scholarship who are below the overall average. The condition is added to an existing condition with AND; the subquery works on its own as usual.
SELECT first_name, last_name, gpa FROM student WHERE has_scholarship gpa < ( (gpa) student) gpa;
Using NOT IN with a subquery that can contain NULL.
OutputSELECT first_name, last_name FROM instructor
WHERE id NOT IN (SELECT advisor_id FROM student); -- 0 rowsThe subquery's result contains the NULL values of students who have no advisor; so for every instructor the answer is "unknown" and no rows come back. There is no error either, which makes it hard to notice. Add WHERE advisor_id IS NOT NULL to the subquery; the result then shows Yuki Cohen, who advises no one. When subqueries start to nest and grow long, readability drops; in lesson 23 you will see the CTE, which lets you name the steps and write them in order.
=, > and use inside SELECT need a single value (one row, one column); a subquery that returns a list is used with IN. = (SELECT MAX(...)) also returns ties, LIMIT 1 does not; if the inner query returns NULL, the comparison returns no rows.IS NOT NULL.Next lesson: You will use a subquery in FROM like a table, write subqueries that rerun for each row, and ask "is there or not" with EXISTS.
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.
| first_name | last_name | gpa |
|---|---|---|
| Adaeze | Álvarez | 0.14 |
| Nikolai | Haddad | 0.59 |
| Maya | Hassan | 0.92 |
| André | Costa | 1.05 |
| Ivan | Park | 1.31 |
(first 5 of 14 rows)