Presentation is loading. Please wait.

Presentation is loading. Please wait.

Subqueries Steve Perry 1.

Similar presentations


Presentation on theme: "Subqueries Steve Perry 1."— Presentation transcript:

1 Subqueries Steve Perry Email: steveperrymail@yahoo.com 1

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 2

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; 3

4 Example - Using a Subquery SELECT title, price FROM book WHERE price IN (SELECT price FROM book WHERE title = 'Straight Talk About Computers'); 4

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 5

6 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

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') 7

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') 8

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'); 9

10 Exercise List the author’s name who appear as the third author on a book. 10

11 Answer SELECT lastname, firstname FROM author WHERE ssn IN (SELECT ssn FROM bookauthor WHERE author_order = 3); 11

12 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

13 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

14 Last Slide 14


Download ppt "Subqueries Steve Perry 1."

Similar presentations


Ads by Google