SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database...

66
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

Transcript of SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database...

Page 1: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 2: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 3: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 4: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 5: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 6: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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.

Page 7: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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.

Page 8: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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.

Page 9: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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.

Page 10: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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.

Page 11: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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.

Page 12: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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.

Page 13: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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.

Page 14: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 15: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 16: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 17: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 18: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 19: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 20: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 21: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 22: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 23: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 24: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 25: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 26: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 27: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 28: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

DatabaseManagement

Peter Wood

SQL queriesSQL Subqueries

Aggregation Queries

Using IN

Find the beers sold by pubs visited by Bob:

SELECT beerFROM SellsWHERE pub IN

(SELECT pubFROM VisitsWHERE drinker = ’Bob’);

Previously we had:

SELECT beerFROM Sells, VisitsWHERE drinker = ’Bob’AND Sells.pub=Visits.pub;

Page 29: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

DatabaseManagement

Peter Wood

SQL queriesSQL Subqueries

Aggregation Queries

Using IN

Find the beers sold by pubs visited by Bob:

SELECT beerFROM SellsWHERE pub IN

(SELECT pubFROM VisitsWHERE drinker = ’Bob’);

Previously we had:

SELECT beerFROM Sells, VisitsWHERE drinker = ’Bob’AND Sells.pub=Visits.pub;

Page 30: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

DatabaseManagement

Peter Wood

SQL queriesSQL Subqueries

Aggregation Queries

Using IN

Find the beers sold by pubs visited by Bob:

SELECT beerFROM SellsWHERE pub IN

(SELECT pubFROM VisitsWHERE drinker = ’Bob’);

Previously we had:

SELECT beerFROM Sells, VisitsWHERE drinker = ’Bob’AND Sells.pub=Visits.pub;

Page 31: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

DatabaseManagement

Peter Wood

SQL queriesSQL Subqueries

Aggregation Queries

Using IN for intersection

MySQL does not support the INTERSECT operator

So to find locations where both a drinker lives and a pubis located:

(SELECT loc FROM Drinkers)INTERSECT

(SELECT loc FROM Pubs);

we can use:

SELECT DISTINCT loc FROM DrinkersWHERE loc IN

(SELECT loc FROM Pubs);

Page 32: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

DatabaseManagement

Peter Wood

SQL queriesSQL Subqueries

Aggregation Queries

Using IN for intersection

MySQL does not support the INTERSECT operator

So to find locations where both a drinker lives and a pubis located:

(SELECT loc FROM Drinkers)INTERSECT

(SELECT loc FROM Pubs);

we can use:

SELECT DISTINCT loc FROM DrinkersWHERE loc IN

(SELECT loc FROM Pubs);

Page 33: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

DatabaseManagement

Peter Wood

SQL queriesSQL Subqueries

Aggregation Queries

Using IN for intersection

MySQL does not support the INTERSECT operator

So to find locations where both a drinker lives and a pubis located:

(SELECT loc FROM Drinkers)INTERSECT

(SELECT loc FROM Pubs);

we can use:

SELECT DISTINCT loc FROM DrinkersWHERE loc IN

(SELECT loc FROM Pubs);

Page 34: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

DatabaseManagement

Peter Wood

SQL queriesSQL Subqueries

Aggregation Queries

Using NOT IN for difference

MySQL does not support the EXCEPT operator

So to find locations where a drinker lives but no pub islocated:

(SELECT loc FROM Drinkers)EXCEPT

(SELECT loc FROM Pubs);

we can use:

SELECT DISTINCT loc FROM DrinkersWHERE loc NOT IN

(SELECT loc FROM Pubs);

Page 35: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

DatabaseManagement

Peter Wood

SQL queriesSQL Subqueries

Aggregation Queries

Using NOT IN for difference

MySQL does not support the EXCEPT operator

So to find locations where a drinker lives but no pub islocated:

(SELECT loc FROM Drinkers)EXCEPT

(SELECT loc FROM Pubs);

we can use:

SELECT DISTINCT loc FROM DrinkersWHERE loc NOT IN

(SELECT loc FROM Pubs);

Page 36: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

DatabaseManagement

Peter Wood

SQL queriesSQL Subqueries

Aggregation Queries

Using NOT IN for difference

MySQL does not support the EXCEPT operator

So to find locations where a drinker lives but no pub islocated:

(SELECT loc FROM Drinkers)EXCEPT

(SELECT loc FROM Pubs);

we can use:

SELECT DISTINCT loc FROM DrinkersWHERE loc NOT IN

(SELECT loc FROM Pubs);

Page 37: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

DatabaseManagement

Peter Wood

SQL queriesSQL Subqueries

Aggregation Queries

Correlated subqueries

I In the previous queries, the subquery could beevaluated once, e.g. to find the pubs visited by Bob.

I This was because the subquery was independent ofthe outer query.

I This is not the case when the subquery refers to atuple variable in the outer query.

I In such a case, we have what is known as acorrelated subquery.

Page 38: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

DatabaseManagement

Peter Wood

SQL queriesSQL Subqueries

Aggregation Queries

Example of correlated subquery

Find the names of drinkers who live where no pub islocated:

SELECT nameFROM DrinkersWHERE NOT EXISTS

(SELECT nameFROM PubsWHERE location=Drinkers.location);

Subquery refers to the tuple variable (or relation) Drinkersin the outer query.

nameEve

Page 39: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

DatabaseManagement

Peter Wood

SQL queriesSQL Subqueries

Aggregation Queries

Example of correlated subquery

Find the names of drinkers who live where no pub islocated:

SELECT nameFROM DrinkersWHERE NOT EXISTS

(SELECT nameFROM PubsWHERE location=Drinkers.location);

Subquery refers to the tuple variable (or relation) Drinkersin the outer query.

nameEve

Page 40: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

DatabaseManagement

Peter Wood

SQL queriesSQL Subqueries

Aggregation Queries

Example of correlated subquery

Find the names of drinkers who live where no pub islocated:

SELECT nameFROM DrinkersWHERE NOT EXISTS

(SELECT nameFROM PubsWHERE location=Drinkers.location);

Subquery refers to the tuple variable (or relation) Drinkersin the outer query.

nameEve

Page 41: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

DatabaseManagement

Peter Wood

SQL queriesSQL Subqueries

Aggregation Queries

Example of correlated subquery

Find the names of drinkers who live where no pub islocated:

SELECT nameFROM DrinkersWHERE NOT EXISTS

(SELECT nameFROM PubsWHERE location=Drinkers.location);

Subquery refers to the tuple variable (or relation) Drinkersin the outer query.

nameEve

Page 42: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

DatabaseManagement

Peter Wood

SQL queriesSQL Subqueries

Aggregation Queries

Aggregation Operators

I sometimes we may want to “summarise” a number ofvalues in a column

I this can be done using aggregation operatorsI SQL aggregation operators include

I SUM: produces the sum of values in a columnI AVG: produces the average of values in a columnI MIN and MAX: produce the smallest and largest

values, respectively, in a columnI COUNT: produces the number of (not necessarily

distinct) values in a column

Page 43: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

DatabaseManagement

Peter Wood

SQL queriesSQL Subqueries

Aggregation Queries

Finding the minimum value

Find the price of the cheapest beer sold in Bloomsbury:

SELECT MIN(price) AS minPriceFROM SellsWHERE pub IN

(SELECT nameFROM PubsWHERE location=’Bloomsbury’);

minPrice1.50

Page 44: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

DatabaseManagement

Peter Wood

SQL queriesSQL Subqueries

Aggregation Queries

Finding the minimum value

Find the price of the cheapest beer sold in Bloomsbury:

SELECT MIN(price) AS minPriceFROM SellsWHERE pub IN

(SELECT nameFROM PubsWHERE location=’Bloomsbury’);

minPrice1.50

Page 45: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

DatabaseManagement

Peter Wood

SQL queriesSQL Subqueries

Aggregation Queries

Finding the minimum value

Find the price of the cheapest beer sold in Bloomsbury:

SELECT MIN(price) AS minPriceFROM SellsWHERE pub IN

(SELECT nameFROM PubsWHERE location=’Bloomsbury’);

minPrice1.50

Page 46: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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.

Page 47: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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.

Page 48: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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.

Page 49: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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.

Page 50: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 51: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 52: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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.

Page 53: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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.

Page 54: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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.

Page 55: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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.

Page 56: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 57: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 58: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 59: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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.

Page 60: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 61: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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)

Page 62: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 63: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 64: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 65: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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

Page 66: SQL Subqueries Management Databaseptw/teaching/DBM/sql-subqueries.pdfduplicate answers. Database Management Peter Wood SQL queries SQL Subqueries Aggregation Queries Intersection of

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]