SlideShare une entreprise Scribd logo
1  sur  20
Télécharger pour lire hors ligne
Oracle OCP 考试系列培训
                之
         1Z0-007 Lesson6
                   www.OracleOnLinux.cn




6-1   Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
6
Using Subqueries to Solve Queries




 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Objectives


      After completing this lesson, you should be able to do
      the following:
       • Define subqueries
       • Describe the types of problems that subqueries
           can solve
       • List the types of subqueries
       • Write single-row and multiple-row subqueries




6-3          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Using a Subquery
                          to Solve a Problem

      Who has a salary greater than Abel’s?
                                    Abel’

      Main query:


                    Which employees have salaries greater
                    than Abel’s salary?
                         Abel’

                  Subquery:


                                  What is Abel’s salary?
                                          Abel’




6-4          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Subquery Syntax


      SELECT       select_list
      FROM         table
      WHERE        expr operator
                               (SELECT                     select_list
                               FROM                        table);

      •   The subquery (inner query) executes once before
          the main query (outer query).
      •   The result of the subquery is used by the main
          query.




6-5            Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Using a Subquery


      SELECT    last_name
      FROM      employees    11000
      WHERE     salary >
                         (SELECT salary
                          FROM     employees
                          WHERE last_name = 'Abel');




6-6            Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Guidelines for Using Subqueries


      •   Enclose subqueries in parentheses.
      •   Place subqueries on the right side of the
          comparison condition.
      •   The ORDER BY clause in the subquery is not
          needed unless you are performing Top-N analysis.
      •   Use single-row operators with single-row
          subqueries, and use multiple-row operators with
          multiple-row subqueries.




6-7         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Types of Subqueries


      •   Single-row subquery
             Main query
                                          returns
                    Subquery                                  ST_CLERK

      •   Multiple-row subquery
             Main query
                                          returns             ST_CLERK
                    Subquery
                                                              SA_MAN




6-8         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Single-Row Subqueries


      •   Return only one row
      •   Use single-row comparison operators
                    Operator      Meaning
                      =           Equal to
                       >          Greater than
                       >=         Greater than or equal to
                       <          Less than
                       <=         Less than or equal to
                       <>         Not equal to




6-9         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Executing Single-Row Subqueries


       SELECT last_name, job_id, salary
       FROM   employees
       WHERE job_id =                 ST_CLERK
                        (SELECT job_id
                         FROM   employees
                         WHERE employee_id = 141)
       AND    salary >                   2600
                        (SELECT salary
                         FROM   employees
                         WHERE employee_id = 143);




6-10         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Using Group Functions in a Subquery


       SELECT    last_name, job_id, salary
       FROM      employees             2100
       WHERE     salary =
                           (SELECT MIN(salary)
                            FROM   employees);




6-11            Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
The HAVING Clause with Subqueries


       •   The Oracle server executes subqueries first.
       •   The Oracle server returns results into the HAVING
           clause of the main query.
       SELECT     department_id, MIN(salary)
       FROM       employees
       GROUP BY   department_id            2100
       HAVING     MIN(salary) >
                                (SELECT MIN(salary)
                                 FROM   employees
                                 WHERE department_id = 50);




6-12         Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
What Is Wrong with This Statement?


       SELECT    employee_id, last_name
       FROM      employees
       WHERE     salary =
                           (SELECT   MIN(salary)
                            FROM     employees
                            GROUP BY department_id);


       ERROR at line 4:
       ORA-01427: single-row subquery returns more than
       one row


           Single-row operator with multiple-row subquery



6-13            Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Will This Statement Return Rows?


       SELECT    last_name, job_id
       FROM      employees
       WHERE     job_id =
                           (SELECT job_id
                            FROM   employees
                            WHERE last_name = 'Haas');

       no rows selected


                           Subquery returns no values.




6-14            Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Multiple-Row Subqueries


       •   Return more than one row
       •   Use multiple-row comparison operators

           Operator         Meaning
           IN               Equal to any member in the list
           ANY              Compare value to each value returned by the
                            subquery
           ALL              Compare value to every value returned by
                            the subquery




6-15             Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Using the ANY Operator
                    in Multiple-Row Subqueries

       SELECT    employee_id, last_name, job_id, salary
       FROM      employees    9000, 6000, 4200
       WHERE     salary < ANY
                              (SELECT salary
                               FROM          employees
                               WHERE job_id = 'IT_PROG')
       AND       job_id <> 'IT_PROG';




       …



6-16            Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Using the ALL Operator
                    in Multiple-Row Subqueries

       SELECT    employee_id, last_name, job_id, salary
       FROM      employees    9000, 6000, 4200
       WHERE     salary < ALL
                              (SELECT salary
                               FROM          employees
                               WHERE job_id = 'IT_PROG')
       AND       job_id <> 'IT_PROG';




6-17            Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Null Values in a Subquery

       SELECT   emp.last_name
       FROM     employees emp
       WHERE    emp.employee_id NOT IN
                                    (SELECT mgr.manager_id
                                     FROM   employees mgr);

       no rows selected

       SELECT emp.last_name
       FROM   employees emp
       WHERE emp.employee_id NOT IN
                                 (SELECT mgr.manager_id
                                  FROM   employees mgr
                                  WHERE manager_id is not null);

   子查询中:凡是返回结果包含NULL值,其结果一定为NULL


6-18            Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Summary


       In this lesson, you should have learned how to:
        • Identify when a subquery can help solve a
            question
        • Write subqueries when a query is based on
            unknown values
       SELECT       select_list
       FROM         table
       WHERE        expr operator
                                (SELECT select_list
                                FROM    table);




6-19            Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
Practice 6: Overview


       This practice covers the following topics:
        • Creating subqueries to query values based on
           unknown criteria
        • Using subqueries to find out which values exist in
           one set of data and not in another

            – P59 Q92
            – P61 Q98 ,P62 Q99
            – P73 Q119,P91 Q151,P92 Q153




6-20          Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.

Contenu connexe

Tendances (20)

Les04
Les04Les04
Les04
 
Lesson05 从多表中查询数据
Lesson05 从多表中查询数据Lesson05 从多表中查询数据
Lesson05 从多表中查询数据
 
Lesson10
Lesson10Lesson10
Lesson10
 
Les09
Les09Les09
Les09
 
plsql Les07
plsql Les07 plsql Les07
plsql Les07
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 
Understanding
Understanding Understanding
Understanding
 
wee
weewee
wee
 
An introduction to SQLAlchemy
An introduction to SQLAlchemyAn introduction to SQLAlchemy
An introduction to SQLAlchemy
 
Language enhancements in cold fusion 11
Language enhancements in cold fusion 11Language enhancements in cold fusion 11
Language enhancements in cold fusion 11
 
Find Anything In Your APEX App - Fuzzy Search with Oracle Text
Find Anything In Your APEX App - Fuzzy Search with Oracle TextFind Anything In Your APEX App - Fuzzy Search with Oracle Text
Find Anything In Your APEX App - Fuzzy Search with Oracle Text
 
APEX Office Hours Interactive Grid Deep Dive
APEX Office Hours Interactive Grid Deep DiveAPEX Office Hours Interactive Grid Deep Dive
APEX Office Hours Interactive Grid Deep Dive
 
Intershop bo
Intershop boIntershop bo
Intershop bo
 
PL/SQL CONDICIONALES Y CICLOS
PL/SQL CONDICIONALES Y CICLOSPL/SQL CONDICIONALES Y CICLOS
PL/SQL CONDICIONALES Y CICLOS
 
PL/SQL CURSORES
PL/SQL CURSORESPL/SQL CURSORES
PL/SQL CURSORES
 
Introduction to JSP pages
Introduction to JSP pagesIntroduction to JSP pages
Introduction to JSP pages
 
PyCon 2010 SQLAlchemy tutorial
PyCon 2010 SQLAlchemy tutorialPyCon 2010 SQLAlchemy tutorial
PyCon 2010 SQLAlchemy tutorial
 
Les01
Les01Les01
Les01
 
Extensible Data Modeling
Extensible Data ModelingExtensible Data Modeling
Extensible Data Modeling
 
Final Defense
Final DefenseFinal Defense
Final Defense
 

Similaire à Lesson06 使用子查询

Subqueries -Oracle DataBase
Subqueries -Oracle DataBaseSubqueries -Oracle DataBase
Subqueries -Oracle DataBaseSalman Memon
 
Lesson07
Lesson07Lesson07
Lesson07renguzi
 
Les07.ppt 0125566655656959652323265656565
Les07.ppt 0125566655656959652323265656565Les07.ppt 0125566655656959652323265656565
Les07.ppt 0125566655656959652323265656565nourhandardeer3
 
Lesson08
Lesson08Lesson08
Lesson08renguzi
 
Subconsultas
SubconsultasSubconsultas
SubconsultasMaria
 
Les06 (using subqueries to solve queries)
Les06 (using subqueries to solve queries)Les06 (using subqueries to solve queries)
Les06 (using subqueries to solve queries)Achmad Solichin
 
Using subqueries to solve queries
Using subqueries to solve queriesUsing subqueries to solve queries
Using subqueries to solve queriesSyed Zaid Irshad
 
ADVANCE SQL-"Sub queries"
ADVANCE SQL-"Sub queries"ADVANCE SQL-"Sub queries"
ADVANCE SQL-"Sub queries"Ankit Surti
 
Ch 6 Sub Query.pptx
Ch 6 Sub Query.pptxCh 6 Sub Query.pptx
Ch 6 Sub Query.pptxRamishaRauf
 
Les02 Restricting and Sorting Data using SQL.ppt
Les02 Restricting and Sorting Data using SQL.pptLes02 Restricting and Sorting Data using SQL.ppt
Les02 Restricting and Sorting Data using SQL.pptDrZeeshanBhatti
 
Restricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data BaseRestricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data BaseSalman Memon
 

Similaire à Lesson06 使用子查询 (20)

Subqueries -Oracle DataBase
Subqueries -Oracle DataBaseSubqueries -Oracle DataBase
Subqueries -Oracle DataBase
 
Lesson07
Lesson07Lesson07
Lesson07
 
Les07.ppt 0125566655656959652323265656565
Les07.ppt 0125566655656959652323265656565Les07.ppt 0125566655656959652323265656565
Les07.ppt 0125566655656959652323265656565
 
Lesson08
Lesson08Lesson08
Lesson08
 
Subconsultas
SubconsultasSubconsultas
Subconsultas
 
Oracle examples
Oracle examplesOracle examples
Oracle examples
 
Les06
Les06Les06
Les06
 
Les06 (using subqueries to solve queries)
Les06 (using subqueries to solve queries)Les06 (using subqueries to solve queries)
Les06 (using subqueries to solve queries)
 
Les06
Les06Les06
Les06
 
Using subqueries to solve queries
Using subqueries to solve queriesUsing subqueries to solve queries
Using subqueries to solve queries
 
Les02.ppt
Les02.pptLes02.ppt
Les02.ppt
 
plsql les01
 plsql les01 plsql les01
plsql les01
 
plsql les02
 plsql les02 plsql les02
plsql les02
 
ADVANCE SQL-"Sub queries"
ADVANCE SQL-"Sub queries"ADVANCE SQL-"Sub queries"
ADVANCE SQL-"Sub queries"
 
plsql les06
 plsql les06 plsql les06
plsql les06
 
Lab5 sub query
Lab5   sub queryLab5   sub query
Lab5 sub query
 
Ch 6 Sub Query.pptx
Ch 6 Sub Query.pptxCh 6 Sub Query.pptx
Ch 6 Sub Query.pptx
 
Les07
Les07Les07
Les07
 
Les02 Restricting and Sorting Data using SQL.ppt
Les02 Restricting and Sorting Data using SQL.pptLes02 Restricting and Sorting Data using SQL.ppt
Les02 Restricting and Sorting Data using SQL.ppt
 
Restricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data BaseRestricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data Base
 

Dernier

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 

Dernier (20)

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 

Lesson06 使用子查询

  • 1. Oracle OCP 考试系列培训 之 1Z0-007 Lesson6 www.OracleOnLinux.cn 6-1 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 2. 6 Using Subqueries to Solve Queries Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 3. Objectives After completing this lesson, you should be able to do the following: • Define subqueries • Describe the types of problems that subqueries can solve • List the types of subqueries • Write single-row and multiple-row subqueries 6-3 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 4. Using a Subquery to Solve a Problem Who has a salary greater than Abel’s? Abel’ Main query: Which employees have salaries greater than Abel’s salary? Abel’ Subquery: What is Abel’s salary? Abel’ 6-4 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 5. Subquery Syntax SELECT select_list FROM table WHERE expr operator (SELECT select_list FROM table); • The subquery (inner query) executes once before the main query (outer query). • The result of the subquery is used by the main query. 6-5 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 6. Using a Subquery SELECT last_name FROM employees 11000 WHERE salary > (SELECT salary FROM employees WHERE last_name = 'Abel'); 6-6 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 7. Guidelines for Using Subqueries • Enclose subqueries in parentheses. • Place subqueries on the right side of the comparison condition. • The ORDER BY clause in the subquery is not needed unless you are performing Top-N analysis. • Use single-row operators with single-row subqueries, and use multiple-row operators with multiple-row subqueries. 6-7 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 8. Types of Subqueries • Single-row subquery Main query returns Subquery ST_CLERK • Multiple-row subquery Main query returns ST_CLERK Subquery SA_MAN 6-8 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 9. Single-Row Subqueries • Return only one row • Use single-row comparison operators Operator Meaning = Equal to > Greater than >= Greater than or equal to < Less than <= Less than or equal to <> Not equal to 6-9 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 10. Executing Single-Row Subqueries SELECT last_name, job_id, salary FROM employees WHERE job_id = ST_CLERK (SELECT job_id FROM employees WHERE employee_id = 141) AND salary > 2600 (SELECT salary FROM employees WHERE employee_id = 143); 6-10 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 11. Using Group Functions in a Subquery SELECT last_name, job_id, salary FROM employees 2100 WHERE salary = (SELECT MIN(salary) FROM employees); 6-11 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 12. The HAVING Clause with Subqueries • The Oracle server executes subqueries first. • The Oracle server returns results into the HAVING clause of the main query. SELECT department_id, MIN(salary) FROM employees GROUP BY department_id 2100 HAVING MIN(salary) > (SELECT MIN(salary) FROM employees WHERE department_id = 50); 6-12 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 13. What Is Wrong with This Statement? SELECT employee_id, last_name FROM employees WHERE salary = (SELECT MIN(salary) FROM employees GROUP BY department_id); ERROR at line 4: ORA-01427: single-row subquery returns more than one row Single-row operator with multiple-row subquery 6-13 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 14. Will This Statement Return Rows? SELECT last_name, job_id FROM employees WHERE job_id = (SELECT job_id FROM employees WHERE last_name = 'Haas'); no rows selected Subquery returns no values. 6-14 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 15. Multiple-Row Subqueries • Return more than one row • Use multiple-row comparison operators Operator Meaning IN Equal to any member in the list ANY Compare value to each value returned by the subquery ALL Compare value to every value returned by the subquery 6-15 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 16. Using the ANY Operator in Multiple-Row Subqueries SELECT employee_id, last_name, job_id, salary FROM employees 9000, 6000, 4200 WHERE salary < ANY (SELECT salary FROM employees WHERE job_id = 'IT_PROG') AND job_id <> 'IT_PROG'; … 6-16 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 17. Using the ALL Operator in Multiple-Row Subqueries SELECT employee_id, last_name, job_id, salary FROM employees 9000, 6000, 4200 WHERE salary < ALL (SELECT salary FROM employees WHERE job_id = 'IT_PROG') AND job_id <> 'IT_PROG'; 6-17 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 18. Null Values in a Subquery SELECT emp.last_name FROM employees emp WHERE emp.employee_id NOT IN (SELECT mgr.manager_id FROM employees mgr); no rows selected SELECT emp.last_name FROM employees emp WHERE emp.employee_id NOT IN (SELECT mgr.manager_id FROM employees mgr WHERE manager_id is not null); 子查询中:凡是返回结果包含NULL值,其结果一定为NULL 6-18 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 19. Summary In this lesson, you should have learned how to: • Identify when a subquery can help solve a question • Write subqueries when a query is based on unknown values SELECT select_list FROM table WHERE expr operator (SELECT select_list FROM table); 6-19 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.
  • 20. Practice 6: Overview This practice covers the following topics: • Creating subqueries to query values based on unknown criteria • Using subqueries to find out which values exist in one set of data and not in another – P59 Q92 – P61 Q98 ,P62 Q99 – P73 Q119,P91 Q151,P92 Q153 6-20 Copyright © 2012, http://OracleOnLinux.cn. Part rights reserved.