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

PPT
SQL subquery
Vikas Gupta
 
PPTX
SQL JOIN
Ritwik Das
 
PPTX
Inner join and outer join
Nargis Ehsan
 
PPTX
STRUCTURE OF SQL QUERIES
VENNILAV6
 
PPTX
set operators.pptx
Anusha sivakumar
 
PPTX
SUBQUERIES.pptx
RenugadeviR5
 
PPTX
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
Abhishek590097
 
PPTX
sql function(ppt)
Ankit Dubey
 
SQL subquery
Vikas Gupta
 
SQL JOIN
Ritwik Das
 
Inner join and outer join
Nargis Ehsan
 
STRUCTURE OF SQL QUERIES
VENNILAV6
 
set operators.pptx
Anusha sivakumar
 
SUBQUERIES.pptx
RenugadeviR5
 
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
Abhishek590097
 
sql function(ppt)
Ankit Dubey
 

What's hot (20)

PPTX
SQL Joins.pptx
Ankit Rai
 
PPTX
joins in database
Sultan Arshad
 
PPTX
Normalization in DBMS
Prateek Parimal
 
PDF
Database Normalization
Arun Sharma
 
PPTX
Aggregate function
Rayhan Chowdhury
 
PDF
View & index in SQL
Swapnali Pawar
 
PPTX
FUNCTION DEPENDENCY AND TYPES & EXAMPLE
Vraj Patel
 
PPTX
Join
Kanchana Rani G
 
PPT
Joins in SQL
Vigneshwaran Sankaran
 
PPT
Databases: Normalisation
Damian T. Gordon
 
PDF
Bca data structures linked list mrs.sowmya jyothi
Sowmya Jyothi
 
PDF
Normalization | (1NF) |(2NF) (3NF)|BCNF| 4NF |5NF
Biplap Bhattarai
 
PPTX
SQL Join Basic
Naimul Arif
 
PPTX
Linked list
KalaivaniKS1
 
PPT
Aggregate functions
sinhacp
 
PPTX
DATABASE CONSTRAINTS
sunanditaAnand
 
PPTX
Relational model
Dabbal Singh Mahara
 
PDF
Serializability
Pyingkodi Maran
 
SQL Joins.pptx
Ankit Rai
 
joins in database
Sultan Arshad
 
Normalization in DBMS
Prateek Parimal
 
Database Normalization
Arun Sharma
 
Aggregate function
Rayhan Chowdhury
 
View & index in SQL
Swapnali Pawar
 
FUNCTION DEPENDENCY AND TYPES & EXAMPLE
Vraj Patel
 
Joins in SQL
Vigneshwaran Sankaran
 
Databases: Normalisation
Damian T. Gordon
 
Bca data structures linked list mrs.sowmya jyothi
Sowmya Jyothi
 
Normalization | (1NF) |(2NF) (3NF)|BCNF| 4NF |5NF
Biplap Bhattarai
 
SQL Join Basic
Naimul Arif
 
Linked list
KalaivaniKS1
 
Aggregate functions
sinhacp
 
DATABASE CONSTRAINTS
sunanditaAnand
 
Relational model
Dabbal Singh Mahara
 
Serializability
Pyingkodi Maran
 
Ad

Viewers also liked (20)

PPTX
Sql subquery
Raveena Thakur
 
PPT
DBMS : Relational Algebra
Sridhar Baithi
 
PPTX
Data integrity Dbms presentation 12 cs 18
Engr Imran Ashraf
 
PPT
Dbms ii mca-ch5-ch6-relational algebra-2013
Prosanta Ghosh
 
PPTX
SQL Data Manipulation
khalid alkhafagi
 
PPTX
T-SQL Overview
Ahmed Elbaz
 
PPTX
trigger dbms
kuldeep100
 
PPT
Er & eer to relational mapping
saurabhshertukde
 
PPTX
Advanced DBMS presentation
Hindustan Petroleum
 
PPTX
Acid properties
Abhilasha Lahigude
 
PDF
Overview of security in DBMS
Vatroslav Mileusnić
 
PPT
4. SQL in DBMS
koolkampus
 
PPT
Presentation on dbms(relational calculus)
yourbookworldanil
 
PPT
6. Integrity and Security in DBMS
koolkampus
 
PDF
CBSE XII Database Concepts And MySQL Presentation
Guru Ji
 
PPT
Dbms models
devgocool
 
PPT
16. Concurrency Control in DBMS
koolkampus
 
PPTX
Data Manipulation Language
Jas Singh Bhasin
 
PPT
15. Transactions in DBMS
koolkampus
 
Sql subquery
Raveena Thakur
 
DBMS : Relational Algebra
Sridhar Baithi
 
Data integrity Dbms presentation 12 cs 18
Engr Imran Ashraf
 
Dbms ii mca-ch5-ch6-relational algebra-2013
Prosanta Ghosh
 
SQL Data Manipulation
khalid alkhafagi
 
T-SQL Overview
Ahmed Elbaz
 
trigger dbms
kuldeep100
 
Er & eer to relational mapping
saurabhshertukde
 
Advanced DBMS presentation
Hindustan Petroleum
 
Acid properties
Abhilasha Lahigude
 
Overview of security in DBMS
Vatroslav Mileusnić
 
4. SQL in DBMS
koolkampus
 
Presentation on dbms(relational calculus)
yourbookworldanil
 
6. Integrity and Security in DBMS
koolkampus
 
CBSE XII Database Concepts And MySQL Presentation
Guru Ji
 
Dbms models
devgocool
 
16. Concurrency Control in DBMS
koolkampus
 
Data Manipulation Language
Jas Singh Bhasin
 
15. Transactions in DBMS
koolkampus
 
Ad

Similar to Nested Queries Lecture (20)

PPTX
Subqueries, Backups, Users and Privileges
Ashwin Dinoriya
 
PPT
Les18
Vijay Kumar
 
PPTX
Module 3.1.pptx
ANSHVAJPAI
 
PPT
e computer notes - Advanced subqueries
ecomputernotes
 
PPT
Les06
Sudharsan S
 
PPTX
Data base management system full details
NitinYadav690862
 
PPTX
Sub query example with advantage and disadvantages
Sarfaraz Ghanta
 
PDF
CS121Lec05.pdf
georgejustymirobi1
 
PDF
SQL Queries .pdf
srinathpurushotham
 
PPTX
OracleSQLraining.pptx
Rajendra Jain
 
PDF
Subqueries For Superheroes
Tracy McKibben
 
PDF
Tech Jam 01 - Database Querying
Rodger Oates
 
PDF
12 things Oracle DBAs must know about SQL
SolarWinds
 
PPT
mis4200notes7_2 .ppt-sharing thispptnotmine
MariaLuisaCarlos
 
PPT
mis4200notes7_2.ppt
PrasannaRavisetti
 
PPT
mis4200not type of joins in dbms pdddddpt
Punit gupta
 
PPTX
MULTIPLE TABLES
ASHABOOPATHY
 
PPT
Transact SQL (T-SQL) for Beginners (A New Hope)
Andrea Allred
 
PPTX
SQL with PostgreSQL - Getting Started
Or Chen
 
PDF
Why Use EXPLAIN FORMAT=JSON?
Sveta Smirnova
 
Subqueries, Backups, Users and Privileges
Ashwin Dinoriya
 
Module 3.1.pptx
ANSHVAJPAI
 
e computer notes - Advanced subqueries
ecomputernotes
 
Data base management system full details
NitinYadav690862
 
Sub query example with advantage and disadvantages
Sarfaraz Ghanta
 
CS121Lec05.pdf
georgejustymirobi1
 
SQL Queries .pdf
srinathpurushotham
 
OracleSQLraining.pptx
Rajendra Jain
 
Subqueries For Superheroes
Tracy McKibben
 
Tech Jam 01 - Database Querying
Rodger Oates
 
12 things Oracle DBAs must know about SQL
SolarWinds
 
mis4200notes7_2 .ppt-sharing thispptnotmine
MariaLuisaCarlos
 
mis4200notes7_2.ppt
PrasannaRavisetti
 
mis4200not type of joins in dbms pdddddpt
Punit gupta
 
MULTIPLE TABLES
ASHABOOPATHY
 
Transact SQL (T-SQL) for Beginners (A New Hope)
Andrea Allred
 
SQL with PostgreSQL - Getting Started
Or Chen
 
Why Use EXPLAIN FORMAT=JSON?
Sveta Smirnova
 

Recently uploaded (20)

PPTX
Services offered by Dynamic Solutions in Pakistan
DaniyaalAdeemShibli1
 
PDF
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
Q-Advise
 
PPTX
oapresentation.pptx
mehatdhavalrajubhai
 
PPTX
Role Of Python In Programing Language.pptx
jaykoshti048
 
PDF
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
PPTX
Explanation about Structures in C language.pptx
Veeral Rathod
 
PDF
Why Use Open Source Reporting Tools for Business Intelligence.pdf
Varsha Nayak
 
PPTX
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pptx
Certivo Inc
 
PDF
The Role of Automation and AI in EHS Management for Data Centers.pdf
TECH EHS Solution
 
PDF
Micromaid: A simple Mermaid-like chart generator for Pharo
ESUG
 
PDF
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
PPTX
AZ900_SLA_Pricing_2025_LondonIT (1).pptx
chumairabdullahph
 
PDF
How to Seamlessly Integrate Salesforce Data Cloud with Marketing Cloud.pdf
NSIQINFOTECH
 
PPTX
EU POPs Limits & Digital Product Passports Compliance Strategy 2025.pptx
Certivo Inc
 
PPTX
Presentation of Computer CLASS 2 .pptx
darshilchaudhary558
 
PDF
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
Hironori Washizaki
 
PPTX
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
DOCX
The Future of Smart Factories Why Embedded Analytics Leads the Way
Varsha Nayak
 
PPTX
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
PPTX
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Services offered by Dynamic Solutions in Pakistan
DaniyaalAdeemShibli1
 
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
Q-Advise
 
oapresentation.pptx
mehatdhavalrajubhai
 
Role Of Python In Programing Language.pptx
jaykoshti048
 
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
Explanation about Structures in C language.pptx
Veeral Rathod
 
Why Use Open Source Reporting Tools for Business Intelligence.pdf
Varsha Nayak
 
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pptx
Certivo Inc
 
The Role of Automation and AI in EHS Management for Data Centers.pdf
TECH EHS Solution
 
Micromaid: A simple Mermaid-like chart generator for Pharo
ESUG
 
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
AZ900_SLA_Pricing_2025_LondonIT (1).pptx
chumairabdullahph
 
How to Seamlessly Integrate Salesforce Data Cloud with Marketing Cloud.pdf
NSIQINFOTECH
 
EU POPs Limits & Digital Product Passports Compliance Strategy 2025.pptx
Certivo Inc
 
Presentation of Computer CLASS 2 .pptx
darshilchaudhary558
 
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
Hironori Washizaki
 
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
The Future of Smart Factories Why Embedded Analytics Leads the Way
Varsha Nayak
 
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 

Nested Queries Lecture

  • 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