SlideShare une entreprise Scribd logo
1  sur  17
Sub queries
Vikas K. Gupta
Using a Subquery to Solve a Problem


To solve this problem, you need two
queries: one to find what Abel earns,
and a second query to find who
earns more than that amount.



You can solve this problem by
combining the two queries, placing
one query inside the other query.



The inner query or the subquery
returns a value that is used by the
outer query or the main query.



Using a subquery is equivalent to
performing two sequential queries
and using the result of the first query
as the search value in the second
query.
Subqueries


A subquery is a SELECT statement
that is embedded in a clause of
another SELECT statement.



They can be very useful when you need
to select rows from a table with a
condition that depends on the data in the
table itself.

You can place the subquery in a number
of SQL clauses, including:
- The WHERE clause
- The HAVING clause
- The FROM clause

You can build powerful statements out of
simple ones by using subqueries.





The subquery generally executes first,
and its output is used to complete the
query condition for the main or outer
query.

Note: Comparison conditions fall into two
classes: single-row operators (>, =, >=,
<, <>, <=) and multiple-row operators
(IN, ANY, ALL).



subqueries can be placed in the
CREATE VIEW statement, CREATE
TABLE statement, UPDATE statement,
INTO clause of an INSERT statement,
and SET clause of an UPDATE
statement.

The subquery is often referred to as a
nested SELECT, sub-SELECT, or inner
SELECT statement.



operator includes a comparison condition
such as >, =, or IN





Sub-query Syntax

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

In the slide, the inner query determines the salary of employee Abel.



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.



Execute the subquery (inner query) on its own first to show the value that the
subquery returns.



Then execute the outer query using the result returned by the inner query.
Finally, execute the entire query (containing the subquery), and show that the
result is the same.
Guidelines for Using Subqueries


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.



Prior to release Oracle8i, subqueries could not contain an ORDER BY clause.



Only one ORDER BY clause can be used for a SELECT statement, and if
specified it must be the last clause in the main SELECT statement. Starting with
release Oracle8i, an ORDER BY clause can be used and is required in the
subquery to perform Top-N analysis.



The Oracle server imposes no limit on the number of subqueries; the limit is
related to the buffer size that the query uses.
Types of Subqueries


Single-row subqueries:
Queries that return only one row
from the inner SELECT statement



Multiple-row subqueries:
Queries that return more than one
row from the inner SELECT
statement



Note: There are also multiplecolumn subqueries: Queries that
return more than one column from
the inner SELECT statement.
Single-Row Subqueries


Return only one row



Use single-row comparison operators
Executing Single-Row Subqueries


A SELECT statement can be considered as a query block.



The example on the slide displays employees whose job ID is the same as that of employee 141
and whose salary is greater than that of employee 143.



The example consists of three query blocks: the outer query and two inner queries.



The inner query blocks are executed first, producing the query results ST_CLERK and
2600, respectively.



The outer query block is then processed and uses the values returned by the inner queries
to complete its search conditions.
Using Group Functions in a Subquery


The example on the slide displays the employee last name, job ID, and
salary of all employees whose salary is equal to the minimum salary.



The MIN group function returns a single value (2500) to the outer query.
The HAVING Clause with Subqueries


The Oracle server executes subqueries first.



The Oracle server returns results into the HAVING clause of the main query.



The SQL statement on the slide displays all the departments that have a minimum salary greater than that of
department 50.
Problems with Subqueries


A common problem with subqueries is no rows being returned by the inner query.



There is no employee named Haas. So the subquery returns no rows.



The outer query takes the results of the subquery (null) and uses these results in its
WHERE clause. The outer query finds no employee with a job ID equal to null, and so
returns no rows.



If a job existed with a value of null, the row is not returned because comparison of two null
values yields a null, therefore the WHERE condition is not true.
Multiple-Row Subqueries


Subqueries that return more than one row
are called multiple-row subqueries.



You use a multiple-row operator, instead of
a single-row operator, with a multiple-row
subquery.



The multiple-row operator expects one or
more values.
ANY Operator in Multiple-Row Subqueries


The ANY operator compares a value to each value returned by a subquery.



The slide example displays employees who are not IT programmers and whose
salary is less than that of any IT programmer. The maximum salary that a
programmer earns is $9,000.



<ANY means less than the maximum.
>ANY means greater than the minimum.
=ANY is equivalent to IN.









<ALL means less than the minimum.
>ALL means greater than the maximum.
When using SOME or ANY, you often use the DISTINCT keyword to prevent
rows from being selected several times.
Example :

The NOT operator can be used with IN, ANY, and ALL operators.
Null Values in a Subquery


One of the values returned by the inner query is a null value, and hence the
entire query returns no rows.



The reason is that all conditions that compare a null value result in a
null.



So whenever null values are likely to be part of the results set of a subquery,
do not use the NOT IN operator.



The NOT IN operator is equivalent to <> ALL.
Summary


In this lesson, you should have learned how to use subqueries.



A subquery is a SELECT statement that is embedded in a clause of another SQL
statement.



Subqueries are useful when a query is based on a search criteria with unknown
intermediate values.

Subqueries have the following characteristics:


Can pass one row of data to a main statement that contains a single-row operator, such as
=, <>, >, >=, <, or <=



Can pass multiple rows of data to a main statement that contains a multiple-row operator,
such as IN



Are processed first by the Oracle server, and the WHERE or HAVING clause uses the
results



Can contain group functions

Contenu connexe

Tendances

Tendances (20)

DATABASE CONSTRAINTS
DATABASE CONSTRAINTSDATABASE CONSTRAINTS
DATABASE CONSTRAINTS
 
SQL select clause
SQL select clauseSQL select clause
SQL select clause
 
Oracle Database Sequence
Oracle Database SequenceOracle Database Sequence
Oracle Database Sequence
 
Sql operators & functions 3
Sql operators & functions 3Sql operators & functions 3
Sql operators & functions 3
 
SQL Basics
SQL BasicsSQL Basics
SQL Basics
 
Using the set operators
Using the set operatorsUsing the set operators
Using the set operators
 
Introduction To Oracle Sql
Introduction To Oracle SqlIntroduction To Oracle Sql
Introduction To Oracle Sql
 
SQL Joins With Examples | Edureka
SQL Joins With Examples | EdurekaSQL Joins With Examples | Edureka
SQL Joins With Examples | Edureka
 
Sql Basics And Advanced
Sql Basics And AdvancedSql Basics And Advanced
Sql Basics And Advanced
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 
SQL Differences SQL Interview Questions
SQL Differences  SQL Interview QuestionsSQL Differences  SQL Interview Questions
SQL Differences SQL Interview Questions
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
 
SQL
SQLSQL
SQL
 
Introduction of sql server indexing
Introduction of sql server indexingIntroduction of sql server indexing
Introduction of sql server indexing
 
Sql(structured query language)
Sql(structured query language)Sql(structured query language)
Sql(structured query language)
 
Types Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql ServerTypes Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql Server
 
Oracle: Joins
Oracle: JoinsOracle: Joins
Oracle: Joins
 
Trigger
TriggerTrigger
Trigger
 
Query processing
Query processingQuery processing
Query processing
 

En vedette (20)

Subqueries -Oracle DataBase
Subqueries -Oracle DataBaseSubqueries -Oracle DataBase
Subqueries -Oracle DataBase
 
Sql subquery
Sql subquerySql subquery
Sql subquery
 
Sql queries with answers
Sql queries with answersSql queries with answers
Sql queries with answers
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries Lecture
 
e computer notes - Subqueries
e computer notes - Subqueriese computer notes - Subqueries
e computer notes - Subqueries
 
Sql joins
Sql joinsSql joins
Sql joins
 
Best sql plsql material
Best sql plsql materialBest sql plsql material
Best sql plsql material
 
A must Sql notes for beginners
A must Sql notes for beginnersA must Sql notes for beginners
A must Sql notes for beginners
 
Oracle Advanced SQL
Oracle Advanced SQLOracle Advanced SQL
Oracle Advanced SQL
 
Oracle Training in Kochi | Trivandrum |Thrissur
Oracle Training in Kochi | Trivandrum |ThrissurOracle Training in Kochi | Trivandrum |Thrissur
Oracle Training in Kochi | Trivandrum |Thrissur
 
Subqueries
SubqueriesSubqueries
Subqueries
 
Pivot Unpivot
Pivot UnpivotPivot Unpivot
Pivot Unpivot
 
Technical stream presentation
Technical stream presentationTechnical stream presentation
Technical stream presentation
 
Using T-SQL
Using T-SQL Using T-SQL
Using T-SQL
 
MS SQL SERVER: Creating Views
MS SQL SERVER: Creating ViewsMS SQL SERVER: Creating Views
MS SQL SERVER: Creating Views
 
Sql db optimization
Sql db optimizationSql db optimization
Sql db optimization
 
Using grouping sets in sql server 2008 tech republic
Using grouping sets in sql server 2008   tech republicUsing grouping sets in sql server 2008   tech republic
Using grouping sets in sql server 2008 tech republic
 
Joins SQL Server
Joins SQL ServerJoins SQL Server
Joins SQL Server
 
Consultas en MS SQL Server 2012
Consultas en MS SQL Server 2012Consultas en MS SQL Server 2012
Consultas en MS SQL Server 2012
 
Sql xp 04
Sql xp 04Sql xp 04
Sql xp 04
 

Similaire à SQL subquery

Using subqueries to solve queries
Using subqueries to solve queriesUsing subqueries to solve queries
Using subqueries to solve queriesSyed Zaid Irshad
 
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
 
Ch 6 Sub Query.pptx
Ch 6 Sub Query.pptxCh 6 Sub Query.pptx
Ch 6 Sub Query.pptxRamishaRauf
 
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?loginworks software
 
Subconsultas
SubconsultasSubconsultas
SubconsultasMaria
 
Sql scripting sorcerypaper
Sql scripting sorcerypaperSql scripting sorcerypaper
Sql scripting sorcerypaperoracle documents
 
Subqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsSubqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsmaxpane
 
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQueryPPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQueryAbhishek590097
 
Subqueries, Backups, Users and Privileges
Subqueries, Backups, Users and PrivilegesSubqueries, Backups, Users and Privileges
Subqueries, Backups, Users and PrivilegesAshwin Dinoriya
 
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343Edgar Alejandro Villegas
 

Similaire à SQL subquery (20)

7. Using Sub Queries
7. Using Sub Queries7. Using Sub Queries
7. Using Sub Queries
 
Les06
Les06Les06
Les06
 
Lab5 sub query
Lab5   sub queryLab5   sub query
Lab5 sub query
 
Using subqueries to solve queries
Using subqueries to solve queriesUsing subqueries to solve queries
Using subqueries to solve queries
 
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)
 
Ch 6 Sub Query.pptx
Ch 6 Sub Query.pptxCh 6 Sub Query.pptx
Ch 6 Sub Query.pptx
 
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?
 
Oracle SQL Part 3
Oracle SQL Part 3Oracle SQL Part 3
Oracle SQL Part 3
 
Subconsultas
SubconsultasSubconsultas
Subconsultas
 
Sql scripting sorcerypaper
Sql scripting sorcerypaperSql scripting sorcerypaper
Sql scripting sorcerypaper
 
Les18
Les18Les18
Les18
 
Subqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsSubqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactions
 
Att160 f.tmp
Att160 f.tmpAtt160 f.tmp
Att160 f.tmp
 
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQueryPPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
 
Subqueries, Backups, Users and Privileges
Subqueries, Backups, Users and PrivilegesSubqueries, Backups, Users and Privileges
Subqueries, Backups, Users and Privileges
 
Les06
Les06Les06
Les06
 
SUBQUERIES.pptx
SUBQUERIES.pptxSUBQUERIES.pptx
SUBQUERIES.pptx
 
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
 
5. Group Functions
5. Group Functions5. Group Functions
5. Group Functions
 

Plus de Vikas Gupta

Plus de Vikas Gupta (7)

SQL DDL
SQL DDLSQL DDL
SQL DDL
 
Sql DML
Sql DMLSql DML
Sql DML
 
Sql DML
Sql DMLSql DML
Sql DML
 
Sql join
Sql  joinSql  join
Sql join
 
Join sql
Join sqlJoin sql
Join sql
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functions
 
Sql intro
Sql introSql intro
Sql intro
 

Dernier

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 

Dernier (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 

SQL subquery

  • 2. Using a Subquery to Solve a Problem  To solve this problem, you need two queries: one to find what Abel earns, and a second query to find who earns more than that amount.  You can solve this problem by combining the two queries, placing one query inside the other query.  The inner query or the subquery returns a value that is used by the outer query or the main query.  Using a subquery is equivalent to performing two sequential queries and using the result of the first query as the search value in the second query.
  • 3. Subqueries  A subquery is a SELECT statement that is embedded in a clause of another SELECT statement.  They can be very useful when you need to select rows from a table with a condition that depends on the data in the table itself. You can place the subquery in a number of SQL clauses, including: - The WHERE clause - The HAVING clause - The FROM clause You can build powerful statements out of simple ones by using subqueries.   The subquery generally executes first, and its output is used to complete the query condition for the main or outer query. Note: Comparison conditions fall into two classes: single-row operators (>, =, >=, <, <>, <=) and multiple-row operators (IN, ANY, ALL).  subqueries can be placed in the CREATE VIEW statement, CREATE TABLE statement, UPDATE statement, INTO clause of an INSERT statement, and SET clause of an UPDATE statement. The subquery is often referred to as a nested SELECT, sub-SELECT, or inner SELECT statement.  operator includes a comparison condition such as >, =, or IN   
  • 4. Sub-query Syntax • The subquery (inner query) executes once before the main query. • The result of the subquery is used by the main query (outer query).
  • 5. Example :  In the slide, the inner query determines the salary of employee Abel.  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.  Execute the subquery (inner query) on its own first to show the value that the subquery returns.  Then execute the outer query using the result returned by the inner query. Finally, execute the entire query (containing the subquery), and show that the result is the same.
  • 6. Guidelines for Using Subqueries  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.  Prior to release Oracle8i, subqueries could not contain an ORDER BY clause.  Only one ORDER BY clause can be used for a SELECT statement, and if specified it must be the last clause in the main SELECT statement. Starting with release Oracle8i, an ORDER BY clause can be used and is required in the subquery to perform Top-N analysis.  The Oracle server imposes no limit on the number of subqueries; the limit is related to the buffer size that the query uses.
  • 7. Types of Subqueries  Single-row subqueries: Queries that return only one row from the inner SELECT statement  Multiple-row subqueries: Queries that return more than one row from the inner SELECT statement  Note: There are also multiplecolumn subqueries: Queries that return more than one column from the inner SELECT statement.
  • 8. Single-Row Subqueries  Return only one row  Use single-row comparison operators
  • 9. Executing Single-Row Subqueries  A SELECT statement can be considered as a query block.  The example on the slide displays employees whose job ID is the same as that of employee 141 and whose salary is greater than that of employee 143.  The example consists of three query blocks: the outer query and two inner queries.  The inner query blocks are executed first, producing the query results ST_CLERK and 2600, respectively.  The outer query block is then processed and uses the values returned by the inner queries to complete its search conditions.
  • 10. Using Group Functions in a Subquery  The example on the slide displays the employee last name, job ID, and salary of all employees whose salary is equal to the minimum salary.  The MIN group function returns a single value (2500) to the outer query.
  • 11. The HAVING Clause with Subqueries  The Oracle server executes subqueries first.  The Oracle server returns results into the HAVING clause of the main query.  The SQL statement on the slide displays all the departments that have a minimum salary greater than that of department 50.
  • 12. Problems with Subqueries  A common problem with subqueries is no rows being returned by the inner query.  There is no employee named Haas. So the subquery returns no rows.  The outer query takes the results of the subquery (null) and uses these results in its WHERE clause. The outer query finds no employee with a job ID equal to null, and so returns no rows.  If a job existed with a value of null, the row is not returned because comparison of two null values yields a null, therefore the WHERE condition is not true.
  • 13. Multiple-Row Subqueries  Subqueries that return more than one row are called multiple-row subqueries.  You use a multiple-row operator, instead of a single-row operator, with a multiple-row subquery.  The multiple-row operator expects one or more values.
  • 14. ANY Operator in Multiple-Row Subqueries  The ANY operator compares a value to each value returned by a subquery.  The slide example displays employees who are not IT programmers and whose salary is less than that of any IT programmer. The maximum salary that a programmer earns is $9,000.  <ANY means less than the maximum. >ANY means greater than the minimum. =ANY is equivalent to IN.      <ALL means less than the minimum. >ALL means greater than the maximum. When using SOME or ANY, you often use the DISTINCT keyword to prevent rows from being selected several times.
  • 15. Example : The NOT operator can be used with IN, ANY, and ALL operators.
  • 16. Null Values in a Subquery  One of the values returned by the inner query is a null value, and hence the entire query returns no rows.  The reason is that all conditions that compare a null value result in a null.  So whenever null values are likely to be part of the results set of a subquery, do not use the NOT IN operator.  The NOT IN operator is equivalent to <> ALL.
  • 17. Summary  In this lesson, you should have learned how to use subqueries.  A subquery is a SELECT statement that is embedded in a clause of another SQL statement.  Subqueries are useful when a query is based on a search criteria with unknown intermediate values. Subqueries have the following characteristics:  Can pass one row of data to a main statement that contains a single-row operator, such as =, <>, >, >=, <, or <=  Can pass multiple rows of data to a main statement that contains a multiple-row operator, such as IN  Are processed first by the Oracle server, and the WHERE or HAVING clause uses the results  Can contain group functions