Top Banner
SCU Holliday - coen 178 7–1 Schedule • Today: Subqueries, Grouping and Aggregation. Read Sections 6.3-6.4. • Next Modifications, Schemas, Views. Read Sections 6.5-6.7. • After that Constraints. Read Sections 7.1-7.3, 7.4.1.
40

Schedule

Jan 04, 2016

Download

Documents

madonna-holman

Schedule. Today: Subqueries, Grouping and Aggregation. Read Sections 6.3-6.4. Next Modifications, Schemas, Views. Read Sections 6.5-6.7. After that Constraints. Read Sections 7.1-7.3, 7.4.1. Union, Intersection, Difference. - PowerPoint PPT Presentation
Welcome message from author
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
Page 1: Schedule

SCU Holliday - coen 178 7–1

Schedule• Today:

Subqueries, Grouping and Aggregation. Read Sections 6.3-6.4.

• Next Modifications, Schemas, Views. Read Sections 6.5-6.7.

• After that Constraints. Read Sections 7.1-7.3, 7.4.1.

Page 2: Schedule

SCU Holliday - coen 178 7–2

Union, Intersection, Difference“(subquery) UNION (subquery)” produces the union of the two relations.• Similarly for INTERSECT, and EXCEPT = set difference.

But: in Oracle set difference is MINUS, not EXCEPT.

ExampleFind the drinkers and beers such that the drinker likes the beer and

frequents a bar that serves it.Likes(drinker, beer)Sells(bar, beer, price)Frequents(drinker, bar)

(SELECT * FROM Likes)INTERSECT

(SELECT drinker, beer FROM Sells, Frequents WHERE Frequents.bar = Sells.bar);

Page 3: Schedule

SCU Holliday - coen 178 7–3

Forcing Set Semantics

• Default for select-from-where is bag; default for union, intersection, and difference is set.

• Force set semantics with DISTINCT after SELECT.Find the different prices charged for beers.

Sells(bar, beer, price)

SELECT DISTINCT priceFROM Sells;

Page 4: Schedule

SCU Holliday - coen 178 7–4

Forcing Bag Semantics

• Force bag semantics with ALL

• In the case of set operations, duplicates are automatically eliminated. To retain duplicates, use union all, intersect all, and except all.

Page 5: Schedule

SCU Holliday - coen 178 7–5

More on Bags• There may be duplicate tuples in the results of SQL

queries. To determine the number of duplicate tuples in the result.

1. If there are c1 copies of a tuple t1 in r and t1 satisfies the predicate P, then there will be c1 copies of t1 in

select * from r where P2. If there are c1 copies of a tuple t1 in r, then there will

be c1 copies of select A from t1 in select A from r3. If there are c1 copies of a tuple t1 in r and c2 copies

of t2 in s, then there will be c1* c2 copies of the tuple t1.t2 in select * from r, s

Page 6: Schedule

SCU Holliday - coen 178 7–6

How many tuples?

select * r=from swhere C = 3

select Bfrom r 

select B s=from r, s select B select Afrom r, s from r,swhere C = 3 where A=C

 

A B

1 a

2 a

C

2

3

3

Page 7: Schedule

SCU Holliday - coen 178 7–7

Forcing Set Semantics with DISTINCT

select distinct B r=from r

 

select distinct B

from r, s s= 

select distinct C

from s

A B

1 a

2 a

C

2

3

3

Page 8: Schedule

SCU Holliday - coen 178 7–8

How many tuples?

(C=3)(s) r=

B(r)

 

B(rs)s=

 B (C=3)(rs)

A (C=3)(rs)

a1

a2

BA

3

3

2

C

Page 9: Schedule

SCU Holliday - coen 178 7–9

Exercise: Use set operations to-

• Find all customers who have both a loan and an account.

• Find all customers who have an account but no loan.

Depositor = (customer-name, account#)

Borrower = (customer-name, loan#)

Page 10: Schedule

SCU Holliday - coen 178 7–10

Answers

(select customer-name from Depositor)

intersect

(select customer-name from Borrower)

 

(select customer-name from Depositor)

except

(select customer-name from Borrower)

Page 11: Schedule

SCU Holliday - coen 178 7–11

Join-Based ExpressionsA number of forms are provided.• Can be used either stand-alone (in place of a select-from-

where) or to define a relation in the FROM-clause.R NATURAL JOIN S (delete duplicate attribute)R JOIN S ON condition (cross product + )

e.g., condition: R.B=S.BR CROSS JOIN S (cross product)R OUTER JOIN S• Outerjoin can be modified by:1. Optional NATURAL in front.2. Optional ON condition at end.3. Optional LEFT, RIGHT, or FULL (default) before OUTER.

LEFT = pad (with NULL) dangling tuples of R only; RIGHT = pad dangling tuples of S only.

Page 12: Schedule

SCU Holliday - coen 178 7–12

Join Exercise

R = S =

What is R natural join S? (no second B)

A B C

a 101 35

b 103 24

b 104 65

D B

Smith 101

Jones 102

Johnson 103

A B C D

a 101 35 Smith

b 103 24 Johnson

Page 13: Schedule

SCU Holliday - coen 178 7–13

Outer Join Exercise

R = S =

What is R natural left outer join S?

A B C

a 101 35

b 103 24

b 104 65

D B

Smith 101

Jones 102

Johnson 103

A B C D

a 101 35 Smith

b 103 24 Johnson

b 104 65 --Null--

Page 14: Schedule

SCU Holliday - coen 178 7–14

Outer Join Exercise

R = S =

What is R natural right outer join S?

A B C

a 101 35

b 103 24

b 104 65

D B

Smith 101

Jones 102

Johnson 103

A B C D

a 101 35 Smith

b 103 24 Johnson

--null-- 102 Jones

Page 15: Schedule

SCU Holliday - coen 178 7–15

Full Outer Join Exercise

R = S =

What is R natural full outer join S?

A B C

a 101 35

b 103 24

b 104 65

D B

Smith 101

Jones 102

Johnson 103

A B C D

a 101 35 Smith

b 103 24 Johnson

B 104 65 --null--

--null-- 102 Jones

Page 16: Schedule

SCU Holliday - coen 178 7–16

Outer Join Exercise

R = S =

R left outer join S on R.B=S.B

A B C

a 101 35

b 103 24

b 104 65

D B

Smith 101

Jones 102

Johnson 103

A B B C D

a 101 101 35 Smith

b 103 103 24 Johnson

b 104 104 65 --Null--

Page 17: Schedule

SCU Holliday - coen 178 7–17

Aggregations

Sum, avg, min, max, and count apply to attributes (columns). Also, count(*) applies to tuples.

Use these in lists following SELECT. (also having)

Output has only one tuple

Sells(bar,beer,price)Find the average price of Bud.

SELECT AVG(price)FROM SellsWHERE beer = 'Bud';

Page 18: Schedule

SCU Holliday - coen 178 7–18

Eliminating DuplicatesBefore Aggregation

Find the number of different prices at which Bud is sold. Sells(bar, beer, price)

SELECT COUNT(DISTINCT price)FROM SellsWHERE beer = 'Bud';

• DISTINCT may be used in any aggregation, but typically only makes sense with COUNT.

Page 19: Schedule

SCU Holliday - coen 178 7–19

Example Using AVG

• Find the average account balance at the Oakland branch.

Account = (branch-name,account#,balance)

select avg(balance)from Accountwhere branch-name = "Oakland“

What does the result look like?

Page 20: Schedule

SCU Holliday - coen 178 7–20

Example Using AVG

• Find the average account balance at the Oakland branch of accounts over $3000.

• Account = (branch-name, account#, balance)

select avg(balance)

from Account

where branch-name =

"Oakland“ and balance>3000

B-name Acc# Balance

Oakland 101 2000

Oakland 102 7000

Oakland 103 5000

Page 21: Schedule

SCU Holliday - coen 178 7–21

GroupingFollow select-from-where by GROUP BY and a list of

attributes.• The relation that is the result of the FROM and WHERE clauses is grouped according to the values of these attributes, and aggregations take place only within a group.

Example:Find the average sales price for each beer. Sells(bar, beer, price)

SELECT beer, AVG(price) FROM Sells GROUP BY beer;

Page 22: Schedule

SCU Holliday - coen 178 7–22

Avg sales price for each beer

SELECT beer, AVG(price)FROM SellsGROUP BY beer;

Bar Beer Price

Joe’s Bud 2.00

Joe’s Miller 3.00

Kelly’s Bud 3.00

O’Shea Miller 5.00

Joe’s Bud 2.00

Kelly’s Bud 3.00

Joe’s Miller 3.00

O’Shea Miller 5.00

Bud 2.00

Bud 3.00

Miller 3.00

Miller 5.00

Bud 2.50

Miller 4.00

Page 23: Schedule

SCU Holliday - coen 178 7–23

ExampleFind, for each drinker, the average price of

Bud at the bars they frequent.Sells(bar, beer, price)

Frequents(drinker, bar)

SELECT drinker, AVG(price)FROM Frequents, SellsWHERE beer = 'Bud' AND

Frequents.bar = Sells.bar

GROUP BY drinker;

Page 24: Schedule

SCU Holliday - coen 178 7–24

When Grouping…

• Note: grouping occurs after the cross product in FROM and the condition in the WHERE is performed.

• When rows (tuples) are grouped, one line of output is produced for each group.

Page 25: Schedule

SCU Holliday - coen 178 7–25

Restriction on SELECT Lists With Aggregation

• If any aggregation is used, then each element of a SELECT clause must either be aggregated or appear in a group-by clause (if a where clause is present).

• The following might seem a tempting way to find the bar that sells Bud the cheapest:

Sells(bar, beer, price)

SELECT bar, MIN(price)

FROM Sells

WHERE beer = 'Bud';• But it is illegal in most SQL implementations.

Page 26: Schedule

SCU Holliday - coen 178 7–26

HAVING Clauses

HAVING clauses are selections on groups, just as WHERE clauses are selections on tuples.

• Condition can use the tuple variables or relations in the FROM and their attributes, just like the WHERE can. But the tuple variables range only over the group. And the attribute better make sense within a group;

i.e., be one of the grouping attributes.

Page 27: Schedule

SCU Holliday - coen 178 7–27

ExampleFind the average price of those beers that are either served in

at least 3 bars or manufactured by Anheuser-Busch.Beers(name, manf)Sells(bar, beer, price)

SELECT beer, AVG(price)FROM SellsGROUP BY beerHAVING COUNT(*) >= 3 OR

beer IN (SELECT nameFROM BeersWHERE manf = 'Anheuser-Busch');

Page 28: Schedule

SCU Holliday - coen 178 7–28

Before we go on..

• How do we find the bar that sells Bud the cheapest? Sells(bar, beer, price)

Select barFrom SellsWhere beer = ‘Bud’ and price =

(select min(price) from Sells where beer = ‘Bud’ )

Page 29: Schedule

SCU Holliday - coen 178 7–29

Alternatively

SELECT barFROM SellsWHERE beer = ‘Bud’ and

price <= ALL(SELECT priceFROM SellsWHERE beer =

‘Bud’);

Page 30: Schedule

SCU Holliday - coen 178 7–30

Database Modifications

• So far, we have looked at queries that ask about the current state of the database (instance).

• We use similar syntax to make changes to the database.

• Modification = insert + delete + update.

Page 31: Schedule

SCU Holliday - coen 178 7–31

DB Insert

Insertion of a TupleINSERT INTO relation VALUES (list of values).

• Inserts the tuple = list of values, associating values with attributes in the order the attributes were declared. Forget the order? List the attributes as arguments of the relation.

ExampleLikes(drinker, beer)

Insert the fact that Sally likes Bud.

INSERT INTO Likes(drinker, beer)

VALUES('Sally', 'Bud');

Page 32: Schedule

SCU Holliday - coen 178 7–32

Insertion of the Result of a QueryINSERT INTO relation (subquery).

ExampleCreate a (unary) table of all Sally's buddies, i.e., the people who frequent

bars that Sally also frequents.Frequents(drinker, bar)

CREATE TABLE Buddies(name char(30)

);

INSERT INTO Buddies(SELECT DISTINCT d2.drinker FROM Frequents d1, Frequents d2 WHERE d1.drinker = 'Sally' AND

d2.drinker <> 'Sally' AND d1.bar = d2.bar

);

Page 33: Schedule

SCU Holliday - coen 178 7–33

DeletionDELETE FROM relation WHERE condition.• Deletes all tuples satisfying the condition from the named

relation.

• Sally no longer likes Bud.Likes(drinker, beer)

DELETE FROM LikesWHERE drinker = 'Sally' AND

beer = 'Bud';

• Make the Likes relation empty.DELETE FROM Likes;

Page 34: Schedule

SCU Holliday - coen 178 7–34

Example• Delete all beers for which there is another beer by

the same manufacturer. Beers(name,manf)

DELETE FROM Beers bWHERE EXISTS

(SELECT name FROM Beers WHERE manf = b.manf AND

name <> b.name);

• Note alias for relation from which deletion occurs.

• Subquery evaluated once for each row of b

Page 35: Schedule

SCU Holliday - coen 178 7–35

• Semantics is tricky. If A.B. makes Bud and BudLite (only), does deletion of Bud make BudLite not satisfy the condition?

• SQL semantics: all conditions in modifications must be evaluated by the system before any changes due to that command occur. In Bud/Budlite example, we would first identify

both beers as targets, and then delete both.

Page 36: Schedule

SCU Holliday - coen 178 7–36

More on Delete

• Oracle 8i does not allow complex conditions in the where clause.

• You can only delete from one table at a time.

Delete all accounts at every branch located in Fremont. 

delete from Account

where branch-name in

(select branch-name

from Branch

where branch-city="Fremont" )

Page 37: Schedule

SCU Holliday - coen 178 7–37

Updates

UPDATE relation SET list of assignments WHERE condition

ExampleDrinker Fred's phone number is now 555-1212.Drinkers(name, addr, phone)

UPDATE DrinkersSET phone = '555-1212'WHERE name = 'Fred';

Page 38: Schedule

SCU Holliday - coen 178 7–38

Example - Update

Make $4 the maximum price for beer.Updates many tuples at once.

Sells(bar, beer, price)

UPDATE SellsSET price = 4.00WHERE price > 4.00;

Page 39: Schedule

SCU Holliday - coen 178 7–39

Review/Quizselect branch-name, avg(balance)

fromAccount

where account# > 5000

group by branch-name

having avg(balance) > 2000

B-name Acc# Balance

Main 105 1000

Main 5005 3000

Oak 203 3100

Oak 5033 1900

Page 40: Schedule

SCU Holliday - coen 178 7–40

Answer

• If both a where clause and a having command are present, the where clause is done first.

B-name AVG(Balance)

Main 3000