SQL subqueries
A subquery returns values the outer query goes on working with.
Rules
- IN (SELECT …) for lists
- NOT IN finds what is missing
- Comparing with a single value: = (SELECT AVG …)
Your turn
Three problems on this topic. You can run the query first.
- 1 · Subqueries
- 2
- 3
List the names of all students without a grade entry.
students
| id | name | major | semester | city |
|---|---|---|---|---|
| 1 | Greta | Law | 1 | Zürich |
| 2 | Eva | Computing | 7 | Berlin |
| 3 | Jonas | Computing | 8 | Bern |
| 4 | Clara | Chemistry | 2 | Wien |
| 5 | Anna | Computing | 2 | Basel |
| 6 | Hannah | Business | 4 | Basel |
| 7 | Felix | Law | 1 | Bern |
grades
| student_id | course_id | grade |
|---|---|---|
| 1 | 2 | 3 |
| 6 | 4 | 4 |
| 2 | 3 | 1 |
| 1 | 4 | 2 |
| 4 | 1 | 2.7 |
| 2 | 4 | 3 |
| 5 | 3 | 2.3 |
| 2 | 1 | 1.7 |
| 3 | 1 | 2.3 |
| 7 | 2 | 2.7 |
+ − More tables: courses
courses
| id | title | credits | lecturer |
|---|---|---|---|
| 1 | Calculus | 3 | Meier |
| 2 | Databases | 3 | Meier |
| 3 | Statistics | 4 | Meier |
| 4 | Marketing | 4 | Weber |
SQL
Any equivalent query counts. It is also checked on data you can’t see.
Worked example
List the titles of all courses where a grade of 1 was given.
courses
| id | title | credits | lecturer |
|---|---|---|---|
| 1 | Law | 4 | Huber |
| 2 | Statistics | 5 | Keller |
| 3 | Calculus | 4 | Keller |
| 4 | Databases | 5 | Weber |
grades
| student_id | course_id | grade |
|---|---|---|
| 6 | 1 | 2.7 |
| 1 | 1 | 1 |
| 1 | 2 | 3 |
| 4 | 3 | 1 |
| 6 | 2 | 3 |
| 2 | 1 | 2.3 |
| 4 | 4 | 4 |
| 5 | 1 | 2.3 |
| 7 | 2 | 2.3 |
| 5 | 2 | 1.3 |
| 6 | 4 | 2.3 |
| 3 | 2 | 1 |
+ − More tables: students
students
| id | name | major | semester | city |
|---|---|---|---|---|
| 1 | Eva | Computing | 8 | Zürich |
| 2 | Lena | Law | 7 | Basel |
| 3 | Greta | Law | 1 | Berlin |
| 4 | David | Computing | 8 | Bern |
| 5 | Max | Business | 5 | Wien |
| 6 | Clara | Business | 5 | Wien |
| 7 | Felix | Chemistry | 6 | Zürich |
Worked solution
SELECT title FROM courses WHERE id IN (SELECT course_id FROM grades WHERE grade = 1)
Result on the sample data:
title
Law
Statistics
Calculus
Typical mistake: The subquery returns a list of ids.
Common questions
Can this be done with a JOIN?
Often yes, but subqueries are sometimes easier to read.
