SlideShare a Scribd company logo
1 of 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)

More Related Content

What's hot

Oracle sql analytic functions
Oracle sql analytic functionsOracle sql analytic functions
Oracle sql analytic functions
mamamowebby
 

What's hot (20)

Sql joins
Sql joinsSql joins
Sql joins
 
Oracle Database Trigger
Oracle Database TriggerOracle Database Trigger
Oracle Database Trigger
 
Sql(structured query language)
Sql(structured query language)Sql(structured query language)
Sql(structured query language)
 
SQL Joins.pptx
SQL Joins.pptxSQL Joins.pptx
SQL Joins.pptx
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Training
 
Sub query_SQL
Sub query_SQLSub query_SQL
Sub query_SQL
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
 
Sql Constraints
Sql ConstraintsSql Constraints
Sql Constraints
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base
 
Oracle sql analytic functions
Oracle sql analytic functionsOracle sql analytic functions
Oracle sql analytic functions
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 
SQL Constraints
SQL ConstraintsSQL Constraints
SQL Constraints
 
View & index in SQL
View & index in SQLView & index in SQL
View & index in SQL
 
SQL Functions
SQL FunctionsSQL Functions
SQL Functions
 
Advanced sql
Advanced sqlAdvanced sql
Advanced sql
 
Set operators
Set  operatorsSet  operators
Set operators
 
Joins in SQL
Joins in SQLJoins in SQL
Joins in SQL
 
Sql Functions And Procedures
Sql Functions And ProceduresSql Functions And Procedures
Sql Functions And Procedures
 

Viewers also liked

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
 

Viewers also liked (20)

Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries Lecture
 
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 joins
Sql joinsSql joins
Sql joins
 
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
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
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
 
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
 

More from Randy Riness @ South Puget Sound Community College

More from 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
 
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
 
Document type definitions part 1
Document type definitions part 1Document type definitions part 1
Document type definitions part 1
 

Recently uploaded

Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al MizharAl Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
allensay1
 
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
 

Recently uploaded (20)

Getting Real with AI - Columbus DAW - May 2024 - Nick Woo from AlignAI
Getting Real with AI - Columbus DAW - May 2024 - Nick Woo from AlignAIGetting Real with AI - Columbus DAW - May 2024 - Nick Woo from AlignAI
Getting Real with AI - Columbus DAW - May 2024 - Nick Woo from AlignAI
 
Organizational Transformation Lead with Culture
Organizational Transformation Lead with CultureOrganizational Transformation Lead with Culture
Organizational Transformation Lead with Culture
 
Durg CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN durg ESCORTS
Durg CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN durg ESCORTSDurg CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN durg ESCORTS
Durg CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN durg ESCORTS
 
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
 
Nashik Call Girl Just Call 7091819311 Top Class Call Girl Service Available
Nashik Call Girl Just Call 7091819311 Top Class Call Girl Service AvailableNashik Call Girl Just Call 7091819311 Top Class Call Girl Service Available
Nashik Call Girl Just Call 7091819311 Top Class Call Girl Service Available
 
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
 
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al MizharAl Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
 
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
 
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
 
JAJPUR CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN JAJPUR ESCORTS
JAJPUR CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN JAJPUR  ESCORTSJAJPUR CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN JAJPUR  ESCORTS
JAJPUR CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN JAJPUR ESCORTS
 
Cannabis Legalization World Map: 2024 Updated
Cannabis Legalization World Map: 2024 UpdatedCannabis Legalization World Map: 2024 Updated
Cannabis Legalization World Map: 2024 Updated
 
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
 
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
 
PARK STREET 💋 Call Girl 9827461493 Call Girls in Escort service book now
PARK STREET 💋 Call Girl 9827461493 Call Girls in  Escort service book nowPARK STREET 💋 Call Girl 9827461493 Call Girls in  Escort service book now
PARK STREET 💋 Call Girl 9827461493 Call Girls in Escort service book now
 
Falcon Invoice Discounting: Empowering Your Business Growth
Falcon Invoice Discounting: Empowering Your Business GrowthFalcon Invoice Discounting: Empowering Your Business Growth
Falcon Invoice Discounting: Empowering Your Business Growth
 
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
 
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)
 
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...
 
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
 
Falcon Invoice Discounting: Unlock Your Business Potential
Falcon Invoice Discounting: Unlock Your Business PotentialFalcon Invoice Discounting: Unlock Your Business Potential
Falcon Invoice Discounting: Unlock Your Business Potential
 

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)