Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries SQL Subqueries I one SQL query can be used in the evaluation of another I a query that is part of another is called a subquery I subqueries can be used I at the “top” level of an SQL query (union, intersection and difference) I in the WHERE clause I in the FROM clause
66
Embed
SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
SQL Subqueries
I one SQL query can be used in the evaluation ofanother
I a query that is part of another is called a subqueryI subqueries can be used
I at the “top” level of an SQL query (union, intersectionand difference)
I in the WHERE clauseI in the FROM clause
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Union of two tablesFind all locations where a drinker lives or a pub is located:
Pubs:
name locHorse and Hound BHound and Hare IMarch Hare BBlack Horse IWhite Horse B
Drinkers:
name locAlice IBob BCarol IDave BEve S
(SELECT loc FROM Drinkers)UNION
(SELECT loc FROM Pubs);
locBloomsburyIslingtonStratford
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Union of two tablesFind all locations where a drinker lives or a pub is located:
Pubs:
name locHorse and Hound BHound and Hare IMarch Hare BBlack Horse IWhite Horse B
Drinkers:
name locAlice IBob BCarol IDave BEve S
(SELECT loc FROM Drinkers)UNION
(SELECT loc FROM Pubs);
locBloomsburyIslingtonStratford
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Union of two tablesFind all locations where a drinker lives or a pub is located:
Pubs:
name locHorse and Hound BHound and Hare IMarch Hare BBlack Horse IWhite Horse B
Drinkers:
name locAlice IBob BCarol IDave BEve S
(SELECT loc FROM Drinkers)UNION
(SELECT loc FROM Pubs);
locBloomsburyIslingtonStratford
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Union of two tablesFind all locations where a drinker lives or a pub is located:
Pubs:
name locHorse and Hound BHound and Hare IMarch Hare BBlack Horse IWhite Horse B
Drinkers:
name locAlice IBob BCarol IDave BEve S
(SELECT loc FROM Drinkers)UNION
(SELECT loc FROM Pubs);
locBloomsburyIslingtonStratford
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Intersection of two tables
Find locations where both a drinker lives and a pub islocated:
(SELECT loc FROM Drinkers)INTERSECT
(SELECT loc FROM Pubs);
locBloomsburyIslington
Note that UNION, INTERSECT and EXCEPT do removeduplicate answers.
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Intersection of two tables
Find locations where both a drinker lives and a pub islocated:
(SELECT loc FROM Drinkers)INTERSECT
(SELECT loc FROM Pubs);
locBloomsburyIslington
Note that UNION, INTERSECT and EXCEPT do removeduplicate answers.
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Intersection of two tables
Find locations where both a drinker lives and a pub islocated:
(SELECT loc FROM Drinkers)INTERSECT
(SELECT loc FROM Pubs);
locBloomsburyIslington
Note that UNION, INTERSECT and EXCEPT do removeduplicate answers.
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Intersection of two tables
Find locations where both a drinker lives and a pub islocated:
(SELECT loc FROM Drinkers)INTERSECT
(SELECT loc FROM Pubs);
locBloomsburyIslington
Note that UNION, INTERSECT and EXCEPT do removeduplicate answers.
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Difference of two tables
Find locations where a drinker lives but no pub is located:
(SELECT loc FROM Drinkers)EXCEPT
(SELECT loc FROM Pubs);
locStratford
Note that the subqueries have to be defined over thesame set of attributes - loc in this case.
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Difference of two tables
Find locations where a drinker lives but no pub is located:
(SELECT loc FROM Drinkers)EXCEPT
(SELECT loc FROM Pubs);
locStratford
Note that the subqueries have to be defined over thesame set of attributes - loc in this case.
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Difference of two tables
Find locations where a drinker lives but no pub is located:
(SELECT loc FROM Drinkers)EXCEPT
(SELECT loc FROM Pubs);
locStratford
Note that the subqueries have to be defined over thesame set of attributes - loc in this case.
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Difference of two tables
Find locations where a drinker lives but no pub is located:
(SELECT loc FROM Drinkers)EXCEPT
(SELECT loc FROM Pubs);
locStratford
Note that the subqueries have to be defined over thesame set of attributes - loc in this case.
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Union with renaming
Find the names of all pubs beginning with ‘H’ in thedatabase:
(SELECT name AS pub FROM Pubs WHERE name LIKE ’H%’)UNION
(SELECT pub FROM Sells WHERE pub LIKE ’H%’)UNION
(SELECT pub FROM Visits WHERE pub LIKE ’H%’);
pubHorse and HoundHound and Hare
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Union with renaming
Find the names of all pubs beginning with ‘H’ in thedatabase:
(SELECT name AS pub FROM Pubs WHERE name LIKE ’H%’)UNION
(SELECT pub FROM Sells WHERE pub LIKE ’H%’)UNION
(SELECT pub FROM Visits WHERE pub LIKE ’H%’);
pubHorse and HoundHound and Hare
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Union with renaming
Find the names of all pubs beginning with ‘H’ in thedatabase:
(SELECT name AS pub FROM Pubs WHERE name LIKE ’H%’)UNION
(SELECT pub FROM Sells WHERE pub LIKE ’H%’)UNION
(SELECT pub FROM Visits WHERE pub LIKE ’H%’);
pubHorse and HoundHound and Hare
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Conditions involving relationsThere are a number of SQL operators that apply to arelation R and return a Boolean result (true or false):
I EXISTS R is true if and only if R is not emptyI s IN R is true if and only if s is equal to one of the
values in R (where, e.g., s is an attribute and R is aunary (one-column) relation)
I s > ALL R is true if and only if s is greater than everyvalue in R
I s > ANY R is true if and only if s is greater than atleast one value in R
I we can use any other comparison operator instead of> above
I we can put NOT in front of IN to test if s is equal tono value in R
I EXISTS, ANY and ALL can be negated by puttingNOT in front of the whole expression
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Conditions involving relationsThere are a number of SQL operators that apply to arelation R and return a Boolean result (true or false):
I EXISTS R is true if and only if R is not empty
I s IN R is true if and only if s is equal to one of thevalues in R (where, e.g., s is an attribute and R is aunary (one-column) relation)
I s > ALL R is true if and only if s is greater than everyvalue in R
I s > ANY R is true if and only if s is greater than atleast one value in R
I we can use any other comparison operator instead of> above
I we can put NOT in front of IN to test if s is equal tono value in R
I EXISTS, ANY and ALL can be negated by puttingNOT in front of the whole expression
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Conditions involving relationsThere are a number of SQL operators that apply to arelation R and return a Boolean result (true or false):
I EXISTS R is true if and only if R is not emptyI s IN R is true if and only if s is equal to one of the
values in R (where, e.g., s is an attribute and R is aunary (one-column) relation)
I s > ALL R is true if and only if s is greater than everyvalue in R
I s > ANY R is true if and only if s is greater than atleast one value in R
I we can use any other comparison operator instead of> above
I we can put NOT in front of IN to test if s is equal tono value in R
I EXISTS, ANY and ALL can be negated by puttingNOT in front of the whole expression
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Conditions involving relationsThere are a number of SQL operators that apply to arelation R and return a Boolean result (true or false):
I EXISTS R is true if and only if R is not emptyI s IN R is true if and only if s is equal to one of the
values in R (where, e.g., s is an attribute and R is aunary (one-column) relation)
I s > ALL R is true if and only if s is greater than everyvalue in R
I s > ANY R is true if and only if s is greater than atleast one value in R
I we can use any other comparison operator instead of> above
I we can put NOT in front of IN to test if s is equal tono value in R
I EXISTS, ANY and ALL can be negated by puttingNOT in front of the whole expression
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Conditions involving relationsThere are a number of SQL operators that apply to arelation R and return a Boolean result (true or false):
I EXISTS R is true if and only if R is not emptyI s IN R is true if and only if s is equal to one of the
values in R (where, e.g., s is an attribute and R is aunary (one-column) relation)
I s > ALL R is true if and only if s is greater than everyvalue in R
I s > ANY R is true if and only if s is greater than atleast one value in R
I we can use any other comparison operator instead of> above
I we can put NOT in front of IN to test if s is equal tono value in R
I EXISTS, ANY and ALL can be negated by puttingNOT in front of the whole expression
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Conditions involving relationsThere are a number of SQL operators that apply to arelation R and return a Boolean result (true or false):
I EXISTS R is true if and only if R is not emptyI s IN R is true if and only if s is equal to one of the
values in R (where, e.g., s is an attribute and R is aunary (one-column) relation)
I s > ALL R is true if and only if s is greater than everyvalue in R
I s > ANY R is true if and only if s is greater than atleast one value in R
I we can use any other comparison operator instead of> above
I we can put NOT in front of IN to test if s is equal tono value in R
I EXISTS, ANY and ALL can be negated by puttingNOT in front of the whole expression
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Conditions involving relationsThere are a number of SQL operators that apply to arelation R and return a Boolean result (true or false):
I EXISTS R is true if and only if R is not emptyI s IN R is true if and only if s is equal to one of the
values in R (where, e.g., s is an attribute and R is aunary (one-column) relation)
I s > ALL R is true if and only if s is greater than everyvalue in R
I s > ANY R is true if and only if s is greater than atleast one value in R
I we can use any other comparison operator instead of> above
I we can put NOT in front of IN to test if s is equal tono value in R
I EXISTS, ANY and ALL can be negated by puttingNOT in front of the whole expression
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Conditions involving relationsThere are a number of SQL operators that apply to arelation R and return a Boolean result (true or false):
I EXISTS R is true if and only if R is not emptyI s IN R is true if and only if s is equal to one of the
values in R (where, e.g., s is an attribute and R is aunary (one-column) relation)
I s > ALL R is true if and only if s is greater than everyvalue in R
I s > ANY R is true if and only if s is greater than atleast one value in R
I we can use any other comparison operator instead of> above
I we can put NOT in front of IN to test if s is equal tono value in R
I EXISTS, ANY and ALL can be negated by puttingNOT in front of the whole expression
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Using ALL
Find the pub, beer and price for the cheapest beer soldby any pub:
SELECT *FROM SellsWHERE price <= ALL
(SELECT priceFROM Sells);
pub beer priceHorse and Hound Bad Habit 1.50
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Using ALL
Find the pub, beer and price for the cheapest beer soldby any pub:
SELECT *FROM SellsWHERE price <= ALL
(SELECT priceFROM Sells);
pub beer priceHorse and Hound Bad Habit 1.50
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Using ALL
Find the pub, beer and price for the cheapest beer soldby any pub:
Find the number of people who visit the March Hare:
SELECT COUNT(drinker) AS numberVisitingFROM VisitsWHERE pub=’March Hare’;
numberVisiting2
Could also use COUNT(*) to count the number of rows.
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Counting tuples
Find the number of people who visit the March Hare:
SELECT COUNT(drinker) AS numberVisitingFROM VisitsWHERE pub=’March Hare’;
numberVisiting2
Could also use COUNT(*) to count the number of rows.
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Counting tuples
Find the number of people who visit the March Hare:
SELECT COUNT(drinker) AS numberVisitingFROM VisitsWHERE pub=’March Hare’;
numberVisiting2
Could also use COUNT(*) to count the number of rows.
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Counting tuples
Find the number of people who visit the March Hare:
SELECT COUNT(drinker) AS numberVisitingFROM VisitsWHERE pub=’March Hare’;
numberVisiting2
Could also use COUNT(*) to count the number of rows.
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
GroupingI Sometimes we don’t want an aggregation applied to
an entire column.I Instead we want to group the tuples of a relation into
groups based on the value of some attribute.I E.g., we can group Sells tuples according to pub
value.
pub beer priceHorse and Hound Bad Habit 1.50Horse and Hound Rampant Ram 2.00Hound and Hare Shining Wit 2.75Hound and Hare Rampant Ram 2.50March Hare Bad Habit 1.75March Hare Rampant Ram 2.50Black Horse Bad Habit 2.50Black Horse Shining Wit 2.25Black Horse Rampant Ram 2.50White Horse Rampant Ram 2.75
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
GroupingI Sometimes we don’t want an aggregation applied to
an entire column.I Instead we want to group the tuples of a relation into
groups based on the value of some attribute.I E.g., we can group Sells tuples according to pub
value.
pub beer priceHorse and Hound Bad Habit 1.50Horse and Hound Rampant Ram 2.00Hound and Hare Shining Wit 2.75Hound and Hare Rampant Ram 2.50March Hare Bad Habit 1.75March Hare Rampant Ram 2.50Black Horse Bad Habit 2.50Black Horse Shining Wit 2.25Black Horse Rampant Ram 2.50White Horse Rampant Ram 2.75
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Grouping example
Find the average price of the beer sold in each pub:
SELECT pub, AVG(price) AS avgPriceFROM SellsGROUP BY pub;
pub avgPriceHorse and Hound 1.75Hound and Hare 2.675March Hare 2.125Black Horse 2.416White Horse 2.75
Each pub appears once in the answer.
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Grouping example
Find the average price of the beer sold in each pub:
SELECT pub, AVG(price) AS avgPriceFROM SellsGROUP BY pub;
pub avgPriceHorse and Hound 1.75Hound and Hare 2.675March Hare 2.125Black Horse 2.416White Horse 2.75
Each pub appears once in the answer.
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Grouping example
Find the average price of the beer sold in each pub:
SELECT pub, AVG(price) AS avgPriceFROM SellsGROUP BY pub;
pub avgPriceHorse and Hound 1.75Hound and Hare 2.675March Hare 2.125Black Horse 2.416White Horse 2.75
Each pub appears once in the answer.
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Grouping example
Find the average price of the beer sold in each pub:
SELECT pub, AVG(price) AS avgPriceFROM SellsGROUP BY pub;
pub avgPriceHorse and Hound 1.75Hound and Hare 2.675March Hare 2.125Black Horse 2.416White Horse 2.75
Each pub appears once in the answer.
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Selecting Groups
Find the average price of the beer sold in each pub thatsells at least two beers:
SELECT pub, AVG(price) AS avgPriceFROM SellsGROUP BY pubHAVING COUNT(beer) > 1;
pub avgPriceHorse and Hound 1.75Hound and Hare 2.675March Hare 2.125Black Horse 2.416
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Selecting Groups
Find the average price of the beer sold in each pub thatsells at least two beers:
SELECT pub, AVG(price) AS avgPriceFROM SellsGROUP BY pubHAVING COUNT(beer) > 1;
pub avgPriceHorse and Hound 1.75Hound and Hare 2.675March Hare 2.125Black Horse 2.416
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Selecting Groups
Find the average price of the beer sold in each pub thatsells at least two beers:
SELECT pub, AVG(price) AS avgPriceFROM SellsGROUP BY pubHAVING COUNT(beer) > 1;
pub avgPriceHorse and Hound 1.75Hound and Hare 2.675March Hare 2.125Black Horse 2.416
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Grouping, Aggregation and Nulls
I The value NULL is ignored in any aggregation.I But NULL is treated as an ordinary value when
forming groups.I When we perform any aggregation other than
COUNT over an empty set (bag) of values, the resultis NULL. The COUNT of an empty set (bag) is 0.
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Ordering the output
I we can ask for the tuples in the output to be sortedI by using ORDER BY clause after any WHERE,
GROUP BY or HAVING clausesI ORDER BY is followed by a list of attributesI ordering is by default ascending (ASC) but we can
specify DESC after any attribute for descending order
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
Other Comparison Operators
I IN, e.g., a IN (b1, b2, . . . )I BETWEEN, e.g., a BETWEEN b and cI LIKE — see next slideI REGEX, e.g., a REGEX b — a matches pattern b,
where b uses regular expression syntax (see online)
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
String Pattern Matching with LIKEWhich pubs have names that include the string ’Hare’?:
SELECT nameFROM PubsWHERE name LIKE ’%Hare%’
name locationHorse and Hound BloomsburyHound and Hare IslingtonMarch Hare BloomsburyBlack Horse IslingtonWhite Horse Bloomsbury
⇓nameHound and HareMarch Hare
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
String Pattern Matching with LIKEWhich pubs have names that include the string ’Hare’?:
SELECT nameFROM PubsWHERE name LIKE ’%Hare%’
name locationHorse and Hound BloomsburyHound and Hare IslingtonMarch Hare BloomsburyBlack Horse IslingtonWhite Horse Bloomsbury
⇓nameHound and HareMarch Hare
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
String Pattern Matching with LIKEWhich pubs have names that include the string ’Hare’?:
SELECT nameFROM PubsWHERE name LIKE ’%Hare%’
name locationHorse and Hound BloomsburyHound and Hare IslingtonMarch Hare BloomsburyBlack Horse IslingtonWhite Horse Bloomsbury
⇓
nameHound and HareMarch Hare
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
String Pattern Matching with LIKEWhich pubs have names that include the string ’Hare’?:
SELECT nameFROM PubsWHERE name LIKE ’%Hare%’
name locationHorse and Hound BloomsburyHound and Hare IslingtonMarch Hare BloomsburyBlack Horse IslingtonWhite Horse Bloomsbury
⇓nameHound and HareMarch Hare
DatabaseManagement
Peter Wood
SQL queriesSQL Subqueries
Aggregation Queries
References
I Chapter 6 of [CB10]I Chapters 3 and 4 of [SKS11]I Chapter 6 of [UW08]