SlideShare a Scribd company logo
1 of 19
Sub Queries
What is a Sub-query?
 A Sub-query is a query within another SQL query
embedded within the WHERE clause.
 The sub-query (inner query) executes once before the main
query.
 The result of the sub-query is used by the main query
(outer query).
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name OPERATOR (SELECT column_name [, column_name ]
FROM table1 [, table2 ] [WHERE] )
Syntax
Inner query
Outer query
Using Sub-query to Solve a Problem
“Which section has more capacity than 385 sec 2?”
Main Query
“Which section has more capacity than
385 sec 2?”
Sub-query
“What is the capacity of 385 sec 2?”
Using Sub-query to Solve a Problem
Examples:
“Who has a salary greater than Jones’?”
“Which employees have a salary greater than
Jones’ salary?
“What is Jones’ salary?”
Main Query
Sub-query
Using a Sub-query
The inner query determines the salary of employee 7566.
The outer query takes the result of the inner query and
uses this result to display all the employees who earn
more than this amount.
SQL> SELECT ename
2 FROM emp
3 WHERE sal > (SELECT sal
4 FROM emp
5 WHERE empno=7566);
ENAME
----------
SCOTT
KING
FORD
2975
Guidelines for Using Sub-queries
 Enclose sub-queries in parentheses.
 Place sub-queries on the right side of the comparison
operator.
 Do not add an ORDER BY clause to a Sub-query.
 Use single-row operators with single-row sub-queries.
 Use multiple-row operators with multiple-row
sub-queries.
Types of Sub-queries
 Single-row subquery
 Multiple-row subquery
 Multiple-column subquery
Main query
Subquery
returns
Main query
Subquery
returns
Main query
Subquery
returns
AHMED
AHMED
ISA
AHMED 24000
ISA 15000
Single-Row Sub-queries
 Returns only one row.
 Use single-row comparison operators
Meaning
Operator
Equal to
=
Greater than
>
Greater than or
equal
>=
Less than
<
Less than or equal
<=
Not equal to
<>
Executing Single-Row Subqueries
 Example:
Display employees whose job title is the same as that
of employee 7369 and whose salary is greater than
that of employee 7876.
Answer
CLERK
1100
Using Group Functions in a Sub-query
Display the employee name and job of the
employee who earns the minimum salary.
SQL> SELECT ename, job, sal
FROM emp
WHERE sal =
(SELECT MIN(sal)
FROM emp);
ENAME JOB SAL
-------- -------- ----------
SMITH CLERK 800
800
HAVING Clause with Sub-queries
 The Oracle Server executes sub-queries first.
 The Oracle Server returns results into the HAVING
clause of the main query.
 We can use sub-queries not only in the WHERE
clause, but also in the HAVING clause.
HAVING Clause with Sub-queries
 Find the Job with the lowest average salary.
What is Wrong
with This Statement?
 Display the employees’ numbers and names for
those who earn the lowest salary in each
department.
Multiple-Row Sub-queries
 Return more than one row
 Use multiple-row comparison operators
Meaning
Operator
Equal to any member in the list
IN
Compare value to each value returned by
the sub-query
ANY
Compare value to every value returned by
the sub-query
ALL
Multiple-Row Sub-queries
Using ANY Operator
in Multiple-Row Sub-queries
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’;
EMPNO ENAME JOB
----- ---------- -----------
7654 MARTIN SALESMAN
7521 WARD SALESMAN
The example displays employees whose salary is less than any clerk and
who are not clerks.
The maximum salary that a clerk earns is $1300. The SQL statement
displays the employees who are not clerks but earn less than $1300.
(1300, 1100, 800, 950)
Multiple-Row Subqueries
Example:
Display employees (number, name, and job) whose
salary is greater than the average salaries of all the
departments.
(1566.667, 2175, 2916.667)
Summary
Sub-queries are useful when a query is Based on
unknown values.
SELECT select_list
FROM table
WHERE expression operator
(SELECT select_list
FROM table);

More Related Content

What's hot

What's hot (19)

Lab4 join - all types listed
Lab4   join - all types listedLab4   join - all types listed
Lab4 join - all types listed
 
Subqueries
SubqueriesSubqueries
Subqueries
 
ADVANCE SQL-"Sub queries"
ADVANCE SQL-"Sub queries"ADVANCE SQL-"Sub queries"
ADVANCE SQL-"Sub queries"
 
Sql subquery
Sql subquerySql subquery
Sql subquery
 
Oracle: Basic SQL
Oracle: Basic SQLOracle: Basic SQL
Oracle: Basic SQL
 
e computer notes - Subqueries
e computer notes - Subqueriese computer notes - Subqueries
e computer notes - Subqueries
 
Group by clause mod
Group by clause modGroup by clause mod
Group by clause mod
 
Introduction to oracle functions
Introduction to oracle functionsIntroduction to oracle functions
Introduction to oracle functions
 
Optimizing MySQL Queries
Optimizing MySQL QueriesOptimizing MySQL Queries
Optimizing MySQL Queries
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functions
 
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
Chapter 2  grouping,scalar and aggergate functions,joins   inner join,outer joinChapter 2  grouping,scalar and aggergate functions,joins   inner join,outer join
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
 
Explain that explain
Explain that explainExplain that explain
Explain that explain
 
Sequences and indexes
Sequences and indexesSequences and indexes
Sequences and indexes
 
SQL Functions and Operators
SQL Functions and OperatorsSQL Functions and Operators
SQL Functions and Operators
 
Mysql Explain Explained
Mysql Explain ExplainedMysql Explain Explained
Mysql Explain Explained
 
Functions oracle (pl/sql)
Functions oracle (pl/sql)Functions oracle (pl/sql)
Functions oracle (pl/sql)
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007
 
Oracle: Functions
Oracle: FunctionsOracle: Functions
Oracle: Functions
 
Oracle SQL, PL/SQL best practices
Oracle SQL, PL/SQL best practicesOracle SQL, PL/SQL best practices
Oracle SQL, PL/SQL best practices
 

Similar to Lab5 sub query (20)

Les06
Les06Les06
Les06
 
Les06
Les06Les06
Les06
 
Les06 Subqueries
Les06 SubqueriesLes06 Subqueries
Les06 Subqueries
 
Les06 (using subqueries to solve queries)
Les06 (using subqueries to solve queries)Les06 (using subqueries to solve queries)
Les06 (using subqueries to solve queries)
 
Ch 6 Sub Query.pptx
Ch 6 Sub Query.pptxCh 6 Sub Query.pptx
Ch 6 Sub Query.pptx
 
Les06
Les06Les06
Les06
 
Using subqueries to solve queries
Using subqueries to solve queriesUsing subqueries to solve queries
Using subqueries to solve queries
 
Subqueries -Oracle DataBase
Subqueries -Oracle DataBaseSubqueries -Oracle DataBase
Subqueries -Oracle DataBase
 
Les06- Subqueries.ppt
Les06- Subqueries.pptLes06- Subqueries.ppt
Les06- Subqueries.ppt
 
Week6_Theory.pptx
Week6_Theory.pptxWeek6_Theory.pptx
Week6_Theory.pptx
 
7. Using Sub Queries
7. Using Sub Queries7. Using Sub Queries
7. Using Sub Queries
 
Module 3.1.pptx
Module 3.1.pptxModule 3.1.pptx
Module 3.1.pptx
 
SQL WORKSHOP::Lecture 6
SQL WORKSHOP::Lecture 6SQL WORKSHOP::Lecture 6
SQL WORKSHOP::Lecture 6
 
Les06[1]Subqueries
Les06[1]SubqueriesLes06[1]Subqueries
Les06[1]Subqueries
 
Oracle Advanced SQL
Oracle Advanced SQLOracle Advanced SQL
Oracle Advanced SQL
 
resource governor
resource governorresource governor
resource governor
 
Oracle examples
Oracle examplesOracle examples
Oracle examples
 
7992267.ppt
7992267.ppt7992267.ppt
7992267.ppt
 
Subqueries, Backups, Users and Privileges
Subqueries, Backups, Users and PrivilegesSubqueries, Backups, Users and Privileges
Subqueries, Backups, Users and Privileges
 
How to work with Subquery in Data Mining?
How to work with Subquery in Data Mining?How to work with Subquery in Data Mining?
How to work with Subquery in Data Mining?
 

Recently uploaded

call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 

Recently uploaded (20)

call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 

Lab5 sub query

  • 2. What is a Sub-query?  A Sub-query is a query within another SQL query embedded within the WHERE clause.  The sub-query (inner query) executes once before the main query.  The result of the sub-query is used by the main query (outer query). SELECT column_name [, column_name ] FROM table1 [, table2 ] WHERE column_name OPERATOR (SELECT column_name [, column_name ] FROM table1 [, table2 ] [WHERE] ) Syntax Inner query Outer query
  • 3. Using Sub-query to Solve a Problem “Which section has more capacity than 385 sec 2?” Main Query “Which section has more capacity than 385 sec 2?” Sub-query “What is the capacity of 385 sec 2?”
  • 4. Using Sub-query to Solve a Problem Examples: “Who has a salary greater than Jones’?” “Which employees have a salary greater than Jones’ salary? “What is Jones’ salary?” Main Query Sub-query
  • 5. Using a Sub-query The inner query determines the salary of employee 7566. The outer query takes the result of the inner query and uses this result to display all the employees who earn more than this amount. SQL> SELECT ename 2 FROM emp 3 WHERE sal > (SELECT sal 4 FROM emp 5 WHERE empno=7566); ENAME ---------- SCOTT KING FORD 2975
  • 6. Guidelines for Using Sub-queries  Enclose sub-queries in parentheses.  Place sub-queries on the right side of the comparison operator.  Do not add an ORDER BY clause to a Sub-query.  Use single-row operators with single-row sub-queries.  Use multiple-row operators with multiple-row sub-queries.
  • 7. Types of Sub-queries  Single-row subquery  Multiple-row subquery  Multiple-column subquery Main query Subquery returns Main query Subquery returns Main query Subquery returns AHMED AHMED ISA AHMED 24000 ISA 15000
  • 8. Single-Row Sub-queries  Returns only one row.  Use single-row comparison operators Meaning Operator Equal to = Greater than > Greater than or equal >= Less than < Less than or equal <= Not equal to <>
  • 9. Executing Single-Row Subqueries  Example: Display employees whose job title is the same as that of employee 7369 and whose salary is greater than that of employee 7876.
  • 11. Using Group Functions in a Sub-query Display the employee name and job of the employee who earns the minimum salary. SQL> SELECT ename, job, sal FROM emp WHERE sal = (SELECT MIN(sal) FROM emp); ENAME JOB SAL -------- -------- ---------- SMITH CLERK 800 800
  • 12. HAVING Clause with Sub-queries  The Oracle Server executes sub-queries first.  The Oracle Server returns results into the HAVING clause of the main query.  We can use sub-queries not only in the WHERE clause, but also in the HAVING clause.
  • 13. HAVING Clause with Sub-queries  Find the Job with the lowest average salary.
  • 14. What is Wrong with This Statement?  Display the employees’ numbers and names for those who earn the lowest salary in each department.
  • 15. Multiple-Row Sub-queries  Return more than one row  Use multiple-row comparison operators Meaning Operator Equal to any member in the list IN Compare value to each value returned by the sub-query ANY Compare value to every value returned by the sub-query ALL
  • 17. Using ANY Operator in Multiple-Row Sub-queries 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’; EMPNO ENAME JOB ----- ---------- ----------- 7654 MARTIN SALESMAN 7521 WARD SALESMAN The example displays employees whose salary is less than any clerk and who are not clerks. The maximum salary that a clerk earns is $1300. The SQL statement displays the employees who are not clerks but earn less than $1300. (1300, 1100, 800, 950)
  • 18. Multiple-Row Subqueries Example: Display employees (number, name, and job) whose salary is greater than the average salaries of all the departments. (1566.667, 2175, 2916.667)
  • 19. Summary Sub-queries are useful when a query is Based on unknown values. SELECT select_list FROM table WHERE expression operator (SELECT select_list FROM table);