A query inside a query

Lesson 12 of 18 · SQL foundations

A subquery is a SELECT nested inside another statement. Here the inner query produces a set of shelf IDs, then the outer query selects books whose shelf ID belongs to that set:

SELECT title FROM books WHERE shelf_id IN (
  SELECT id FROM shelves WHERE label = 'Nature'
) ORDER BY id;

The inner result is 1; the outer result is Moss Atlas and River Notes. If no shelf matches, the inner set is empty and no book matches. A scalar subquery supplies a single value, such as an aggregate:

SELECT title, pages FROM books
WHERE pages > (SELECT AVG(pages) FROM books) ORDER BY id;

The average of known page counts is about 133.3, so Clay Roads is returned. NULL pages do not satisfy the comparison. For scalar subqueries make the one-value intent explicit; SQLite takes the first row if more are returned, whereas other engines may reject it. Subqueries and joins can express similar requests but have different duplicate and NULL behavior.

Chapter index · Course index