SlideShare uma empresa Scribd logo
1 de 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)

Mais conteúdo relacionado

Mais procurados

Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In Sql
Anurag
 
Analytic & Windowing functions in oracle
Analytic & Windowing functions in oracleAnalytic & Windowing functions in oracle
Analytic & Windowing functions in oracle
Logan Palanisamy
 

Mais procurados (20)

Oracle: Joins
Oracle: JoinsOracle: Joins
Oracle: Joins
 
Sql commands
Sql commandsSql commands
Sql commands
 
set operators.pptx
set operators.pptxset operators.pptx
set operators.pptx
 
SQL subquery
SQL subquerySQL subquery
SQL subquery
 
Join
JoinJoin
Join
 
Joins in SQL
Joins in SQLJoins in SQL
Joins in SQL
 
SQL commands
SQL commandsSQL commands
SQL commands
 
Sql commands
Sql commandsSql commands
Sql commands
 
Sql Tutorials
Sql TutorialsSql Tutorials
Sql Tutorials
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In Sql
 
SQL Basics
SQL BasicsSQL Basics
SQL Basics
 
Analytic & Windowing functions in oracle
Analytic & Windowing functions in oracleAnalytic & Windowing functions in oracle
Analytic & Windowing functions in oracle
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
Sql join
Sql  joinSql  join
Sql join
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries Lecture
 
Sql operators & functions 3
Sql operators & functions 3Sql operators & functions 3
Sql operators & functions 3
 
SQL
SQLSQL
SQL
 
SQL Joins With Examples | Edureka
SQL Joins With Examples | EdurekaSQL Joins With Examples | Edureka
SQL Joins With Examples | Edureka
 
Sql ppt
Sql pptSql ppt
Sql ppt
 
MySQL Views
MySQL ViewsMySQL Views
MySQL Views
 

Destaque

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
 

Destaque (20)

Sub query_SQL
Sub query_SQLSub query_SQL
Sub query_SQL
 
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 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
 
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
 

Mais de Randy Riness @ South Puget Sound Community College

Mais de 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
 

Último

Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...
Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...
Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...
amitlee9823
 
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
daisycvs
 
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Sheetaleventcompany
 
Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...
Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...
Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...
lizamodels9
 

Último (20)

Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service AvailableCall Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
 
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
 
Falcon's Invoice Discounting: Your Path to Prosperity
Falcon's Invoice Discounting: Your Path to ProsperityFalcon's Invoice Discounting: Your Path to Prosperity
Falcon's Invoice Discounting: Your Path to Prosperity
 
Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...
Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...
Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...
 
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
 
Pharma Works Profile of Karan Communications
Pharma Works Profile of Karan CommunicationsPharma Works Profile of Karan Communications
Pharma Works Profile of Karan Communications
 
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptxB.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
 
Business Model Canvas (BMC)- A new venture concept
Business Model Canvas (BMC)-  A new venture conceptBusiness Model Canvas (BMC)-  A new venture concept
Business Model Canvas (BMC)- A new venture concept
 
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
 
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
 
Katrina Personal Brand Project and portfolio 1
Katrina Personal Brand Project and portfolio 1Katrina Personal Brand Project and portfolio 1
Katrina Personal Brand Project and portfolio 1
 
Call Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine ServiceCall Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine Service
 
VVVIP Call Girls In Greater Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In Greater Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...VVVIP Call Girls In Greater Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In Greater Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
 
How to Get Started in Social Media for Art League City
How to Get Started in Social Media for Art League CityHow to Get Started in Social Media for Art League City
How to Get Started in Social Media for Art League City
 
Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...
Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...
Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...
 
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesMysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
 
Ensure the security of your HCL environment by applying the Zero Trust princi...
Ensure the security of your HCL environment by applying the Zero Trust princi...Ensure the security of your HCL environment by applying the Zero Trust princi...
Ensure the security of your HCL environment by applying the Zero Trust princi...
 
Cracking the Cultural Competence Code.pptx
Cracking the Cultural Competence Code.pptxCracking the Cultural Competence Code.pptx
Cracking the Cultural Competence Code.pptx
 
Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...
Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...
Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...
 
Forklift Operations: Safety through Cartoons
Forklift Operations: Safety through CartoonsForklift Operations: Safety through Cartoons
Forklift Operations: Safety through Cartoons
 

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)