SlideShare ist ein Scribd-Unternehmen logo
1 von 10
Subqueries
CIS-182
Subqueries
• A subquery is one SELECT statement
inside a second SELECT statement
– May be used throughout the main query, in
SELECT, FROM, WHERE or HAVING
– Parentheses control order of execution
Sample Subqueries
• Display the price and average price of all
books:
SELECT Price, (SELECT Avg(Price) FROM
titles) AS AveragePrice FROM titles
• Display all books with a higher than
average price:
SELECT title FROM titles WHERE
Price>(SELECT Avg(Price) FROM titles)
Subquery Results
• Scalar values: Subqueries may return a
single value
• Lists: Subqueries may return one or more
rows
– Some situations require a single column list
– Typically use IN or EXISTS to test
Scalar Subqueries Example
• Display titles that have the highest price:
SELECT title, price
FROM titles
WHERE Price = (SELECT Max(price) FROM
Titles)
List Subqueries Example
• Display the publishers who have
published cook books:
SELECT pub_name
FROM publishers
WHERE pub_id IN
(SELECT pub_id FROM titles WHERE [type]
LIKE ‘%cook%’)
Correlated Subqueries
• A correlated subquery uses a value from
the main query as part of the inner query
– Data from each row in the main query is
“passed” to the subquery for processing
• Typically a processing-intensive operation
– Subquery must be re-run with new value(s)
for each row
Correlated Subquery Example
• Display all books with a higher than
average price for that type of book
SELECT title
FROM titles t1
WHERE price >
(SELECT Avg(price) FROM titles t2 WHERE
t1.type = t2.type)
Using Subqueries - 1
• If data that’s known is from one table and
data to return is in a second table
• Display authors who have written books
(titleauthors represents what’s known):
SELECT au_fname, au_lname
FROM authors
WHERE au_id IN
(SELECT au_id FROM titleauthors)
Using Subqueries – 2
• If data to return depends on a calculation
from a related set
• Display books where actual sales have
exceeded projected sales:
SELECT title
FROM titles t
WHERE projected_sales <
(SELECT sum(qty_shipped) FROM salesdetails
sd WHERE t.title_id=sd.title_id)

Weitere ähnliche Inhalte

Was ist angesagt?

Inner join and outer join
Inner join and outer joinInner join and outer join
Inner join and outer join
Nargis Ehsan
 

Was ist angesagt? (20)

PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
joins in database
 joins in database joins in database
joins in database
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL Commands
 
Joins And Its Types
Joins And Its TypesJoins And Its Types
Joins And Its Types
 
Sql joins
Sql joinsSql joins
Sql joins
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries Lecture
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sql
 
Mysql joins
Mysql joinsMysql joins
Mysql joins
 
View & index in SQL
View & index in SQLView & index in SQL
View & index in SQL
 
Introduction of sql server indexing
Introduction of sql server indexingIntroduction of sql server indexing
Introduction of sql server indexing
 
Inner join and outer join
Inner join and outer joinInner join and outer join
Inner join and outer join
 
SQL JOINS
SQL JOINSSQL JOINS
SQL JOINS
 
MySQL JOIN & UNION
MySQL JOIN & UNIONMySQL JOIN & UNION
MySQL JOIN & UNION
 
Join
JoinJoin
Join
 
Sql joins inner join self join outer joins
Sql joins inner join self join outer joinsSql joins inner join self join outer joins
Sql joins inner join self join outer joins
 
Aggregating Data Using Group Functions
Aggregating Data Using Group FunctionsAggregating Data Using Group Functions
Aggregating Data Using Group Functions
 
pl/sql Procedure
pl/sql Procedurepl/sql Procedure
pl/sql Procedure
 
Aggregate function
Aggregate functionAggregate function
Aggregate function
 
Using the set operators
Using the set operatorsUsing the set operators
Using the set operators
 
Trigger
TriggerTrigger
Trigger
 

Andere mochten auch

Sql queries with answers
Sql queries with answersSql queries with answers
Sql queries with answers
vijaybusu
 
e computer notes - Subqueries
e computer notes - Subqueriese computer notes - Subqueries
e computer notes - Subqueries
ecomputernotes
 
Subqueries, Backups, Users and Privileges
Subqueries, Backups, Users and PrivilegesSubqueries, Backups, Users and Privileges
Subqueries, Backups, Users and Privileges
Ashwin Dinoriya
 

Andere mochten auch (20)

Subqueries -Oracle DataBase
Subqueries -Oracle DataBaseSubqueries -Oracle DataBase
Subqueries -Oracle DataBase
 
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
Structured Query Language (SQL) - Lecture 5 - Introduction to Databases (1007...
 
Sql subquery
Sql subquerySql subquery
Sql subquery
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
Sql queries with answers
Sql queries with answersSql queries with answers
Sql queries with answers
 
1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQL
 
e computer notes - Subqueries
e computer notes - Subqueriese computer notes - Subqueries
e computer notes - Subqueries
 
Subqueries, Backups, Users and Privileges
Subqueries, Backups, Users and PrivilegesSubqueries, Backups, Users and Privileges
Subqueries, Backups, Users and Privileges
 
Black hat hackers
Black hat hackersBlack hat hackers
Black hat hackers
 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals I
 
ORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERSORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERS
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
Oracle: PLSQL Introduction
Oracle: PLSQL IntroductionOracle: PLSQL Introduction
Oracle: PLSQL Introduction
 
Best sql plsql material
Best sql plsql materialBest sql plsql material
Best sql plsql material
 
SQL JOIN
SQL JOINSQL JOIN
SQL JOIN
 
SQL212.2 Introduction to SQL using Oracle Module 2
SQL212.2 Introduction to SQL using Oracle Module 2SQL212.2 Introduction to SQL using Oracle Module 2
SQL212.2 Introduction to SQL using Oracle Module 2
 
SQL : introduction
SQL : introductionSQL : introduction
SQL : introduction
 
SQL Basics
SQL BasicsSQL Basics
SQL Basics
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands
 
DBMS - Normalization
DBMS - NormalizationDBMS - Normalization
DBMS - Normalization
 

Mehr von Randy Riness @ South Puget Sound Community College

Mehr von Randy Riness @ South Puget Sound Community College (20)

Stored procedures
Stored proceduresStored procedures
Stored procedures
 
3 sql overview
3 sql overview3 sql overview
3 sql overview
 
Normalization
NormalizationNormalization
Normalization
 
CIS160 final review
CIS160 final reviewCIS160 final review
CIS160 final review
 
SQL Constraints
SQL ConstraintsSQL Constraints
SQL Constraints
 
CIS 245 Final Review
CIS 245 Final ReviewCIS 245 Final Review
CIS 245 Final Review
 
CIS145 Final Review
CIS145 Final ReviewCIS145 Final Review
CIS145 Final Review
 
Cis166 Final Review C#
Cis166 Final Review C#Cis166 Final Review C#
Cis166 Final Review C#
 
Classes and Objects
Classes and ObjectsClasses and Objects
Classes and Objects
 
CIS245 sql
CIS245 sqlCIS245 sql
CIS245 sql
 
Cis245 Midterm Review
Cis245 Midterm ReviewCis245 Midterm Review
Cis245 Midterm Review
 
CSS
CSSCSS
CSS
 
XPath
XPathXPath
XPath
 
XSLT Overview
XSLT OverviewXSLT Overview
XSLT Overview
 
Views
ViewsViews
Views
 
CIS282 Midterm review
CIS282 Midterm reviewCIS282 Midterm review
CIS282 Midterm review
 
Schemas 2 - Restricting Values
Schemas 2 - Restricting ValuesSchemas 2 - Restricting Values
Schemas 2 - Restricting Values
 
CIS 145 test 1 review
CIS 145 test 1 reviewCIS 145 test 1 review
CIS 145 test 1 review
 
XML schemas
XML schemasXML schemas
XML schemas
 
Document type definitions part 2
Document type definitions part 2Document type definitions part 2
Document type definitions part 2
 

Kürzlich hochgeladen

The Abortion pills for sale in Qatar@Doha [+27737758557] []Deira Dubai Kuwait
The Abortion pills for sale in Qatar@Doha [+27737758557] []Deira Dubai KuwaitThe Abortion pills for sale in Qatar@Doha [+27737758557] []Deira Dubai Kuwait
The Abortion pills for sale in Qatar@Doha [+27737758557] []Deira Dubai Kuwait
daisycvs
 
Jual Obat Aborsi ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan Cytotec
Jual Obat Aborsi ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan CytotecJual Obat Aborsi ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan Cytotec
Jual Obat Aborsi ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan Cytotec
ZurliaSoop
 

Kürzlich hochgeladen (20)

joint cost.pptx COST ACCOUNTING Sixteenth Edition ...
joint cost.pptx  COST ACCOUNTING  Sixteenth Edition                          ...joint cost.pptx  COST ACCOUNTING  Sixteenth Edition                          ...
joint cost.pptx COST ACCOUNTING Sixteenth Edition ...
 
UAE Bur Dubai Call Girls ☏ 0564401582 Call Girl in Bur Dubai
UAE Bur Dubai Call Girls ☏ 0564401582 Call Girl in Bur DubaiUAE Bur Dubai Call Girls ☏ 0564401582 Call Girl in Bur Dubai
UAE Bur Dubai Call Girls ☏ 0564401582 Call Girl in Bur Dubai
 
New 2024 Cannabis Edibles Investor Pitch Deck Template
New 2024 Cannabis Edibles Investor Pitch Deck TemplateNew 2024 Cannabis Edibles Investor Pitch Deck Template
New 2024 Cannabis Edibles Investor Pitch Deck Template
 
PHX May 2024 Corporate Presentation Final
PHX May 2024 Corporate Presentation FinalPHX May 2024 Corporate Presentation Final
PHX May 2024 Corporate Presentation Final
 
Arti Languages Pre Seed Teaser Deck 2024.pdf
Arti Languages Pre Seed Teaser Deck 2024.pdfArti Languages Pre Seed Teaser Deck 2024.pdf
Arti Languages Pre Seed Teaser Deck 2024.pdf
 
WheelTug Short Pitch Deck 2024 | Byond Insights
WheelTug Short Pitch Deck 2024 | Byond InsightsWheelTug Short Pitch Deck 2024 | Byond Insights
WheelTug Short Pitch Deck 2024 | Byond Insights
 
Ooty Call Gril 80022//12248 Only For Sex And High Profile Best Gril Sex Avail...
Ooty Call Gril 80022//12248 Only For Sex And High Profile Best Gril Sex Avail...Ooty Call Gril 80022//12248 Only For Sex And High Profile Best Gril Sex Avail...
Ooty Call Gril 80022//12248 Only For Sex And High Profile Best Gril Sex Avail...
 
Dr. Admir Softic_ presentation_Green Club_ENG.pdf
Dr. Admir Softic_ presentation_Green Club_ENG.pdfDr. Admir Softic_ presentation_Green Club_ENG.pdf
Dr. Admir Softic_ presentation_Green Club_ENG.pdf
 
Pre Engineered Building Manufacturers Hyderabad.pptx
Pre Engineered  Building Manufacturers Hyderabad.pptxPre Engineered  Building Manufacturers Hyderabad.pptx
Pre Engineered Building Manufacturers Hyderabad.pptx
 
Uneak White's Personal Brand Exploration Presentation
Uneak White's Personal Brand Exploration PresentationUneak White's Personal Brand Exploration Presentation
Uneak White's Personal Brand Exploration Presentation
 
The Abortion pills for sale in Qatar@Doha [+27737758557] []Deira Dubai Kuwait
The Abortion pills for sale in Qatar@Doha [+27737758557] []Deira Dubai KuwaitThe Abortion pills for sale in Qatar@Doha [+27737758557] []Deira Dubai Kuwait
The Abortion pills for sale in Qatar@Doha [+27737758557] []Deira Dubai Kuwait
 
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60% in 6 Months
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60%  in 6 MonthsSEO Case Study: How I Increased SEO Traffic & Ranking by 50-60%  in 6 Months
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60% in 6 Months
 
Putting the SPARK into Virtual Training.pptx
Putting the SPARK into Virtual Training.pptxPutting the SPARK into Virtual Training.pptx
Putting the SPARK into Virtual Training.pptx
 
GUWAHATI 💋 Call Girl 9827461493 Call Girls in Escort service book now
GUWAHATI 💋 Call Girl 9827461493 Call Girls in  Escort service book nowGUWAHATI 💋 Call Girl 9827461493 Call Girls in  Escort service book now
GUWAHATI 💋 Call Girl 9827461493 Call Girls in Escort service book now
 
Lundin Gold - Q1 2024 Conference Call Presentation (Revised)
Lundin Gold - Q1 2024 Conference Call Presentation (Revised)Lundin Gold - Q1 2024 Conference Call Presentation (Revised)
Lundin Gold - Q1 2024 Conference Call Presentation (Revised)
 
Kalyan Call Girl 98350*37198 Call Girls in Escort service book now
Kalyan Call Girl 98350*37198 Call Girls in Escort service book nowKalyan Call Girl 98350*37198 Call Girls in Escort service book now
Kalyan Call Girl 98350*37198 Call Girls in Escort service book now
 
Jual Obat Aborsi ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan Cytotec
Jual Obat Aborsi ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan CytotecJual Obat Aborsi ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan Cytotec
Jual Obat Aborsi ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan Cytotec
 
Unveiling Falcon Invoice Discounting: Leading the Way as India's Premier Bill...
Unveiling Falcon Invoice Discounting: Leading the Way as India's Premier Bill...Unveiling Falcon Invoice Discounting: Leading the Way as India's Premier Bill...
Unveiling Falcon Invoice Discounting: Leading the Way as India's Premier Bill...
 
Berhampur Call Girl Just Call 8084732287 Top Class Call Girl Service Available
Berhampur Call Girl Just Call 8084732287 Top Class Call Girl Service AvailableBerhampur Call Girl Just Call 8084732287 Top Class Call Girl Service Available
Berhampur Call Girl Just Call 8084732287 Top Class Call Girl Service Available
 
Lucknow Housewife Escorts by Sexy Bhabhi Service 8250092165
Lucknow Housewife Escorts  by Sexy Bhabhi Service 8250092165Lucknow Housewife Escorts  by Sexy Bhabhi Service 8250092165
Lucknow Housewife Escorts by Sexy Bhabhi Service 8250092165
 

Subqueries

  • 2. Subqueries • A subquery is one SELECT statement inside a second SELECT statement – May be used throughout the main query, in SELECT, FROM, WHERE or HAVING – Parentheses control order of execution
  • 3. Sample Subqueries • Display the price and average price of all books: SELECT Price, (SELECT Avg(Price) FROM titles) AS AveragePrice FROM titles • Display all books with a higher than average price: SELECT title FROM titles WHERE Price>(SELECT Avg(Price) FROM titles)
  • 4. Subquery Results • Scalar values: Subqueries may return a single value • Lists: Subqueries may return one or more rows – Some situations require a single column list – Typically use IN or EXISTS to test
  • 5. Scalar Subqueries Example • Display titles that have the highest price: SELECT title, price FROM titles WHERE Price = (SELECT Max(price) FROM Titles)
  • 6. List Subqueries Example • Display the publishers who have published cook books: SELECT pub_name FROM publishers WHERE pub_id IN (SELECT pub_id FROM titles WHERE [type] LIKE ‘%cook%’)
  • 7. Correlated Subqueries • A correlated subquery uses a value from the main query as part of the inner query – Data from each row in the main query is “passed” to the subquery for processing • Typically a processing-intensive operation – Subquery must be re-run with new value(s) for each row
  • 8. Correlated Subquery Example • Display all books with a higher than average price for that type of book SELECT title FROM titles t1 WHERE price > (SELECT Avg(price) FROM titles t2 WHERE t1.type = t2.type)
  • 9. Using Subqueries - 1 • If data that’s known is from one table and data to return is in a second table • Display authors who have written books (titleauthors represents what’s known): SELECT au_fname, au_lname FROM authors WHERE au_id IN (SELECT au_id FROM titleauthors)
  • 10. Using Subqueries – 2 • If data to return depends on a calculation from a related set • Display books where actual sales have exceeded projected sales: SELECT title FROM titles t WHERE projected_sales < (SELECT sum(qty_shipped) FROM salesdetails sd WHERE t.title_id=sd.title_id)