SlideShare a Scribd company logo
1 of 23
Copyright  Oracle Corporation, 1998. All rights reserved.
6
Subqueries
6-2 Copyright  Oracle Corporation, 1998. All rights reserved.
Objectives
After completing this lesson, you should
be able to do the following:
• Describe the types of problems that
subqueries can solve
• Define subqueries
• List the types of subqueries
• Write single-row and multiple-row
subqueries
6-3 Copyright  Oracle Corporation, 1998. All rights reserved.
Using a Subquery
to Solve a Problem
“Who has a salary greater than Jones’?”
“Which employees have a salary greater
than Jones’ salary?”
Main Query
?
“What is Jones’ salary?”
?
Subquery
6-4 Copyright  Oracle Corporation, 1998. All rights reserved.
Subqueries
• The subquery (inner query) executes
once before the main query.
• The result of the subquery is used by
the main query (outer query).
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);
6-5 Copyright  Oracle Corporation, 1998. All rights reserved.
Using a Subquery
Display the names of those employees
who earn more than
employee no 7566.
6-6 Copyright  Oracle Corporation, 1998. All rights reserved.
2975
SQL> SELECT ename
2 FROM emp
3 WHERE sal >
4 (SELECT sal
5 FROM emp
6 WHERE empno=7566);
Using a Subquery
ENAME
----------
KING
FORD
SCOTT
6-7 Copyright  Oracle Corporation, 1998. All rights reserved.
Guidelines for Using Subqueries
• Enclose subqueries in parentheses.
• Place subqueries on the right side of the
comparison operator.
• Do not add an ORDER BY clause to a subquery.
• Use single-row operators with single-row
subqueries.
• Use multiple-row operators with multiple-row
subqueries.
6-8 Copyright  Oracle Corporation, 1998. All rights reserved.
Types of Subqueries
• Single-row subquery
Main query
Subquery
returns
CLERK
• Multiple-row subquery
CLERK
MANAGER
Main query
Subquery
returns
• Multiple-column subquery
CLERK 7900
MANAGER 7698
Main query
Subquery
returns
6-9 Copyright  Oracle Corporation, 1998. All 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-10 Copyright  Oracle Corporation, 1998. All rights reserved.
Executing Single-Row Subqueries
Display name and job of all those employees
who have same job as employee no 7369
and
who have salary greater than the salary of
employee no 7876.
6-11 Copyright  Oracle Corporation, 1998. All rights reserved.
Executing Single-Row Subqueries
CLERK
1100
ENAME JOB
---------- ---------
MILLER CLERK
SQL> SELECT ename, job
2 FROM emp
3 WHERE job =
4 (SELECT job
5 FROM emp
6 WHERE empno = 7369)
7 AND sal >
8 (SELECT sal
9 FROM emp
10 WHERE empno = 7876);
6-12 Copyright  Oracle Corporation, 1998. All rights reserved.
Using Group Functions
in a Subquery
Display name, job and salary of those employees
who have
Salary equal to the minimum salary.
6-13 Copyright  Oracle Corporation, 1998. All rights reserved.
Using Group Functions
in a Subquery
800
ENAME JOB SAL
---------- --------- ---------
SMITH CLERK 800
SQL> SELECT ename, job, sal
2 FROM emp
3 WHERE sal =
4 (SELECT MIN(sal)
5 FROM emp);
6-14 Copyright  Oracle Corporation, 1998. All rights reserved.
HAVING Clause with Subqueries
• The Oracle Server executes subqueries first.
• The Oracle Server returns results into the
HAVING clause of the main query.
800
Display department no, minimum salary
of each department
who have minimum salary
greater than the
minimum salary of department no 20.
6-15 Copyright  Oracle Corporation, 1998. All rights reserved.
HAVING Clause with Subqueries
800
SQL> SELECT deptno, MIN(sal)
2 FROM emp
3 GROUP BY deptno
4 HAVING MIN(sal) >
5 (SELECT MIN(sal)
6 FROM emp
7 WHERE deptno = 20);
6-16 Copyright  Oracle Corporation, 1998. All rights reserved.
What Is Wrong with This Statement?
ERROR:
ORA-01427: single-row subquery returns more than
one row
no rows selected
SQL> SELECT empno, ename
2 FROM emp
3 WHERE sal =
4 (SELECT MIN(sal)
5 FROM emp
6 GROUP BY deptno);
6-17 Copyright  Oracle Corporation, 1998. All rights reserved.
Will This Statement Work?
no rows selected
SQL> SELECT ename, job
2 FROM emp
3 WHERE job =
4 (SELECT job
5 FROM emp
6 WHERE ename='SMYTHE');
6-18 Copyright  Oracle Corporation, 1998. All rights reserved.
Multiple-Row Subqueries
• Return more than one row
• Use multiple-row comparison operators
Operator
IN
ANY
ALL
Meaning
Equal to any member in the list
Compare value to each value returned by
the subquery
Compare value to every value returned by
the subquery
6-19 Copyright  Oracle Corporation, 1998. All rights reserved.
Using the IN Operator
Use the IN operator to test for values in a
list.
SQL> SELECT empno, ename, sal, mgr
2 FROM emp
3 WHERE mgr IN (7902, 7566, 7788);
EMPNO ENAME SAL MGR
--------- ---------- --------- ---------
7902 FORD 3000 7566
7369 SMITH 800 7902
7788 SCOTT 3000 7566
7876 ADAMS 1100 7788
Subquery
6-20 Copyright  Oracle Corporation, 1998. All rights reserved.
Using ANY Operator
in Multiple-Row Subqueries
950
800
1100
1300
EMPNO ENAME JOB
--------- ---------- ---------
7654 MARTIN SALESMAN
7521 WARD SALESMAN
SQL> SELECT empno, ename, job
2 FROM emp
3 WHERE sal < ANY
4 (SELECT sal
5 FROM emp
6 WHERE job = 'CLERK')
7 AND job <> 'CLERK';
EMP
DEPTNO JOB SAL
------ --------- -------
10 MANAGER 2450
10 PRESIDENT 5000
10 CLERK 1300
20 CLERK 800
20 CLERK 1100
20 ANALYST 3000
20 ANALYST 3000
20 MANAGER 2975
30 SALESMAN 1600
30 MANAGER 2850
30 SALESMAN 1250
30 CLERK 950
30 SALESMAN 1500
30 SALESMAN 1250
6-21 Copyright  Oracle Corporation, 1998. All rights reserved.
Using ALL Operator
in Multiple-Row Subqueries
2916.6667
2175
1566.6667
EMPNO ENAME JOB
--------- ---------- ---------
7839 KING PRESIDENT
7566 JONES MANAGER
7902 FORD ANALYST
7788 SCOTT ANALYST
SQL> SELECT empno, ename, job
2 FROM emp
3 WHERE sal > ALL
4 (SELECT avg(sal)
5 FROM emp
6 GROUP BY deptno);
DEPTNO SAL
------ -------
10 2450
10 5000
10 1300
20 800
20 1100
20 3000
20 3000
20 2975
30 1600
30 2850
30 1250
30 950
30 1500
30 1250
DEPTNO AVG(SAL)
------- ---------
10 2916.6667
20 2175
30 1566.6667
6-22 Copyright  Oracle Corporation, 1998. All rights reserved.
Select all customers where rating is bigger than
the rating of all customers living in Berlin.
SELECT *
FROM XYZ
WHERE rating > ALL ( SELECT rating FROM XYZ
WHERE stadt='Berlin' );
6-23 Copyright  Oracle Corporation, 1998. All rights reserved.
Select all customers with rating bigger than
rating of at least one of living in Berlin.
SELECT *
FROM tkunden
WHERE rating > ANY ( SELECT rating FROM
tkunden WHERE stadt='Berlin' );

More Related Content

Similar to Les06- Subqueries.ppt

Les07- Multiple-Column Subqueries.ppt
Les07- Multiple-Column Subqueries.pptLes07- Multiple-Column Subqueries.ppt
Les07- Multiple-Column Subqueries.pptgznfrch1
 
Restricting and sorting data
Restricting and sorting data Restricting and sorting data
Restricting and sorting data HuzaifaMushtaq3
 
Les05[1]Aggregating Data Using Group Functions
Les05[1]Aggregating Data  Using Group FunctionsLes05[1]Aggregating Data  Using Group Functions
Les05[1]Aggregating Data Using Group Functionssiavosh kaviani
 
Les07.ppt 0125566655656959652323265656565
Les07.ppt 0125566655656959652323265656565Les07.ppt 0125566655656959652323265656565
Les07.ppt 0125566655656959652323265656565nourhandardeer3
 
Subconsultas
SubconsultasSubconsultas
SubconsultasMaria
 
Les02[1]Restricting and Sorting Data
Les02[1]Restricting and Sorting DataLes02[1]Restricting and Sorting Data
Les02[1]Restricting and Sorting Datasiavosh kaviani
 
Les09[1]Manipulating Data
Les09[1]Manipulating DataLes09[1]Manipulating Data
Les09[1]Manipulating Datasiavosh kaviani
 
Aggregating Data Using Group Functions
Aggregating Data Using Group FunctionsAggregating Data Using Group Functions
Aggregating Data Using Group FunctionsSalman Memon
 
MERGE SQL Statement: Lesser Known Facets
MERGE SQL Statement: Lesser Known FacetsMERGE SQL Statement: Lesser Known Facets
MERGE SQL Statement: Lesser Known FacetsAndrej Pashchenko
 
Oracle SQL - Aggregating Data Les 05.ppt
Oracle SQL - Aggregating Data Les 05.pptOracle SQL - Aggregating Data Les 05.ppt
Oracle SQL - Aggregating Data Les 05.pptDrZeeshanBhatti
 
Les08[1] Producing Readable Output with SQL*Plus
Les08[1] Producing Readable Output with SQL*PlusLes08[1] Producing Readable Output with SQL*Plus
Les08[1] Producing Readable Output with SQL*Plussiavosh kaviani
 
Regular Expressions with full Unicode support
Regular Expressions with full Unicode supportRegular Expressions with full Unicode support
Regular Expressions with full Unicode supportMartinHanssonOracle
 

Similar to Les06- Subqueries.ppt (20)

Les07- Multiple-Column Subqueries.ppt
Les07- Multiple-Column Subqueries.pptLes07- Multiple-Column Subqueries.ppt
Les07- Multiple-Column Subqueries.ppt
 
Lab5 sub query
Lab5   sub queryLab5   sub query
Lab5 sub query
 
Les06
Les06Les06
Les06
 
Les12[1]Creating Views
Les12[1]Creating ViewsLes12[1]Creating Views
Les12[1]Creating Views
 
Restricting and sorting data
Restricting and sorting data Restricting and sorting data
Restricting and sorting data
 
chap2 (3).ppt
chap2 (3).pptchap2 (3).ppt
chap2 (3).ppt
 
Les02.pptx
Les02.pptxLes02.pptx
Les02.pptx
 
Les05[1]Aggregating Data Using Group Functions
Les05[1]Aggregating Data  Using Group FunctionsLes05[1]Aggregating Data  Using Group Functions
Les05[1]Aggregating Data Using Group Functions
 
Les02.ppt
Les02.pptLes02.ppt
Les02.ppt
 
Les07.ppt 0125566655656959652323265656565
Les07.ppt 0125566655656959652323265656565Les07.ppt 0125566655656959652323265656565
Les07.ppt 0125566655656959652323265656565
 
Oracle examples
Oracle examplesOracle examples
Oracle examples
 
Subconsultas
SubconsultasSubconsultas
Subconsultas
 
Les02[1]Restricting and Sorting Data
Les02[1]Restricting and Sorting DataLes02[1]Restricting and Sorting Data
Les02[1]Restricting and Sorting Data
 
Les09[1]Manipulating Data
Les09[1]Manipulating DataLes09[1]Manipulating Data
Les09[1]Manipulating Data
 
Aggregating Data Using Group Functions
Aggregating Data Using Group FunctionsAggregating Data Using Group Functions
Aggregating Data Using Group Functions
 
MERGE SQL Statement: Lesser Known Facets
MERGE SQL Statement: Lesser Known FacetsMERGE SQL Statement: Lesser Known Facets
MERGE SQL Statement: Lesser Known Facets
 
Oracle SQL - Aggregating Data Les 05.ppt
Oracle SQL - Aggregating Data Les 05.pptOracle SQL - Aggregating Data Les 05.ppt
Oracle SQL - Aggregating Data Les 05.ppt
 
Les08[1] Producing Readable Output with SQL*Plus
Les08[1] Producing Readable Output with SQL*PlusLes08[1] Producing Readable Output with SQL*Plus
Les08[1] Producing Readable Output with SQL*Plus
 
Les06
Les06Les06
Les06
 
Regular Expressions with full Unicode support
Regular Expressions with full Unicode supportRegular Expressions with full Unicode support
Regular Expressions with full Unicode support
 

Recently uploaded

Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
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
 
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
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 

Recently uploaded (20)

Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
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!
 
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
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 

Les06- Subqueries.ppt

  • 1. Copyright  Oracle Corporation, 1998. All rights reserved. 6 Subqueries
  • 2. 6-2 Copyright  Oracle Corporation, 1998. All rights reserved. Objectives After completing this lesson, you should be able to do the following: • Describe the types of problems that subqueries can solve • Define subqueries • List the types of subqueries • Write single-row and multiple-row subqueries
  • 3. 6-3 Copyright  Oracle Corporation, 1998. All rights reserved. Using a Subquery to Solve a Problem “Who has a salary greater than Jones’?” “Which employees have a salary greater than Jones’ salary?” Main Query ? “What is Jones’ salary?” ? Subquery
  • 4. 6-4 Copyright  Oracle Corporation, 1998. All rights reserved. Subqueries • The subquery (inner query) executes once before the main query. • The result of the subquery is used by the main query (outer query). SELECT select_list FROM table WHERE expr operator (SELECT select_list FROM table);
  • 5. 6-5 Copyright  Oracle Corporation, 1998. All rights reserved. Using a Subquery Display the names of those employees who earn more than employee no 7566.
  • 6. 6-6 Copyright  Oracle Corporation, 1998. All rights reserved. 2975 SQL> SELECT ename 2 FROM emp 3 WHERE sal > 4 (SELECT sal 5 FROM emp 6 WHERE empno=7566); Using a Subquery ENAME ---------- KING FORD SCOTT
  • 7. 6-7 Copyright  Oracle Corporation, 1998. All rights reserved. Guidelines for Using Subqueries • Enclose subqueries in parentheses. • Place subqueries on the right side of the comparison operator. • Do not add an ORDER BY clause to a subquery. • Use single-row operators with single-row subqueries. • Use multiple-row operators with multiple-row subqueries.
  • 8. 6-8 Copyright  Oracle Corporation, 1998. All rights reserved. Types of Subqueries • Single-row subquery Main query Subquery returns CLERK • Multiple-row subquery CLERK MANAGER Main query Subquery returns • Multiple-column subquery CLERK 7900 MANAGER 7698 Main query Subquery returns
  • 9. 6-9 Copyright  Oracle Corporation, 1998. All 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
  • 10. 6-10 Copyright  Oracle Corporation, 1998. All rights reserved. Executing Single-Row Subqueries Display name and job of all those employees who have same job as employee no 7369 and who have salary greater than the salary of employee no 7876.
  • 11. 6-11 Copyright  Oracle Corporation, 1998. All rights reserved. Executing Single-Row Subqueries CLERK 1100 ENAME JOB ---------- --------- MILLER CLERK SQL> SELECT ename, job 2 FROM emp 3 WHERE job = 4 (SELECT job 5 FROM emp 6 WHERE empno = 7369) 7 AND sal > 8 (SELECT sal 9 FROM emp 10 WHERE empno = 7876);
  • 12. 6-12 Copyright  Oracle Corporation, 1998. All rights reserved. Using Group Functions in a Subquery Display name, job and salary of those employees who have Salary equal to the minimum salary.
  • 13. 6-13 Copyright  Oracle Corporation, 1998. All rights reserved. Using Group Functions in a Subquery 800 ENAME JOB SAL ---------- --------- --------- SMITH CLERK 800 SQL> SELECT ename, job, sal 2 FROM emp 3 WHERE sal = 4 (SELECT MIN(sal) 5 FROM emp);
  • 14. 6-14 Copyright  Oracle Corporation, 1998. All rights reserved. HAVING Clause with Subqueries • The Oracle Server executes subqueries first. • The Oracle Server returns results into the HAVING clause of the main query. 800 Display department no, minimum salary of each department who have minimum salary greater than the minimum salary of department no 20.
  • 15. 6-15 Copyright  Oracle Corporation, 1998. All rights reserved. HAVING Clause with Subqueries 800 SQL> SELECT deptno, MIN(sal) 2 FROM emp 3 GROUP BY deptno 4 HAVING MIN(sal) > 5 (SELECT MIN(sal) 6 FROM emp 7 WHERE deptno = 20);
  • 16. 6-16 Copyright  Oracle Corporation, 1998. All rights reserved. What Is Wrong with This Statement? ERROR: ORA-01427: single-row subquery returns more than one row no rows selected SQL> SELECT empno, ename 2 FROM emp 3 WHERE sal = 4 (SELECT MIN(sal) 5 FROM emp 6 GROUP BY deptno);
  • 17. 6-17 Copyright  Oracle Corporation, 1998. All rights reserved. Will This Statement Work? no rows selected SQL> SELECT ename, job 2 FROM emp 3 WHERE job = 4 (SELECT job 5 FROM emp 6 WHERE ename='SMYTHE');
  • 18. 6-18 Copyright  Oracle Corporation, 1998. All rights reserved. Multiple-Row Subqueries • Return more than one row • Use multiple-row comparison operators Operator IN ANY ALL Meaning Equal to any member in the list Compare value to each value returned by the subquery Compare value to every value returned by the subquery
  • 19. 6-19 Copyright  Oracle Corporation, 1998. All rights reserved. Using the IN Operator Use the IN operator to test for values in a list. SQL> SELECT empno, ename, sal, mgr 2 FROM emp 3 WHERE mgr IN (7902, 7566, 7788); EMPNO ENAME SAL MGR --------- ---------- --------- --------- 7902 FORD 3000 7566 7369 SMITH 800 7902 7788 SCOTT 3000 7566 7876 ADAMS 1100 7788 Subquery
  • 20. 6-20 Copyright  Oracle Corporation, 1998. All rights reserved. Using ANY Operator in Multiple-Row Subqueries 950 800 1100 1300 EMPNO ENAME JOB --------- ---------- --------- 7654 MARTIN SALESMAN 7521 WARD SALESMAN SQL> SELECT empno, ename, job 2 FROM emp 3 WHERE sal < ANY 4 (SELECT sal 5 FROM emp 6 WHERE job = 'CLERK') 7 AND job <> 'CLERK'; EMP DEPTNO JOB SAL ------ --------- ------- 10 MANAGER 2450 10 PRESIDENT 5000 10 CLERK 1300 20 CLERK 800 20 CLERK 1100 20 ANALYST 3000 20 ANALYST 3000 20 MANAGER 2975 30 SALESMAN 1600 30 MANAGER 2850 30 SALESMAN 1250 30 CLERK 950 30 SALESMAN 1500 30 SALESMAN 1250
  • 21. 6-21 Copyright  Oracle Corporation, 1998. All rights reserved. Using ALL Operator in Multiple-Row Subqueries 2916.6667 2175 1566.6667 EMPNO ENAME JOB --------- ---------- --------- 7839 KING PRESIDENT 7566 JONES MANAGER 7902 FORD ANALYST 7788 SCOTT ANALYST SQL> SELECT empno, ename, job 2 FROM emp 3 WHERE sal > ALL 4 (SELECT avg(sal) 5 FROM emp 6 GROUP BY deptno); DEPTNO SAL ------ ------- 10 2450 10 5000 10 1300 20 800 20 1100 20 3000 20 3000 20 2975 30 1600 30 2850 30 1250 30 950 30 1500 30 1250 DEPTNO AVG(SAL) ------- --------- 10 2916.6667 20 2175 30 1566.6667
  • 22. 6-22 Copyright  Oracle Corporation, 1998. All rights reserved. Select all customers where rating is bigger than the rating of all customers living in Berlin. SELECT * FROM XYZ WHERE rating > ALL ( SELECT rating FROM XYZ WHERE stadt='Berlin' );
  • 23. 6-23 Copyright  Oracle Corporation, 1998. All rights reserved. Select all customers with rating bigger than rating of at least one of living in Berlin. SELECT * FROM tkunden WHERE rating > ANY ( SELECT rating FROM tkunden WHERE stadt='Berlin' );