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

Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
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
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
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
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 

Recently uploaded (20)

Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
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
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
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
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
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
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 

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);