Subquery
Also Subqueries
A subquery is a complete SELECT query in parentheses written where SQL expects a table, standing for the table that the inner query produces.
Know these firstSQL Query Structure
Properties#
- How to read a query with subqueries: understand the table created by each subquery, then read the outer query as if that table were stored under its name.
- Typical use: per-group values back to rows. Grouping aggregates per column, so “for each year, the movie with the highest score” cannot be written with
GROUP BYalone. Compute the aggregate per group in a subquery and join it back to the original table on the group key and the aggregate value (exam WS 23/24, Task 3.3). Ties yield several rows per group. - Typical use: filter groups, then join. A subquery with
GROUP BY … HAVING …yields the keys of qualifying groups, which are joined with other tables (retake WS 23/24, Task 2.1.2). - Column names matter for
NATURAL JOIN: a natural join with a subquery uses every column name the two share. Naming the aggregateMAX(score) AS scoremakes the join match onscoreas well, which is exactly what the argmax query needs; naming itmax_scorewould join onyearonly.
Example#
Sources#
- Slides 05, p. 33 (definition, example), p. 34 (explanation), p. 29 (limits of GROUP BY)
- DBIS_VL05 > Subqueries, DBIS_VL05 > Grouping
- Exams: DBIS Exam WS2324 (not published) (Task 3.3), DBIS Exam WS2324-2 (not published) (Tasks 2.1, 3.3)