Understanding Subqueries

In this section, I’ll define some terms and introduce subqueries by giving an example of a SELECT statement that contains a simple subquery. In subsequent sections, I’ll explain the types of subqueries and their syntax and semantics.

Suppose that you want to list the names of the publishers of biographies. The naive approach is to write two queries: one query to retrieve the IDs of all the biography publishers (Listing 8.1 and Figure 8.1), and a second query that uses the first query’s result to list the publisher names (Listing 8.2 and Figure 8.2).

A better way is to use an inner join (Listing 8.3 and Figure 8.3); see “Creating an Inner Join with INNER JOIN” in Chapter 7.

Another alternative is to use a subquery (

Get SQL: Visual QuickStart Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.