Contents Index About this chapter Single-row and multiple-row subqueries

ASA Getting Started
  Selecting Data Using Subqueries

Introduction


Subqueries use the results of one query as part of another query. This section illustrates a situation where subqueries can be used by building a query that lists order items for products that are low in stock.

There are two queries involved in producing this list. This section first describes them separately, and then shows the single query that produces the same result.

List all products for which there are less than 20 items in stock

List all order items for wool caps

This two-step process of identifying items low in stock and identifying orders for those items can be combined into a single query using subqueries.

List all order items for items that are low in stock

The subquery in the statement is the phrase enclosed in parentheses:

(   SELECT id
    FROM product
    WHERE quantity < 20 )

The subquery makes a list of all values in the id column in the product table, satisfying the WHERE clause search condition.

The subquery returns a set of rows, but only a single column. The IN keyword treats each value as a member of a set and tests whether each row in the main query is a member of the set.


Contents Index About this chapter Single-row and multiple-row subqueries