Subquery Examples

Using subqueries saves you steps. For example, if you want to find all books that are the same price as Straight Talk About Computers, you can perform the task in two steps (or use a subquery). First, find the price of Straight Talk:

SELECT price
FROM titles
WHERE title = 'Straight Talk About Computers'

price
---------
    19.99

(1 row(s) affected)

Now use the result (the price) in a second query to find all books that cost the same as Straight Talk:

SELECT title, price
FROM titles
WHERE price = $19.99
title
price
---------------------------------------------
-------
The Busy Executive's Database Guide
19.99
Straight Talk About Computers
19.99
Silicon Valley Gastronomic Treats
19.99
Prolonged Data Deprivation: Four Case Studies
19.99


(4 row(s) affected)



By using a subquery, you can solve the problem with a single statement:

SELECT title, price
FROM titles
WHERE price = 
    (SELECT price
    FROM titles
    WHERE title = 'Straight Talk About Computers')