Upload
stephanie-richards
View
217
Download
0
Embed Size (px)
Citation preview
2
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
3
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;
4
Example - Using a Subquery
• SELECT title, priceFROM bookWHERE price IN
(SELECT price FROM book WHERE title = 'Straight Talk About Computers');
5
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
6
Example - Two Ways
• SELECT name, lastname, firstnameFROM publisher JOIN author USING (city);
• SELECT nameFROM publisherWHERE city IN
(SELECT city FROM author);
7
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')
8
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')
9
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');
10
Exercise
• List the author’s name who appear as the third author on a book.
11
Answer
• SELECT lastname, firstnameFROM authorWHERE ssn IN
(SELECT ssn FROM bookauthor WHERE author_order = 3);
12
Using Aggregate Functions
• Aggregate Functions always return a single value for a set of rows
• SELECT title, ytd_sales * price, advanceFROM bookWHERE ytd_sales * price >
(SELECT MAX(advance) FROM book);
13
Insert, Update, and Delete
• UPDATE bookSET price = price * 2WHERE pub_id IN
(SELECT pub_id FROM publisher WHERE name = 'New Age Books');
14
Last Slide