A SQL subquery is a query written inside another query, wrapped in parentheses. The inner query runs first, and the outer query uses its result. Use a subquery when you need an answer in order to ask your real question, such as "students whose GPA is above the average GPA".
The examples use the Northbridge University database in Port Alder, mainly the student (120 rows), department and instructor tables.
How do you write a subquery in the WHERE clause?
Put the inner query in parentheses where a value would go. If it returns a single value, you can compare it with >, = and the other operators. The average GPA is 2.45, so this finds the two final-year students with the highest GPA above that average:
SELECT first_name, last_name, gpa FROM student WHERE gpa > (SELECT AVG(gpa) FROM student) AND year = 4 ORDER BY gpa DESC, id LIMIT 2;
| first_name | last_name | gpa |
|---|---|---|
| Camila | Osei | 3.88 |
| Zara | Larsen | 3.85 |
You cannot write WHERE gpa > AVG(gpa) directly, because WHERE cannot use aggregates (see [WHERE vs HAVING](/blog/sql-where-vs-having)). The subquery works around that. Across all years, 46 students are above the average.
How does a subquery with IN work?
When the inner query returns a list of values, use IN. This finds final-year students in the Faculty of Engineering without knowing the department numbers:
SELECT first_name, last_name FROM student WHERE department_id IN (SELECT id FROM department WHERE faculty = 'Faculty of Engineering') AND year = 4 ORDER BY id LIMIT 4;
| first_name | last_name |
|---|---|
| Anika | Park |
| Camila | Osei |
| Rosa | Haddad |
| Lucas | García |
The inner query returns departments 2, 3 and 8. If the faculty gets a new department tomorrow, the outer query picks it up without any change.
What does EXISTS do in a subquery?
EXISTS asks "does the inner query return at least one row?". It returns true or false and ignores the column values. NOT EXISTS finds things that have no match:
SELECT name FROM department d WHERE NOT EXISTS (SELECT 1 FROM student s WHERE s.department_id = d.id);
| name |
|---|
| Data Science and Analytics |
The inner query uses d.id from the outer query. That makes it a correlated subquery, which is the next topic.
What is a correlated subquery?
A correlated subquery refers to a column of the outer query, so it is evaluated again for each outer row. This shows each student's GPA next to the average GPA of their own department:
SELECT s.first_name, s.last_name, s.gpa, (SELECT ROUND(AVG(x.gpa), 2) FROM student x WHERE x.department_id = s.department_id) AS dept_avg FROM student s WHERE s.id IN (1, 2, 4) ORDER BY s.id;
| first_name | last_name | gpa | dept_avg |
|---|---|---|---|
| Anika | Park | 3.65 | 2.80 |
| Anika | Rivera | 3.88 | 2.70 |
| Isabella | Popescu | 2.57 | 2.15 |
A subquery in the SELECT list must return exactly one value per row. Here each row gets the average of its own department, so the three numbers differ.
Subquery vs join: which one should you use?
Many questions can be answered both ways. Find the departments that have at least one fourth-year student:
SELECT d.name FROM department d WHERE d.id IN (SELECT department_id FROM student WHERE year = 4) ORDER BY d.id;
SELECT DISTINCT d.name FROM department d JOIN student s ON s.department_id = d.id WHERE s.year = 4 ORDER BY d.name;
Both return the same five departments: Software Engineering, Industrial Engineering, Business Administration, New Media and Communication, and Psychology. The join needs DISTINCT, because a department with several fourth-year students would otherwise repeat.
| Situation | Better choice |
|---|---|
| You only filter by the other table | Subquery with IN or EXISTS |
| You need columns from both tables in the result | Join |
| You need "has no match" | NOT EXISTS or LEFT JOIN ... IS NULL |
| You compare with an aggregate such as the average | Subquery |
For the join side, read [SQL joins explained](/blog/sql-join-types). Modern databases often run both forms in a similar way, so pick the one that is easier to read.
Why does NOT IN return nothing?
NOT IN has a trap: if the list contains even one NULL, the whole result is empty. Eight students have no advisor, so advisor_id contains NULL:
SELECT COUNT(*) FROM instructor WHERE id NOT IN (SELECT advisor_id FROM student);
This returns 0. Yet one instructor, Yuki Cohen, advises nobody. Filtering the NULL out of the list fixes it:
SELECT COUNT(*) FROM instructor WHERE id NOT IN (SELECT advisor_id FROM student WHERE advisor_id IS NOT NULL);
Now the answer is 1. Using NOT EXISTS avoids the problem entirely, which is why many people prefer it. More on this in [SQL NULL values](/blog/sql-null-values).
Why does SQL say a subquery returned more than one row?
A comparison like = or > expects one value. If the inner query returns several rows, you get an error:
SELECT first_name FROM student WHERE gpa = (SELECT gpa FROM student WHERE year = 4);
PostgreSQL answers:
Outputmore than one row returned by a subquery used as an expressionUse IN for a list, or reduce the subquery to one value with an aggregate such as MAX(gpa). With MAX, the query returns the students with the highest GPA: Noor García and Omar Kim.
What to read next
- Practice in your browser: [Subqueries](/learn/sql/subqueries-1) and [Correlated subqueries and EXISTS](/learn/sql/correlated-exists)
- Related post: [SQL joins explained](/blog/sql-join-types)
- Go further: [SQL CASE WHEN](/blog/sql-case-when)
- Browse the whole course: [SQL course](/courses/sql)
- #sql
- #subquery
- #exists
- #beginners