A subquery is a SELECT expression nested inside a larger SQL statement. Data-center inventory systems can use nested queries to find racks containing hot sensors, compare readings against a fleet average, and identify equipment with missing telemetry. After OSSQL.007: Aggregate Functions, learners combine aggregation with filtering and relationships.
Prerequisites and objectives
Complete OSSQL.006: Joins and the aggregate lesson. Install the SQLite command-line shell from SQLite downloads, or use a local SQLite GUI. No production database or network access is needed. By completion, learners can distinguish scalar, membership and correlated subqueries; use IN and EXISTS; explain NULL behavior and repair NOT IN; and execute and validate nested queries using a reproducible dataset.
1. Prepare the local laboratory
Open a terminal and run sqlite3 :memory: to create a temporary database. Enter the following statements, including semicolons. Rack C deliberately has no sensor; sensor 4 has no assigned rack. Temperatures are synthetic Celsius readings. All changes disappear when the session closes.
CREATE TABLE racks(id INTEGER PRIMARY KEY, name TEXT);CREATE TABLE sensors(id INTEGER PRIMARY KEY, rack_id INTEGER, temp REAL);INSERT INTO racks VALUES (1,'A'),(2,'B'),(3,'C');INSERT INTO sensors VALUES (1,1,24),(2,1,30),(3,2,36),(4,NULL,40);
Use .headers on and .mode column in the SQLite shell for readable results. These dot commands belong to the shell rather than SQL. Enter SELECT * FROM sensors; to check that four records exist.
2. Scalar subqueries
A scalar subquery supplies a single value to an expression. An aggregate without GROUP BY produces a single result row, making AVG suitable for comparison. First calculate the average independently, then use it in the outer WHERE filter. For more filtering basics, revisit OSSQL.003: WHERE.
SELECT AVG(temp) FROM sensors;SELECT id, temp FROM sensorsWHERE temp > (SELECT AVG(temp) FROM sensors)ORDER BY id;
Expected results: average 32.5; sensor 3 at 36.0 and sensor 4 at 40.0. The nested average includes all four readings, including the unassigned sensor. SQLite uses the first result row for a scalar subquery and NULL for no rows; other engines may reject multiple rows. Design scalar queries to guarantee one row rather than depending on engine-specific behavior.
3. Membership with IN
IN compares a value against the values returned by a one-column query. Multiple matching inner records do not multiply outer rows, unlike some joins. The following query identifies racks with at least one sensor at or above 30°C.
SELECT name FROM racksWHERE id IN (SELECT rack_id FROM sensors WHERE temp >= 30)ORDER BY id;
Expected rows: A and B. The inner query returns 1, 2 and NULL; the unassigned sensor does not establish a match with any rack ID.
4. Correlated queries and EXISTS
A correlated subquery references an outer-query column. Aliases r and s identify the outer rack and inner sensor respectively. EXISTS checks whether at least one qualifying inner row exists, regardless of the selected values. Logically, each outer rack is tested against its associated sensors; an optimizer may choose a different physical execution plan.
SELECT r.name FROM racks rWHERE EXISTS (SELECT 1 FROM sensors sWHERE s.rack_id = r.id AND s.temp >= 30)ORDER BY r.id;
Expected rows: A and B. A correlated scalar query can also report the maximum reading for every rack, including racks without observations.
SELECT r.name, (SELECT MAX(s.temp) FROM sensors sWHERE s.rack_id = r.id) AS max_tempFROM racks r ORDER BY r.id;
Expected rows: A | 30.0; B | 36.0; C | NULL. NULL means no qualifying non-NULL temperature, not zero degrees.
5. Missing telemetry and NULL
SQL uses three-valued logic: true, false and unknown. WHERE retains true only. NOT IN can evaluate to unknown when the inner list contains NULL and no equality match exists. Compare the following three statements.
SELECT name FROM racks WHERE id NOT IN(SELECT rack_id FROM sensors) ORDER BY id;SELECT name FROM racks WHERE id NOT IN(SELECT rack_id FROM sensors WHERE rack_id IS NOT NULL) ORDER BY id;SELECT r.name FROM racks r WHERE NOT EXISTS(SELECT 1 FROM sensors s WHERE s.rack_id = r.id) ORDER BY r.id;
Expected results in order: no rows; C; C. Filtering NULL explicitly repairs the membership query for non-null rack IDs. NOT EXISTS expresses the absence of a matching row directly. Avoid treating missing sensor associations as evidence of a physical outage; validate inventory records and the telemetry collection pipeline.
6. Practice, troubleshooting and answer key
A. Change the membership threshold to 35°C. Which rack matches? B. Explain why sensor 4 affects the global average but does not match a rack. C. Find the fault in NOT IN when unassigned sensors exist. D. Why does MAX for rack C return NULL? E. Remove the WHERE correlation in the EXISTS query and predict the result when any hot sensor exists.
Answers: A. B only. B. AVG operates on all non-NULL temperature readings; rack membership relies on rack_id. C. A NULL inner value can make a nonmatching comparison unknown; filter NULL or use NOT EXISTS. D. No associated reading exists. E. Every rack passes because the inner condition no longer depends on the outer rack. Restore the correlation to identify the intended rack.
If a query returns too many records, run the inner SELECT alone and inspect its results, verify aliases and predicates, and use explicit ORDER BY when comparing outputs. The lab uses temporary data only. All nine query results, including the threshold exercise, were executed against SQLite 3.46.1.
References and continuing study
Consult the SQLite expression reference for scalar subqueries, correlated expressions, IN and EXISTS. Review OSSQL.004: ORDER BY for reproducible row ordering. Subqueries express dependencies between data selections; always verify the expected result shape and treatment of missing values before using them in operational reports.
We volunteer daily to ensure the credibility of the information on our platform is Verifiably True.

Leave a Reply