Lesson 28 of 30
93%
Subqueries
A subquery is a SELECT inside another SQL statement.
The inner query runs first. The outer query uses that answer.
In WHERE
Who scored more than the average?
sql
Result
| student_id | points |
|---|---|
| 1 | 95 |
1 row
With IN
sql
Result
| name |
|---|
| Ada |
| Sam |
2 rows
In FROM
You can treat a subquery as a tiny table. Give it a name.
sql
Result
| city | avg_age |
|---|---|
| London | 12.0000 |
| Taipei | 13.0000 |
| Cairo | 12.0000 |
3 rows
Join or subquery?
Many subqueries can be written as JOINs.
Pick the one you can read next month.
Tip: Run the inner SELECT by itself first. Check that result. Then wrap it.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.