Study Vault Search notes, aliases and full text
Graph
ConceptDBISAI-written · not yet proofread

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 BY alone. 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 aggregate MAX(score) AS score makes the join match on score as well, which is exactly what the argmax query needs; naming it max_score would join on year only.

Example#

Sources#

Search

Type In
↑ ↓ move ↵ open ⇥ next section Ctrl↵ results page Prefix # to search text only