SlideShare a Scribd company logo
SUBQUERIES
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
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
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);
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
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.
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
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
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);
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);
HAVING Clause with
Subqueries
 The Oracle Server executes subqueries first.
 The Oracle Server returns results into the
HAVING clause of the main query.
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);
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);
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');
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
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';
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);
Summary
 Subqueries are useful when a query is
based on unknown values.
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);
Practice Overview
 Creating subqueries to query values based on
unknown criteria
 Using subqueries to find out what values exist
in one set of data and not in another

More Related Content

Similar to Ch 6 Sub Query.pptx

SQL subquery
SQL subquerySQL subquery
SQL subquery
Vikas Gupta
 
Les06[1]Subqueries
Les06[1]SubqueriesLes06[1]Subqueries
Les06[1]Subqueries
siavosh kaviani
 
Les06- Subqueries.ppt
Les06- Subqueries.pptLes06- Subqueries.ppt
Les06- Subqueries.ppt
gznfrch1
 
Subqueries -Oracle DataBase
Subqueries -Oracle DataBaseSubqueries -Oracle DataBase
Subqueries -Oracle DataBase
Salman Memon
 
Week8_Theory.pptx
Week8_Theory.pptxWeek8_Theory.pptx
Week8_Theory.pptx
MDTOUKERAHMED
 
7. Using Sub Queries
7. Using Sub Queries7. Using Sub Queries
7. Using Sub Queries
Evelyn Oluchukwu
 
Sub query_SQL
Sub query_SQLSub query_SQL
Sub query_SQL
CoT
 
7992267.ppt
7992267.ppt7992267.ppt
7992267.ppt
ssuser767860
 
Subconsultas
SubconsultasSubconsultas
Subconsultas
Maria
 
Sql subquery
Sql  subquerySql  subquery
Sql subquery
Raveena Thakur
 
e computer notes - Subqueries
e computer notes - Subqueriese computer notes - Subqueries
e computer notes - Subqueriesecomputernotes
 
Aggregating Data Using Group Functions
Aggregating Data Using Group FunctionsAggregating Data Using Group Functions
Aggregating Data Using Group Functions
Salman Memon
 
Les07.ppt 0125566655656959652323265656565
Les07.ppt 0125566655656959652323265656565Les07.ppt 0125566655656959652323265656565
Les07.ppt 0125566655656959652323265656565
nourhandardeer3
 
Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)
Vidyasagar Mundroy
 
Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Final
mukesh24pandey
 
SUBQUERIES.pptx
SUBQUERIES.pptxSUBQUERIES.pptx
SUBQUERIES.pptx
RenugadeviR5
 
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
DrZeeshanBhatti
 

Similar to Ch 6 Sub Query.pptx (20)

SQL subquery
SQL subquerySQL subquery
SQL subquery
 
Les06[1]Subqueries
Les06[1]SubqueriesLes06[1]Subqueries
Les06[1]Subqueries
 
Les06- Subqueries.ppt
Les06- Subqueries.pptLes06- Subqueries.ppt
Les06- Subqueries.ppt
 
Subqueries -Oracle DataBase
Subqueries -Oracle DataBaseSubqueries -Oracle DataBase
Subqueries -Oracle DataBase
 
Week8_Theory.pptx
Week8_Theory.pptxWeek8_Theory.pptx
Week8_Theory.pptx
 
7. Using Sub Queries
7. Using Sub Queries7. Using Sub Queries
7. Using Sub Queries
 
Sub query_SQL
Sub query_SQLSub query_SQL
Sub query_SQL
 
7992267.ppt
7992267.ppt7992267.ppt
7992267.ppt
 
Subconsultas
SubconsultasSubconsultas
Subconsultas
 
Les06
Les06Les06
Les06
 
Sql subquery
Sql  subquerySql  subquery
Sql subquery
 
e computer notes - Subqueries
e computer notes - Subqueriese computer notes - Subqueries
e computer notes - Subqueries
 
Les06
Les06Les06
Les06
 
Aggregating Data Using Group Functions
Aggregating Data Using Group FunctionsAggregating Data Using Group Functions
Aggregating Data Using Group Functions
 
Les07.ppt 0125566655656959652323265656565
Les07.ppt 0125566655656959652323265656565Les07.ppt 0125566655656959652323265656565
Les07.ppt 0125566655656959652323265656565
 
Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)
 
Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Final
 
SUBQUERIES.pptx
SUBQUERIES.pptxSUBQUERIES.pptx
SUBQUERIES.pptx
 
Les18
Les18Les18
Les18
 
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
 

Recently uploaded

Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 

Recently uploaded (20)

Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 

Ch 6 Sub Query.pptx

  • 2. 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. 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. 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. 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. 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.
  • 7. 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
  • 8. 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
  • 9. 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);
  • 10. 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);
  • 11. HAVING Clause with Subqueries  The Oracle Server executes subqueries first.  The Oracle Server returns results into the HAVING clause of the main query. 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);
  • 12. 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);
  • 13. 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');
  • 14. 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
  • 15. 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';
  • 16. 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);
  • 17. Summary  Subqueries are useful when a query is based on unknown values. SELECT select_list FROM table WHERE expr operator (SELECT select_list FROM table);
  • 18. Practice Overview  Creating subqueries to query values based on unknown criteria  Using subqueries to find out what values exist in one set of data and not in another