Arman Pouyaei Start a conversation
Lesson 7  ·  Oct 12, 2026
Data Engineering Fundamentals

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:

  1. The parentheses — everything inside is the subquery, a complete SELECT that could run on its own.
  2. The inner query runs first: "which station_ids recorded temps above 30°C?" Answer: (3). The outer query then reads as WHERE station_id IN (3).
  3. IN is 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_idnamelatlon
1Princeton40.36-74.66
2Boulder40.02-105.27
3Houston29.76-95.37
temperature_readings
station_idtemp_crecorded_at
124.506:00
219.206:00
333.806:00
125.107:00
334.207: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.

← All posts