How Do Subqueries Work?

Subqueries return results from an inner query to an outer clause and come in two basic flavors: simple and correlated. The first is evaluated (conceptually) from the inside out. That is, the outer query takes an action based on the results of the inner query. You can think of the second type of subquery—the correlated subquery—as working the opposite way: The outer SQL statement provides the values for the inner subquery to use in its evaluation. Then the subquery results are passed back to the outer query. You use a correlated subquery when you need to look at the data row by row.

Figure 8.2 compares a simple and a correlated subquery that produce identical results. Both find the names of the publishers who produce business ...

Get Practical SQL Handbook, The: Using SQL Variants, Fourth Edition 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.