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

Post on 09-Apr-2018

246 views 6 download

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

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:

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 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;

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;

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;

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);

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);

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);

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);

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);

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);

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.

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

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

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

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

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

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

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

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

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

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]