Subqueries
Based on Introduction to Oracle: SQL and PL/SQL Problem Solution to question Requires a two step query Can use only one SQL statement Example – Who has a salary greater than Jones’ salary? 2/24/05 Based on Introduction to Oracle: SQL and PL/SQL
Based on Introduction to Oracle: SQL and PL/SQL Use a Subquery Main Query Which employees have a salary greater than Jones’ salary? Subquery What is Jones’ salary? 2/24/05 Based on Introduction to Oracle: SQL and PL/SQL
Based on Introduction to Oracle: SQL and PL/SQL SELECT select_list FROM table WHERE expr operator (SELECT select_list FROM table) Subquery (bottom) executed first Outer query (top) executed last Addition SQL clauses can be added Inner & Outer queries 2/24/05 Based on Introduction to Oracle: SQL and PL/SQL
Based on Introduction to Oracle: SQL and PL/SQL Types of Subqueries Single-row subquery Multiple-row subquery Multiple-column subquery Main query Subquery CLERK Main query returns CLERK MANAGER Subquery Main query returns Subquery CLERK 7900 MANAGER 7698 2/24/05 Based on Introduction to Oracle: SQL and PL/SQL
Single-Row Subqueries Return only one row to Main Query Use single-row comparison operators =, >, >=, <, <=, and <> 2/24/05 Based on Introduction to Oracle: SQL and PL/SQL
Based on Introduction to Oracle: SQL and PL/SQL Example Find the employee names and jobs for employees whose salary is greater than employee number 7876 and who have the same job as employee number 7369. 2/24/05 Based on Introduction to Oracle: SQL and PL/SQL
Multiple-Row Subqueries Return more than one row Use multiple-row comparison operators IN, equal to any member in the list ANY ALL 2/24/05 Based on Introduction to Oracle: SQL and PL/SQL
Based on Introduction to Oracle: SQL and PL/SQL Example Find the employee name, salary, and department number for the employee who has the minimum salary in each department. 2/24/05 Based on Introduction to Oracle: SQL and PL/SQL