Presentation is loading. Please wait.

Presentation is loading. Please wait.

Schedule Today: Next After that Subqueries, Grouping and Aggregation.

Similar presentations


Presentation on theme: "Schedule Today: Next After that Subqueries, Grouping and Aggregation."— Presentation transcript:

1 Schedule Today: Next After that Subqueries, Grouping and Aggregation.
Read Sections Next Modifications, Schemas, Views. Read Sections After that Constraints. Read Sections , SCU Holliday - coen 178

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. Example Find 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); SCU Holliday - coen 178

3 Forcing Set Semantics SELECT DISTINCT price FROM Sells;
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 price FROM Sells; SCU Holliday - coen 178

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. SCU Holliday - coen 178

5 J. Holliday 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 P 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 r 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 SCU Holliday - coen 178

6 Bag vs Set Bag Semantics Set Semantics SQL query relational algebra
SELECT DISTINCT ... (query)UNION(query) (query)INTERSECT(query) (query)UNION ALL(query) (query)EXCEPT(query) (query)INTERSECT ALL(query) (query)EXCEPT ALL(query) SCU Holliday - coen 178

7 How many tuples? A B 1 a 2 C 2 3 select * r= from s where C = 3
select B from r select B s= from r, s select B select A from r, s from r,s where C = 3 where A=C A B 1 a 2 C 2 3 SCU Holliday - coen 178

8 Forcing Set Semantics with DISTINCT
B 1 a 2 select distinct B r= from r select distinct B from r, s s= select distinct C from s C 2 3 SCU Holliday - coen 178

9 How many tuples? a 1 2 B A 3 2 C (C=3)(s) r= B(r) B(rs) s=
B(rs) s=  B (C=3)(rs) A (C=3)(rs) a 1 2 B A 3 2 C SCU Holliday - coen 178

10 What is the Result? r = r2 = a 1 2 B A a 1 b B A (Select A from r2)
UNION (Select A from r) (Select * from r2) UNION ALL (Select * from r) (Select * from r2) INTERSECT (Select * from r) (Select * from r2) UNION (Select * from r) (Select * from r2) EXCEPT ALL (Select * from r) (Select * from r2) EXCEPT (Select * from r) SCU Holliday - coen 178

11 What is the Result? r = r2 = a 1 2 B A (Select * from r2) INTERSECT
UNION ALL (Select * from r) (Select * from r2) INTERSECT ALL (Select * from r) (Select * from r2) EXCEPT ALL (Select * from r) (Select * from r2) EXCEPT (Select * from r) SCU Holliday - coen 178

12 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#) SCU Holliday - coen 178

13 Answers (select customer-name from Depositor) intersect
(select customer-name from Borrower) except SCU Holliday - coen 178

14 Join-Based Expressions
Natural join does a cross product and requires the common attributes to be equal. Can be used to relate 2 select-from-where statements or 2 tables or to define a relation in the FROM-clause. (Select A,B FROM R) NATURAL JOIN (Select B,C FROM S) R NATURAL JOIN S Select A,B,C FROM R NATURAL JOIN S SCU Holliday - coen 178

15 Join Semantics Two types of join:
Natural Join - do cross product and choose rows where common attributes are equal (equi-join), delete duplicate attribute. R NATURAL JOIN S Cross Join - do cross product, and choose rows as specified by ON. R JOIN S ON condition e.g., condition: R.B=S.B If no condition, just cross product R CROSS JOIN S SCU Holliday - coen 178

16 Join Exercise R = S = What is R natural join S ? (no second B) A B C a
101 35 b 103 24 104 65 D B Smith 101 Jones 102 Johnson 103 A B C D a 101 35 Smith b 103 24 Johnson SCU Holliday - coen 178

17 Outer Join Expressions
Natural join and Cross Join...On gives us a way to choose tuples by matching attributes from tables. Outer join gives us a way to report on the tuples that don’t match up. Optional LEFT, RIGHT, or FULL (default) before OUTER. LEFT = pad (with NULL) dangling tuples of R only; RIGHT = pad dangling tuples of S only. To do an outer join, do a cross or natural join then add in the tuples from the left or right table (as specified) that didn’t match up and pad them with Null. SCU Holliday - coen 178

18 Outer Join Exercise R = S = What is R natural left outer join S? A B C
101 35 b 103 24 104 65 D B Smith 101 Jones 102 Johnson 103 A B C D a 101 35 Smith b 103 24 Johnson 104 65 --Null-- SCU Holliday - coen 178

19 Outer Join Exercise R = S = What is R natural right outer join S? A B
101 35 b 103 24 104 65 D B Smith 101 Jones 102 Johnson 103 Jones 102 --null-- Johnson 24 103 b Smith 35 101 a D C B A -null- SCU Holliday - coen 178

20 Full Outer Join Exercise
R = S = What is R natural full outer join S? A B C a 101 35 b 103 24 104 65 D B Smith 101 Jones 102 Johnson 103 A B C D a 101 35 Smith b 103 24 Johnson 104 65 --null-- 102 Jones --null-- SCU Holliday - coen 178

21 Outer Join Exercise R = S = R left outer join S on R.B=S.B A B C a 101
35 b 103 24 104 65 D B Smith 101 Jones 102 Johnson 103 A B C D a 101 35 Smith b 103 24 Johnson 104 65 --Null-- SCU Holliday - coen 178

22 Outer Join Exercise Find all customers who have an account but no loan. Depositor=(customer-name,account#) Borrower=(customer-name, loan#) Select customer-name From Depositor LEFT OUTER NATURAL JOIN Borrower Where loan# is NULL SCU Holliday - coen 178

23 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 Sells WHERE beer = 'Bud'; SCU Holliday - coen 178

24 Eliminating Duplicates Before Aggregation
Find the number of different prices at which Bud is sold. Sells(bar, beer, price) SELECT COUNT(DISTINCT price) FROM Sells WHERE beer = 'Bud'; DISTINCT may be used in any aggregation, but typically only makes sense with COUNT. SCU Holliday - coen 178

25 Example Using AVG Find the average account balance at the Oakland branch. Account = (branch-name,account#,balance) select avg(balance) from Account where branch-name = "Oakland“ What does the result look like? SCU Holliday - coen 178

26 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 102 7000 103 5000 SCU Holliday - coen 178

27 Grouping Example:Find the average sales price for each beer.
Follow 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; SCU Holliday - coen 178

28 Avg sales price for each beer
SELECT beer, AVG(price) FROM Sells GROUP BY beer; Joe’s Bud 2.00 Kelly’s 3.00 Miller O’Shea 5.00 Bar Beer Price Joe’s Bud 2.00 Miller 3.00 Kelly’s O’Shea 5.00 Bud 2.00 3.00 Miller 5.00 Bud 2.50 Miller 4.00 SCU Holliday - coen 178

29 Example Find, 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, Sells WHERE beer = 'Bud' AND Frequents.bar = Sells.bar GROUP BY drinker; SCU Holliday - coen 178

30 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. SCU Holliday - coen 178

31 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. SCU Holliday - coen 178

32 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. SCU Holliday - coen 178

33 Example Find 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 Sells GROUP BY beer HAVING COUNT(*) >= 3 OR beer IN ( SELECT name FROM Beers WHERE manf = 'Anheuser-Busch' ); SCU Holliday - coen 178

34 Before we go on.. How do we find the bar that sells Bud the cheapest? Sells(bar, beer, price) Select bar From Sells Where beer = ‘Bud’ and price = (select min(price) from Sells where beer = ‘Bud’ ) SCU Holliday - coen 178

35 Alternatively SELECT bar FROM Sells WHERE beer = ‘Bud’ and
price <= ALL( SELECT price WHERE beer = ‘Bud’); SCU Holliday - coen 178

36 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. SCU Holliday - coen 178

37 DB Insert Insertion of a Tuple Example
INSERT 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. Example Likes(drinker, beer) Insert the fact that Sally likes Bud. INSERT INTO Likes(drinker, beer) VALUES('Sally', 'Bud'); SCU Holliday - coen 178

38 Insertion of the Result of a Query
INSERT INTO relation (subquery). Example Create 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 SCU Holliday - coen 178

39 Deletion DELETE FROM relation WHERE condition.
Deletes all tuples satisfying the condition from the named relation. Sally no longer likes Bud. Likes(drinker, beer) DELETE FROM Likes WHERE drinker = 'Sally' AND beer = 'Bud'; Make the Likes relation empty. DELETE FROM Likes; SCU Holliday - coen 178

40 Example Delete all beers for which there is another beer by the same manufacturer. Beers(name,manf) DELETE FROM Beers b WHERE 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 SCU Holliday - coen 178

41 Semantics is tricky. If A. B
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. SCU Holliday - coen 178

42 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" ) SCU Holliday - coen 178

43 Updates UPDATE relation SET list of assignments WHERE condition Example Drinker Fred's phone number is now Drinkers(name, addr, phone) UPDATE Drinkers SET phone = ' ' WHERE name = 'Fred'; SCU Holliday - coen 178

44 Example - Update Make $4 the maximum price for beer.
Updates many tuples at once. Sells(bar, beer, price) UPDATE Sells SET price = 4.00 WHERE price > 4.00; SCU Holliday - coen 178

45 Review/Quiz select branch-name, avg(balance) from Account
where account# > 5000 group by branch-name having avg(balance) > 2000 B-name Acc# Balance Main 105 1000 5005 3000 Oak 203 3100 5033 1900 SCU Holliday - coen 178

46 Answer If both a where clause and a having command are present, the where clause is done first. B-name AVG(Balance) Main 3000 SCU Holliday - coen 178


Download ppt "Schedule Today: Next After that Subqueries, Grouping and Aggregation."

Similar presentations


Ads by Google