Subqueries
Steve Perry
Email: [email protected]
1
Subqueries
• A Subquery nests a SELECT statement in the WHERE clause of another
SELECT, INSERT, UPDATE, or DELETE statement
• A Subquery’s Outer SELECT operates on rows returned from the Inner SELECT
• The Inner and Outer SELECT statements may refer to the same table
2
Example - without a Subquery
• Find all the books that have the same price as Straight Talk About Computers
SELECT price
FROM book
WHERE title = 'Straight Talk About Computers';
SELECT title, price
FROM book
WHERE price = 19.99;
3
Example - Using a Subquery
• SELECT title, price
FROM book
WHERE price IN
(SELECT price
FROM book
WHERE title = 'Straight Talk About Computers');
4
Joins vs. Subqueries
• Join
– Advantages: Can return results from all tables
– Disadvantages: May need two statements to get desired results
• Subquery
– Advantages: Can compare aggregates to other values. Can get information in a single
statement
– Disadvantages: Can only return results from the Outer Select statement
5
Example - Two Ways
• SELECT name, lastname, firstname
FROM publisher
JOIN author USING (city);
• SELECT name
FROM publisher
WHERE city IN
(SELECT city FROM author);
6
The IN operator
• In a simple SELECT statement you can avoid specifying many OR’s by using an
IN list
– Instead of…
SELECT lastname, firstname, state
FROM author
WHERE state='TN' or state='KS' or state='MD'
– Do …
SELECT lastname, firstname, state
FROM author
WHERE state IN ('TN', 'KS', 'MD')
7
The IN operator with a Subquery
• Use the ‘IN’ operator when the results of the inner query will have 0, one, or more
values
• Once the inner query returns results, the outer query will make use of them
SELECT lastname, firstname, state
FROM author
WHERE state IN
(SELECT state
FROM author
WHERE state != 'CA') 8
Conceptually...
• Inner Query-
SELECT state
FROM author
WHERE state != 'CA'
• Outer Query-
SELECT name
FROM author
WHERE state IN ('KS', 'TN', 'OR', 'MI', 'IN', 'MD', 'UT');
9
Exercise
• List the author’s name who appear as the third author on a book.
10
Answer
• SELECT lastname, firstname
FROM author
WHERE ssn IN
(SELECT ssn
FROM bookauthor
WHERE author_order = 3);
11
Using Aggregate Functions
• Aggregate Functions always return a single value for a set of rows
• SELECT title, ytd_sales * price, advance
FROM book
WHERE ytd_sales * price >
(SELECT MAX(advance)
FROM book);
12
Insert, Update, and Delete
• UPDATE book
SET price = price * 2
WHERE pub_id IN
(SELECT pub_id
FROM publisher
WHERE name = 'New Age Books');
13
Last Slide
14