Nesting queries with subqueries
Sometimes the answer to one question is the input to another. "Which stations saw temps above 30°C?" and then "give me those stations' names." A subquery asks both in one statement: it's a complete SELECT nested inside another query, wrapped in parentheses. The database runs the inner query first and feeds its result to the outer one.
The code
SELECT name
FROM weather_stations
WHERE station_id IN (
SELECT station_id
FROM temperature_readings
WHERE temp_c > 30
);
Reading it piece by piece:
- The parentheses — everything inside is the subquery, a complete
SELECTthat could run on its own. - The inner query runs first: "which
station_ids recorded temps above 30°C?" Answer: (3). The outer query then reads asWHERE station_id IN (3). INis the workhorse for subqueries that return multiple rows: a row survives when its value appears in the subquery's result. (Comparison operators like>need a subquery that returns exactly one value.)
In practice
A data engineer uses this to filter rows by a condition computed from another table's data — without creating an intermediate table or pulling data into Python. Where a JOIN answers "combine," a subquery answers "filter by another table's answer": stations that hit extreme heat, customers who ordered this week, events after a deploy.
Python bridge: two pandas steps collapsed into one statement that runs inside the warehouse:
hot = readings[readings.temp_c > 30].station_id
stations[stations.station_id.isin(hot)]
Pandas' .isin(list) is exactly SQL's IN with a subquery — SQL just does both steps without shipping data out.
Further reading
Beginner's Guide to the SQL Subquery — LearnSQL
Try it
Practice question: using these sample tables, write a query that returns the names of all stations with at least one reading below 20°C. Use a subquery with IN.
| weather_stations | |||
|---|---|---|---|
| station_id | name | lat | lon |
| 1 | Princeton | 40.36 | -74.66 |
| 2 | Boulder | 40.02 | -105.27 |
| 3 | Houston | 29.76 | -95.37 |
| temperature_readings | ||
|---|---|---|
| station_id | temp_c | recorded_at |
| 1 | 24.5 | 06:00 |
| 2 | 19.2 | 06:00 |
| 3 | 33.8 | 06:00 |
| 1 | 25.1 | 07:00 |
| 3 | 34.2 | 07:00 |
Show answer
SELECT name
FROM weather_stations
WHERE station_id IN (
SELECT station_id
FROM temperature_readings
WHERE temp_c < 20
);
| name |
|---|
| Boulder |
Only Boulder's 19.2°C reading clears the bar — Princeton (24.5, 25.1) and Houston (33.8, 34.2) don't. One nice property: the subquery doesn't care that stations 1 and 3 appear twice in the readings — IN just needs the value present, so unlike a JOIN it can't multiply rows.