SlideShare a Scribd company logo
1 of 29
Download to read offline
Nested Queries
Felipe dos Santos Costa
fsc7@yahoo.com
May 2016
Topics
●
Nested queries
●
CREATE
●
UPDATE
●
DELETE
●
The Subquery as Scalar Operand
●
Comparisons Using Subqueries
●
Subqueries with ANY, IN, or SOME
●
Subqueries with ALL
●
Row Subqueries
●
Subqueries with EXISTS or NOT EXISTS
●
Correlated Subqueries
●
Subqueries in the FROM Clause
●
Subquery Errors
●
Optimizing Subqueries
●
Rewriting Subqueries as Joins
What are Nested Queries?
● A Subquery or Inner query or Nested query is a query within
another SQL query and embedded within the WHERE clause.
● Subqueries (also known as inner queries or nested queries) are
a tool for performing operations in multiple steps.
– Subqueries can be used in several places within a query, but
it’s easiest to start with the FROM statement.
●
Subqueries can return individual values or a list of records
What are Nested Queries?
Example
● SELECT * FROM t1 WHERE column1 = (SELECT column1 FROM t2);
– Outer query Subquery
Advantages
● The main advantages of subqueries are:
– They allow queries that are structured so that it is
possible to isolate each part of a statement.
– They provide alternative ways to perform operations
that would otherwise require complex joins and unions.
– More readable than complex joins or unions.
● Indeed, it was the innovation of subqueries that gave
people the original idea of calling the early SQL
“Structured Query Language.”
Return
● Scalar (a single value)
● Single row
● Single column
● Table (one or more rows of one or more columns).
Other info
● Subqueries must be enclosed with parenthesis
● A subquery can contain many of the clauses that an
ordinary SELECT can: DISTINCT, GROUP BY, ORDER BY,
LIMIT, joins, index hints, UNION constructs, comments,
functions, and so on.
● A subquery's outer statement can be any one of: SELECT,
INSERT, UPDATE, DELETE, SET, or DO.
● In MySQL, you cannot modify a table and select from the
same table in a subquery
Database used for example
● Historical series of fertility rate
CREATE
● CREATE TABLE countries AS (SELECT DISTINCT country
from fertility)
UPDATE
● How can I get the updated fertility rate for each country?
● SELECT country, year, fertility FROM fertility WHERE year = 2015
GROUP BY country
● How can I update my country table using subquery?
● UPDATE countries c SET c.fertility = (
SELECT fertility
FROM fertility f
WHERE YEAR =2015
AND f.country = c.country
GROUP BY country),
c.year =2015
Another example
● Two sources of data
UPDATE
● How to get one column (continent) from the second
source?
● UPDATE countries c SET c.continent =
(SELECT continent_code FROM countries2 c2
WHERE c2.name = c.country )
DELETE
● How to delete countries which has no data
● DELETE FROM countries WHERE country IN (SELECT
country FROM fertility GROUP BY country HAVING
SUM(fertility) IS NULL) *
● * It might give error on MySQL workbench because of
safe update mode. (Error Code: 1175) – You must disable
safe mode.
The Subquery as Scalar Operand
● A scalar subquery is a simple operand, and you can use it almost
anywhere a single column value or literal is legal, and you can expect
it to have those characteristics that all operands have: a data type, a
length, an indication that it can be NULL, and so on. For example:
● CREATE TABLE t1 (s1 INT, s2 CHAR(5) NOT NULL);
● INSERT INTO t1 VALUES(100, 'abcde');
● SELECT (SELECT s2 FROM t1);
● The subquery in this SELECT returns a single value ('abcde') that has
a data type of CHAR, a length of 5, a character set and collation
equal to the defaults in effect at CREATE TABLE time, and an
indication that the value in the column can be NULL.
Example
● Fertility average of Europe and South America
– SELECT (SELECT AVG(fertility) FROM countries
WHERE continent = 'EU'),
(SELECT AVG(fertility) FROM countries WHERE
continent = 'SA')
Comparisons Using Subqueries
● = > < >= <= <> != <=>
● What are the countries in South America which have
fertility smaller than Max european fertility?
● SELECT * FROM countries
WHERE fertility < (
SELECT MAX(fertility)
FROM countries
WHERE continent='EU')
AND continent = 'SA';
Subqueries with ANY, IN, or SOME
● Which countries in Africa have fertility rate < than any
european country?
● SELECT * FROM countries
WHERE fertility < ANY
(SELECT fertility FROM countries WHERE
continent='EU')
AND continent = 'AF';
● When used with a subquery, IN is an alias for = ANY
Subqueries with ALL
● SELECT s1 FROM t1 WHERE s1 > ALL
(SELECT s1 FROM t2);
● Which countries in Africa have the fertility rate bigger
than all countries of Asia and South America
● SELECT s1 FROM t1 WHERE s1 <> ALL
(SELECT s1 FROM t2);
● NOT IN is an alias for <> ALL
Row Subqueries
● A row subquery is a subquery variant that returns a single
row and can thus return more than one column value
● SELECT * FROM t1 WHERE (col1, col2) = (SELECT col3,
col4 FROM t2 WHERE id = 10);
● Which countries are on the average of 2015?
● SELECT country, year, fertility FROM fertility
WHERE (TRUNCATE(fertility,1), year) =
(SELECT TRUNCATE(AVG(fertility),1), year FROM
countries);
Row Subqueries
● SELECT * FROM t1 WHERE ROW(col1, col2) = (SELECT
col3, col4 FROM t2 WHERE id = 10);
● The row constructor and the row returned by the subquery
must contain the same number of values.
● The following query answers the request, “find all rows in
table t1 that also exist in table t2”:
● SELECT column1, column2, column3
FROM t1
WHERE (column1, column2, column3) IN
(SELECT column1, column2, column3 FROM t2);
Row Subqueries
● Which countries have the same fertility rate than Estonia
(rounding)?
● SELECT * FROM fertility
WHERE ROW(TRUNCATE(fertility,1), year) =
(SELECT TRUNCATE(fertility,1), year
FROM countries
WHERE country='Estonia');
Subqueries with EXISTS or NOT EXISTS
● SELECT column1 FROM t1 WHERE EXISTS (SELECT * FROM t2);
● What countries exists in my two datasources?
– SELECT DISTINCT country FROM countries c
WHERE EXISTS (SELECT name FROM countries2 c2 WHERE
c.country = c2.name);
● Now the opposite
– SELECT DISTINCT country FROM countries c
WHERE NOT EXISTS (SELECT name FROM countries2 c2
WHERE c.country = c2.name);
Correlated Subqueries
● A correlated subquery is a subquery that contains a reference to
a table that also appears in the outer query.
● SELECT * FROM t1
WHERE column1 = ANY (SELECT column1 FROM t2
WHERE t2.column2 = t1.column2);
● In which years Estonia had fertility rate bigger than it's historical
average.
● SELECT * FROM fertility f
WHERE fertility >
(SELECT AVG(fertility) FROM fertility f2 WHERE f.country =
f2.country AND f2.country = 'Estonia' GROUP BY f2.country);
Correlated Subqueries
● In which years Estonia had fertility smaller than average
for 2000 to 2015 (1.53)?
● SELECT * FROM fertility f
WHERE fertility <
(SELECT AVG(fertility)
FROM fertility f2
WHERE f.country = f2.country AND f2.country = 'Estonia'
AND f2.year BETWEEN 2000 AND 2015
GROUP BY f2.country);
Subqueries in the FROM Clause
● SELECT ... FROM (subquery) [AS] name …
● Average of fertility for each continent using historical average
for each country
●
SELECT continent, AVG(avg_fertility)
FROM
(SELECT AVG(fertility) as avg_fertility, country
FROM fertility f
WHERE year BETWEEN 2000 AND 2015
GROUP BY country) AS avgfert
JOIN countries c ON (c.country = avgfert.country)
GROUP BY continent
If we have time
● https://www.google.com/fusiontables/DataSource?doc
id=1tVN1toVTUb1Ju3gaLxIHTtlcST_bdaR7UgU2OfJO#rows:
id=1
● https://www.google.com/fusiontables/DataSource?do
cid=1kg8Pn9JEheqA8whqsmZBgM3quEiPTyFrasfUv5hQ
References
● MySQL 5.7 Reference Manual - http://dev.mysql.com/doc/refman/5.7/en/
● Data Country and Continents
http://www.geekality.net/2011/08/21/country-names-continent-names-
and-iso-3166-codes-for-mysql/
● Historical Fertility Rate - http://www.gapminder.org/data/
https://ourworldindata.org/grapher/total-fertility-rate?tab=map
● Nested Queries
http://www.w3resource.com/sql/subqueries/nested-subqueries.php
● Subqueries -
https://sqlschool.modeanalytics.com/advanced/subqueries/
● Using Nested Queries -
http://sqlzoo.net/wiki/Using_nested_SELECT
Questions?
● Thank you!

More Related Content

What's hot (20)

basic structure of SQL FINAL.pptx
basic structure of SQL FINAL.pptxbasic structure of SQL FINAL.pptx
basic structure of SQL FINAL.pptx
 
Triggers
TriggersTriggers
Triggers
 
Sql operators & functions 3
Sql operators & functions 3Sql operators & functions 3
Sql operators & functions 3
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
Relational Data Model Introduction
Relational Data Model IntroductionRelational Data Model Introduction
Relational Data Model Introduction
 
SQL Constraints
SQL ConstraintsSQL Constraints
SQL Constraints
 
Nested queries in database
Nested queries in databaseNested queries in database
Nested queries in database
 
SQL(DDL & DML)
SQL(DDL & DML)SQL(DDL & DML)
SQL(DDL & DML)
 
MySQL Views
MySQL ViewsMySQL Views
MySQL Views
 
Relational model
Relational modelRelational model
Relational model
 
Introduction to data structure ppt
Introduction to data structure pptIntroduction to data structure ppt
Introduction to data structure ppt
 
Types Of Keys in DBMS
Types Of Keys in DBMSTypes Of Keys in DBMS
Types Of Keys in DBMS
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL Commands
 
trigger dbms
trigger dbmstrigger dbms
trigger dbms
 
Query processing-and-optimization
Query processing-and-optimizationQuery processing-and-optimization
Query processing-and-optimization
 
Sql subquery
Sql  subquerySql  subquery
Sql subquery
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
Dbms relational model
Dbms relational modelDbms relational model
Dbms relational model
 
Aggregate function
Aggregate functionAggregate function
Aggregate function
 
Integrity Constraints
Integrity ConstraintsIntegrity Constraints
Integrity Constraints
 

Viewers also liked

DBMS : Relational Algebra
DBMS : Relational Algebra DBMS : Relational Algebra
DBMS : Relational Algebra Sridhar Baithi
 
Data integrity Dbms presentation 12 cs 18
Data integrity Dbms presentation 12 cs 18Data integrity Dbms presentation 12 cs 18
Data integrity Dbms presentation 12 cs 18Engr Imran Ashraf
 
FUNCTION DEPENDENCY AND TYPES & EXAMPLE
FUNCTION DEPENDENCY  AND TYPES & EXAMPLEFUNCTION DEPENDENCY  AND TYPES & EXAMPLE
FUNCTION DEPENDENCY AND TYPES & EXAMPLEVraj Patel
 
Dbms ii mca-ch5-ch6-relational algebra-2013
Dbms ii mca-ch5-ch6-relational algebra-2013Dbms ii mca-ch5-ch6-relational algebra-2013
Dbms ii mca-ch5-ch6-relational algebra-2013Prosanta Ghosh
 
Er & eer to relational mapping
Er & eer to relational mappingEr & eer to relational mapping
Er & eer to relational mappingsaurabhshertukde
 
4. SQL in DBMS
4. SQL in DBMS4. SQL in DBMS
4. SQL in DBMSkoolkampus
 
Presentation on dbms(relational calculus)
Presentation on dbms(relational calculus)Presentation on dbms(relational calculus)
Presentation on dbms(relational calculus)yourbookworldanil
 
6. Integrity and Security in DBMS
6. Integrity and Security in DBMS6. Integrity and Security in DBMS
6. Integrity and Security in DBMSkoolkampus
 
CBSE XII Database Concepts And MySQL Presentation
CBSE XII Database Concepts And MySQL PresentationCBSE XII Database Concepts And MySQL Presentation
CBSE XII Database Concepts And MySQL PresentationGuru Ji
 
16. Concurrency Control in DBMS
16. Concurrency Control in DBMS16. Concurrency Control in DBMS
16. Concurrency Control in DBMSkoolkampus
 
Data Manipulation Language
Data Manipulation LanguageData Manipulation Language
Data Manipulation LanguageJas Singh Bhasin
 

Viewers also liked (20)

Subqueries
SubqueriesSubqueries
Subqueries
 
DBMS : Relational Algebra
DBMS : Relational Algebra DBMS : Relational Algebra
DBMS : Relational Algebra
 
Data integrity Dbms presentation 12 cs 18
Data integrity Dbms presentation 12 cs 18Data integrity Dbms presentation 12 cs 18
Data integrity Dbms presentation 12 cs 18
 
FUNCTION DEPENDENCY AND TYPES & EXAMPLE
FUNCTION DEPENDENCY  AND TYPES & EXAMPLEFUNCTION DEPENDENCY  AND TYPES & EXAMPLE
FUNCTION DEPENDENCY AND TYPES & EXAMPLE
 
SQL subquery
SQL subquerySQL subquery
SQL subquery
 
Dbms ii mca-ch5-ch6-relational algebra-2013
Dbms ii mca-ch5-ch6-relational algebra-2013Dbms ii mca-ch5-ch6-relational algebra-2013
Dbms ii mca-ch5-ch6-relational algebra-2013
 
SQL Data Manipulation
SQL Data ManipulationSQL Data Manipulation
SQL Data Manipulation
 
T-SQL Overview
T-SQL OverviewT-SQL Overview
T-SQL Overview
 
Er & eer to relational mapping
Er & eer to relational mappingEr & eer to relational mapping
Er & eer to relational mapping
 
Advanced DBMS presentation
Advanced DBMS presentationAdvanced DBMS presentation
Advanced DBMS presentation
 
Acid properties
Acid propertiesAcid properties
Acid properties
 
Overview of security in DBMS
Overview of security in DBMSOverview of security in DBMS
Overview of security in DBMS
 
4. SQL in DBMS
4. SQL in DBMS4. SQL in DBMS
4. SQL in DBMS
 
Presentation on dbms(relational calculus)
Presentation on dbms(relational calculus)Presentation on dbms(relational calculus)
Presentation on dbms(relational calculus)
 
6. Integrity and Security in DBMS
6. Integrity and Security in DBMS6. Integrity and Security in DBMS
6. Integrity and Security in DBMS
 
CBSE XII Database Concepts And MySQL Presentation
CBSE XII Database Concepts And MySQL PresentationCBSE XII Database Concepts And MySQL Presentation
CBSE XII Database Concepts And MySQL Presentation
 
Databases: Normalisation
Databases: NormalisationDatabases: Normalisation
Databases: Normalisation
 
Dbms models
Dbms modelsDbms models
Dbms models
 
16. Concurrency Control in DBMS
16. Concurrency Control in DBMS16. Concurrency Control in DBMS
16. Concurrency Control in DBMS
 
Data Manipulation Language
Data Manipulation LanguageData Manipulation Language
Data Manipulation Language
 

Similar to Nested Queries Lecture

Bis 345-final-exam-guide-set-1-new
Bis 345-final-exam-guide-set-1-newBis 345-final-exam-guide-set-1-new
Bis 345-final-exam-guide-set-1-newassignmentcloud85
 
SQL Fundamentals
SQL FundamentalsSQL Fundamentals
SQL FundamentalsBrian Foote
 
Bootcamp sql fundamentals bootcamp_part1
Bootcamp   sql fundamentals  bootcamp_part1Bootcamp   sql fundamentals  bootcamp_part1
Bootcamp sql fundamentals bootcamp_part1varunbhatt23
 
Sql basics
Sql basicsSql basics
Sql basicsKumar
 
SQL: The Language of Databases
SQL: The Language of DatabasesSQL: The Language of Databases
SQL: The Language of DatabasesRJ Podeschi
 
States, state graphs and transition testing
States, state graphs and transition testingStates, state graphs and transition testing
States, state graphs and transition testingABHISHEK KUMAR
 
Fun with ClickHouse Window Functions-2021-08-19.pdf
Fun with ClickHouse Window Functions-2021-08-19.pdfFun with ClickHouse Window Functions-2021-08-19.pdf
Fun with ClickHouse Window Functions-2021-08-19.pdfAltinity Ltd
 
Fun with click house window functions webinar slides 2021-08-19
Fun with click house window functions webinar slides  2021-08-19Fun with click house window functions webinar slides  2021-08-19
Fun with click house window functions webinar slides 2021-08-19Altinity Ltd
 
The ultimate-guide-to-sql
The ultimate-guide-to-sqlThe ultimate-guide-to-sql
The ultimate-guide-to-sqlMcNamaraChiwaye
 
Bootcamp sql fundamental
Bootcamp sql fundamentalBootcamp sql fundamental
Bootcamp sql fundamentalvarunbhatt23
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Trainingbixxman
 
Unit 3-Select Options and Aggregate Functions in SQL (1).pptx
Unit 3-Select Options and Aggregate Functions in SQL (1).pptxUnit 3-Select Options and Aggregate Functions in SQL (1).pptx
Unit 3-Select Options and Aggregate Functions in SQL (1).pptxHAMEEDHUSSAINBU21CSE
 

Similar to Nested Queries Lecture (20)

Sql
SqlSql
Sql
 
Bis 345-final-exam-guide-set-1-new
Bis 345-final-exam-guide-set-1-newBis 345-final-exam-guide-set-1-new
Bis 345-final-exam-guide-set-1-new
 
Oracle SQL Advanced
Oracle SQL AdvancedOracle SQL Advanced
Oracle SQL Advanced
 
Crash course in sql
Crash course in sqlCrash course in sql
Crash course in sql
 
SQL Fundamentals
SQL FundamentalsSQL Fundamentals
SQL Fundamentals
 
Bootcamp sql fundamentals bootcamp_part1
Bootcamp   sql fundamentals  bootcamp_part1Bootcamp   sql fundamentals  bootcamp_part1
Bootcamp sql fundamentals bootcamp_part1
 
Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
 
Sql General
Sql General Sql General
Sql General
 
SQL Basics
SQL BasicsSQL Basics
SQL Basics
 
Sql basics
Sql basicsSql basics
Sql basics
 
SQL: The Language of Databases
SQL: The Language of DatabasesSQL: The Language of Databases
SQL: The Language of Databases
 
States, state graphs and transition testing
States, state graphs and transition testingStates, state graphs and transition testing
States, state graphs and transition testing
 
Fun with ClickHouse Window Functions-2021-08-19.pdf
Fun with ClickHouse Window Functions-2021-08-19.pdfFun with ClickHouse Window Functions-2021-08-19.pdf
Fun with ClickHouse Window Functions-2021-08-19.pdf
 
Fun with click house window functions webinar slides 2021-08-19
Fun with click house window functions webinar slides  2021-08-19Fun with click house window functions webinar slides  2021-08-19
Fun with click house window functions webinar slides 2021-08-19
 
The ultimate-guide-to-sql
The ultimate-guide-to-sqlThe ultimate-guide-to-sql
The ultimate-guide-to-sql
 
Bootcamp sql fundamental
Bootcamp sql fundamentalBootcamp sql fundamental
Bootcamp sql fundamental
 
2.2 sql commands
2.2 sql commands2.2 sql commands
2.2 sql commands
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Training
 
Unit 3-Select Options and Aggregate Functions in SQL (1).pptx
Unit 3-Select Options and Aggregate Functions in SQL (1).pptxUnit 3-Select Options and Aggregate Functions in SQL (1).pptx
Unit 3-Select Options and Aggregate Functions in SQL (1).pptx
 
SQL Windowing
SQL WindowingSQL Windowing
SQL Windowing
 

Recently uploaded

%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxalwaysnagaraju26
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyAnusha Are
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 

Recently uploaded (20)

%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 

Nested Queries Lecture

  • 1. Nested Queries Felipe dos Santos Costa fsc7@yahoo.com May 2016
  • 2. Topics ● Nested queries ● CREATE ● UPDATE ● DELETE ● The Subquery as Scalar Operand ● Comparisons Using Subqueries ● Subqueries with ANY, IN, or SOME ● Subqueries with ALL ● Row Subqueries ● Subqueries with EXISTS or NOT EXISTS ● Correlated Subqueries ● Subqueries in the FROM Clause ● Subquery Errors ● Optimizing Subqueries ● Rewriting Subqueries as Joins
  • 3. What are Nested Queries? ● A Subquery or Inner query or Nested query is a query within another SQL query and embedded within the WHERE clause. ● Subqueries (also known as inner queries or nested queries) are a tool for performing operations in multiple steps. – Subqueries can be used in several places within a query, but it’s easiest to start with the FROM statement. ● Subqueries can return individual values or a list of records
  • 4. What are Nested Queries?
  • 5. Example ● SELECT * FROM t1 WHERE column1 = (SELECT column1 FROM t2); – Outer query Subquery
  • 6. Advantages ● The main advantages of subqueries are: – They allow queries that are structured so that it is possible to isolate each part of a statement. – They provide alternative ways to perform operations that would otherwise require complex joins and unions. – More readable than complex joins or unions. ● Indeed, it was the innovation of subqueries that gave people the original idea of calling the early SQL “Structured Query Language.”
  • 7. Return ● Scalar (a single value) ● Single row ● Single column ● Table (one or more rows of one or more columns).
  • 8. Other info ● Subqueries must be enclosed with parenthesis ● A subquery can contain many of the clauses that an ordinary SELECT can: DISTINCT, GROUP BY, ORDER BY, LIMIT, joins, index hints, UNION constructs, comments, functions, and so on. ● A subquery's outer statement can be any one of: SELECT, INSERT, UPDATE, DELETE, SET, or DO. ● In MySQL, you cannot modify a table and select from the same table in a subquery
  • 9. Database used for example ● Historical series of fertility rate
  • 10. CREATE ● CREATE TABLE countries AS (SELECT DISTINCT country from fertility)
  • 11. UPDATE ● How can I get the updated fertility rate for each country? ● SELECT country, year, fertility FROM fertility WHERE year = 2015 GROUP BY country ● How can I update my country table using subquery? ● UPDATE countries c SET c.fertility = ( SELECT fertility FROM fertility f WHERE YEAR =2015 AND f.country = c.country GROUP BY country), c.year =2015
  • 12. Another example ● Two sources of data
  • 13. UPDATE ● How to get one column (continent) from the second source? ● UPDATE countries c SET c.continent = (SELECT continent_code FROM countries2 c2 WHERE c2.name = c.country )
  • 14. DELETE ● How to delete countries which has no data ● DELETE FROM countries WHERE country IN (SELECT country FROM fertility GROUP BY country HAVING SUM(fertility) IS NULL) * ● * It might give error on MySQL workbench because of safe update mode. (Error Code: 1175) – You must disable safe mode.
  • 15. The Subquery as Scalar Operand ● A scalar subquery is a simple operand, and you can use it almost anywhere a single column value or literal is legal, and you can expect it to have those characteristics that all operands have: a data type, a length, an indication that it can be NULL, and so on. For example: ● CREATE TABLE t1 (s1 INT, s2 CHAR(5) NOT NULL); ● INSERT INTO t1 VALUES(100, 'abcde'); ● SELECT (SELECT s2 FROM t1); ● The subquery in this SELECT returns a single value ('abcde') that has a data type of CHAR, a length of 5, a character set and collation equal to the defaults in effect at CREATE TABLE time, and an indication that the value in the column can be NULL.
  • 16. Example ● Fertility average of Europe and South America – SELECT (SELECT AVG(fertility) FROM countries WHERE continent = 'EU'), (SELECT AVG(fertility) FROM countries WHERE continent = 'SA')
  • 17. Comparisons Using Subqueries ● = > < >= <= <> != <=> ● What are the countries in South America which have fertility smaller than Max european fertility? ● SELECT * FROM countries WHERE fertility < ( SELECT MAX(fertility) FROM countries WHERE continent='EU') AND continent = 'SA';
  • 18. Subqueries with ANY, IN, or SOME ● Which countries in Africa have fertility rate < than any european country? ● SELECT * FROM countries WHERE fertility < ANY (SELECT fertility FROM countries WHERE continent='EU') AND continent = 'AF'; ● When used with a subquery, IN is an alias for = ANY
  • 19. Subqueries with ALL ● SELECT s1 FROM t1 WHERE s1 > ALL (SELECT s1 FROM t2); ● Which countries in Africa have the fertility rate bigger than all countries of Asia and South America ● SELECT s1 FROM t1 WHERE s1 <> ALL (SELECT s1 FROM t2); ● NOT IN is an alias for <> ALL
  • 20. Row Subqueries ● A row subquery is a subquery variant that returns a single row and can thus return more than one column value ● SELECT * FROM t1 WHERE (col1, col2) = (SELECT col3, col4 FROM t2 WHERE id = 10); ● Which countries are on the average of 2015? ● SELECT country, year, fertility FROM fertility WHERE (TRUNCATE(fertility,1), year) = (SELECT TRUNCATE(AVG(fertility),1), year FROM countries);
  • 21. Row Subqueries ● SELECT * FROM t1 WHERE ROW(col1, col2) = (SELECT col3, col4 FROM t2 WHERE id = 10); ● The row constructor and the row returned by the subquery must contain the same number of values. ● The following query answers the request, “find all rows in table t1 that also exist in table t2”: ● SELECT column1, column2, column3 FROM t1 WHERE (column1, column2, column3) IN (SELECT column1, column2, column3 FROM t2);
  • 22. Row Subqueries ● Which countries have the same fertility rate than Estonia (rounding)? ● SELECT * FROM fertility WHERE ROW(TRUNCATE(fertility,1), year) = (SELECT TRUNCATE(fertility,1), year FROM countries WHERE country='Estonia');
  • 23. Subqueries with EXISTS or NOT EXISTS ● SELECT column1 FROM t1 WHERE EXISTS (SELECT * FROM t2); ● What countries exists in my two datasources? – SELECT DISTINCT country FROM countries c WHERE EXISTS (SELECT name FROM countries2 c2 WHERE c.country = c2.name); ● Now the opposite – SELECT DISTINCT country FROM countries c WHERE NOT EXISTS (SELECT name FROM countries2 c2 WHERE c.country = c2.name);
  • 24. Correlated Subqueries ● A correlated subquery is a subquery that contains a reference to a table that also appears in the outer query. ● SELECT * FROM t1 WHERE column1 = ANY (SELECT column1 FROM t2 WHERE t2.column2 = t1.column2); ● In which years Estonia had fertility rate bigger than it's historical average. ● SELECT * FROM fertility f WHERE fertility > (SELECT AVG(fertility) FROM fertility f2 WHERE f.country = f2.country AND f2.country = 'Estonia' GROUP BY f2.country);
  • 25. Correlated Subqueries ● In which years Estonia had fertility smaller than average for 2000 to 2015 (1.53)? ● SELECT * FROM fertility f WHERE fertility < (SELECT AVG(fertility) FROM fertility f2 WHERE f.country = f2.country AND f2.country = 'Estonia' AND f2.year BETWEEN 2000 AND 2015 GROUP BY f2.country);
  • 26. Subqueries in the FROM Clause ● SELECT ... FROM (subquery) [AS] name … ● Average of fertility for each continent using historical average for each country ● SELECT continent, AVG(avg_fertility) FROM (SELECT AVG(fertility) as avg_fertility, country FROM fertility f WHERE year BETWEEN 2000 AND 2015 GROUP BY country) AS avgfert JOIN countries c ON (c.country = avgfert.country) GROUP BY continent
  • 27. If we have time ● https://www.google.com/fusiontables/DataSource?doc id=1tVN1toVTUb1Ju3gaLxIHTtlcST_bdaR7UgU2OfJO#rows: id=1 ● https://www.google.com/fusiontables/DataSource?do cid=1kg8Pn9JEheqA8whqsmZBgM3quEiPTyFrasfUv5hQ
  • 28. References ● MySQL 5.7 Reference Manual - http://dev.mysql.com/doc/refman/5.7/en/ ● Data Country and Continents http://www.geekality.net/2011/08/21/country-names-continent-names- and-iso-3166-codes-for-mysql/ ● Historical Fertility Rate - http://www.gapminder.org/data/ https://ourworldindata.org/grapher/total-fertility-rate?tab=map ● Nested Queries http://www.w3resource.com/sql/subqueries/nested-subqueries.php ● Subqueries - https://sqlschool.modeanalytics.com/advanced/subqueries/ ● Using Nested Queries - http://sqlzoo.net/wiki/Using_nested_SELECT