Presentation is loading. Please wait.

Presentation is loading. Please wait.

CPSC-608 Database Systems Fall 2008 Instructor: Jianer Chen Office: HRBB 309B Phone: 845-4259 Notes #4.

Similar presentations


Presentation on theme: "CPSC-608 Database Systems Fall 2008 Instructor: Jianer Chen Office: HRBB 309B Phone: 845-4259 Notes #4."— Presentation transcript:

1 CPSC-608 Database Systems Fall 2008 Instructor: Jianer Chen Office: HRBB 309B Phone: 845-4259 Email: chen@cs.tamu.edu Notes #4

2 SQL: Structured Query language How does SQL manipulate (read/write) tables? (continued)

3 Products and Natural Joins Cross join (Cartesian Product): R CROSS JOIN S; A B 1 2 3 4 CROSS JOIN B C D 25 6 4 7 8 R S A R.B S.B C D 1 2 2 5 6 1 2 4 7 8 3 4 2 5 6 3 4 4 7 8

4 Products and Natural Joins Natural join (join tuples agreeing on common attributes): R NATURAL JOIN S; A B 1 2 3 4 NATURAL JOIN B C D 25 6 4 7 8 R S A B C D 1 2 5 6 3 4 7 8

5 Theta Join R JOIN S ON Example: using Drinkers(name, addr) and Frequents(drinker, bar): Drinkers JOIN Frequents ON name = drinker; gives us all (d, a, d, b) quadruples such that drinker d lives at address a and frequents bar b.

6 Theta Join R JOIN S ON A B 1 2 4 5 JOIN B C D 25 6 4 7 2 R S A R.B S.B C D 1 2 2 5 6 1 2 4 7 2 4 5 2 5 6 ON A < D;

7 Outerjoins R OUTER JOIN S is the core of an outerjoin expression. It is modified by: 1.Optional NATURAL in front of OUTER. 2.Optional ON after JOIN. 3.Optional LEFT, RIGHT, or FULL before OUTER. uLEFT = pad dangling tuples of R only. uRIGHT = pad dangling tuples of S only. uFULL = pad both; this choice is the default.

8 Outerjoins (Examples) R NATURAL FULL OUTER JOIN S R NATURAL LEFT OUTER JOIN S R NATURAL RIGHT OUTER JOIN S

9 Outerjoins (Examples) R NATURAL FULL OUTER JOIN S A B 1 2 3 9 NATURAL FULL OUTER JOIN B C D 25 6 4 7 8 R S A B C D 1 2 5 6 3 9 N N N 4 7 8

10 Outerjoins (Examples) R NATURAL LEFT OUTER JOIN S A B 1 2 3 9 NATURAL LEFT OUTER JOIN B C D 25 6 4 7 8 R S A B C D 1 2 5 6 3 9 N N

11 Outerjoins (Examples) R NATURAL RIGHT OUTER JOIN S A B 1 2 3 9 NATURAL RIGHT OUTER JOIN B C D 25 6 4 7 8 R S A B C D 1 2 5 6 N 4 7 8

12 Aggregations SUM, AVG, COUNT, MIN, and MAX can be applied to a column in a SELECT clause to produce that aggregation on the column. Also, COUNT(*) counts the number of tuples.

13 Example: Aggregation From Sells(bar, beer, price), find the average price of Bud: SELECT AVG(price) FROM Sells WHERE beer = ’Bud’;

14 Eliminating Duplicates in an Aggregation Use DISTINCT inside an aggregation. Example: find the number of different prices charged for Bud: SELECT COUNT(DISTINCT price) FROM Sells WHERE beer = ’Bud’;

15 NULL’s Ignored in Aggregation NULL never contributes to a sum, average, or count, and can never be the minimum or maximum of a column. But if there are no non-NULL values in a column, then the result of the aggregation is NULL.

16 Example: Effect of NULL’s SELECT count(*) FROM Sells WHERE beer = ’Bud’; SELECT count(price) FROM Sells WHERE beer = ’Bud’; The number of bars that sell Bud. The number of bars that sell Bud at a known price.

17 Grouping We may follow a SELECT-FROM-WHERE expression by GROUP BY and a list of attributes. The relation that results from the SELECT-FROM-WHERE is grouped according to the values of all those attributes, and any aggregation is applied only within each group.

18 Example: Grouping From Sells(bar, beer, price), find the average price for each beer: SELECT beer, AVG(price) FROM Sells GROUP BY beer;

19 Example: Grouping From Sells(bar, beer, price) and Frequents(drinker, bar), find for each drinker the average price of Bud at the bars they frequent: SELECT drinker, AVG(price) FROM Frequents, Sells WHERE beer = ’Bud’ AND Frequents.bar = Sells.bar GROUP BY drinker; Compute drinker-bar- price for Bud tuples first, then group by drinker.

20 Restriction on SELECT Lists With Aggregation If any aggregation is used, then each element of the SELECT list must be either: 1.Aggregated, or 2.An attribute on the GROUP BY list.

21 Illegal Query Example You might think you could find the bar that sells Bud the cheapest by: SELECT bar, MIN(price) FROM Sells WHERE beer = ’Bud’; But this query is illegal in SQL.

22 HAVING Clauses HAVING may follow a GROUP BY clause. If so, the condition applies to each group, and groups not satisfying the condition are eliminated.

23 Example. From Sells(bar, beer, price) and Beers(name, manf), find the average price of those beers that are either served in at least three bars or are manufactured by Pete’s. SELECT beer, AVG(price) FROM Sells GROUP BY beer HAVING COUNT(bar) >= 3 OR beer IN (SELECT name FROM Beers WHERE manf = ’Pete’’s’); Beers manu- factured by Pete’s. Beer groups with at least 3 non-NULL bars and also beer groups where the manufacturer is Pete’s.

24 Requirements on HAVING Conditions These conditions may refer to any relation or tuple-variable in the FROM clause. They may refer to attributes of those relations, as long as the attribute makes sense within a group; i.e., it is either: 1.A grouping attribute, or 2.Aggregated.

25 Requirements on HAVING Conditions It is easier to understand this from an implementation viewpoint: SELECT FROM WHERE GROUP BY HAVING step 1, input step 5, output step 2 step 3 step 4

26 Database Modifications A modification command does not return a result (as a query does), but changes the database in some way. Three kinds of modifications: 1.Insert a tuple or tuples. 2.Delete a tuple or tuples. 3.Update the value(s) of an existing tuple or tuples.

27 Insertion To insert a single tuple: INSERT INTO VALUES ( ); Example: add to Likes(drinker, beer) the fact that Sally likes Bud. INSERT INTO Likes VALUES(’Sally’, ’Bud’);

28 Specifying Attributes in INSERT We may add to the relation name a list of attributes. Two reasons to do so: 1.We forget the standard order of attributes for the relation. 2.We don’t have values for all attributes, and we want the system to fill in missing components with NULL or a default value.

29 Example: Specifying Attributes Another way to add the fact that Sally likes Bud to Likes(drinker, beer): INSERT INTO Likes(beer, drinker) VALUES(’Bud’, ’Sally’);

30 Inserting Many Tuples We may insert the entire result of a query into a relation, using the form: INSERT INTO ( );

31 Example. Using Frequents(drinker, bar), enter into the new relation PotBuddies(name) all of Sally’s “potential buddies,” i.e., those drinkers who frequent at least one bar that Sally also frequents. INSERT INTO PotBuddies (SELECT d2.drinker FROM Frequents d1, Frequents d2 WHERE d1.drinker = ’Sally’ AND d2.drinker <> ’Sally’ AND d1.bar = d2.bar); Pairs of Drinker tuples where the first is for Sally, the second is for someone else, and the bars are the same. The other drinker

32 Deletion To delete tuples satisfying a condition from some relation: DELETE FROM WHERE ;

33 Example: Deletion Delete from Likes(drinker, beer) the fact that Sally likes Bud: DELETE FROM Likes WHERE drinker = ’Sally’ AND beer = ’Bud’;

34 Example: Delete all Tuples Make the relation Likes empty: DELETE FROM Likes; Note no WHERE clause needed.

35 Example: Delete Many Tuples Delete from Beers(name, manf) all beers for which there is another beer by the same manufacturer. DELETE FROM Beers b WHERE EXISTS ( SELECT name FROM Beers WHERE manf = b.manf AND name <> b.name); Beers with the same manufacturer and a different name from the name of the beer represented by tuple b.

36 Semantics of Deletion (1) Suppose Anheuser-Busch makes only Bud and Bud Lite. Suppose we come to the tuple b for Bud first. The subquery is nonempty, because of the Bud Lite tuple, so we delete Bud. Now, when b is the tuple for Bud Lite, do we delete that tuple too?

37 Semantics of Deletion (2) Answer: we do delete Bud Lite as well. The reason is that deletion proceeds in two stages: 1.Mark all tuples for which the WHERE condition is satisfied. 2.Delete the marked tuples.

38 Updates To change certain attributes in certain tuples of a relation: UPDATE SET WHERE ;

39 Example: Update Change drinker Fred’s phone number to 555-1212: UPDATE Drinkers SET phone = ’555-1212’ WHERE name = ’Fred’;

40 Example: Update Several Tuples Make $4 the maximum price for beer: UPDATE Sells SET price = 4.00 WHERE price > 4.00;

41 Read Chapter 6 for more details.

42 Constraints and Triggers A constraint is a relationship among data elements that the DBMS is required to enforce. A triggers are only executed when a specified condition occurs.

43 Kinds of Constraints Keys. Foreign-key (referential-integrity). Value-based constraints. Tuple-based constraints. Assertions: any SQL boolean expression.

44 Foreign Keys A foreign key constraint on a set A of attributes in a relation R is such that 1.A is a (primary or unique) key for another relation S; 2.Any value appearing in the A-column of relation R must also appear in the A-column in relation S

45 Expressing Foreign Keys Use the keyword REFERENCES, either: 1.Within the declaration of an attribute (only for one-attribute keys). 2.As an element of the schema: FOREIGN KEY ( ) REFERENCES ( ) Referenced attributes (in relation-2) must be declared PRIMARY KEY or UNIQUE.

46 Example: With Attribute CREATE TABLE Beers ( nameCHAR(20) PRIMARY KEY, manfCHAR(20) ); CREATE TABLE Sells ( barCHAR(20), beerCHAR(20) REFERENCES Beers(name), priceREAL );

47 Enforcing Foreign-Key Constraints If there is a foreign-key constraint from attributes of relation R to a key of relation S, two violations are possible: 1.An insert or update to R introduces values not found in S. 2.A deletion or update to S causes some tuples of R to “dangle.”

48 Actions Taken (1) Suppose R = Sells, S = Beers, and beer in Sells is a foreign key in Beers. An insert or update to Sells that introduces a nonexistent beer must be rejected.

49 Actions Taken (2) A deletion or update to Beers that removes a beer value found in some tuples of Sells can be handled in three ways. uDefault : Reject the modification. 1.Cascade : Make the same changes in Sells. –Deleted beer: delete the tuples in Sells. –Updated beer: change the values in Sells. 2.Set NULL : Change beer in Sells to NULL.

50 Choosing a Policy When we declare a foreign key, we may choose policies SET NULL or CASCADE for deletions and updates. Follow the foreign-key declaration by: ON [UPDATE,DELETE][SET NULL,CASCADE] Otherwise, the default (reject) is used.

51 Example CREATE TABLE Sells ( barCHAR(20), beerCHAR(20), priceREAL, FOREIGN KEY(beer) REFERENCES Beers(name) ON DELETE SET NULL ON UPDATE CASCADE );

52 Attribute-Based Checks Constraints on the value of an attribute. Add: CHECK ( ) to the declaration for the attribute. The condition may use the name of the attribute, but any other relation or attribute name must be in a subquery.

53 Example CREATE TABLE Sells ( barCHAR(20), beerCHAR(20) CHECK ( beer IN (SELECT name FROM Beers)), priceREAL CHECK ( price <= 5.00 ) );

54 Tuple-Based Checks CHECK ( ) may be added as a relation-schema element. The condition may refer to any attribute of the relation (but any other attributes or relations require a subquery). Checked on insert or update only.

55 Example: Tuple-Based Check Only Joe’s Bar can sell beer for more than $5: CREATE TABLE Sells ( barCHAR(20), beerCHAR(20), priceREAL, CHECK (bar = ’Joe’’s Bar’ OR price <= 5.00) );

56 Assertions These are database-schema elements, like relations or views. Defined by: CREATE ASSERTION CHECK ( ); Condition may refer to any relation or attribute in the database schema.

57 Example: Assertion In Sells(bar, beer, price), no bar may charge an average of more than $5. CREATE ASSERTION NoRipoffBars CHECK ( NOT EXISTS ( SELECT bar FROM Sells GROUP BY bar HAVING 5.00 < AVG(price)) );

58 Timing of Assertion Checks In principle, we must check every assertion after every modification to any relation of the database. A clever system can observe that only certain changes could cause a given assertion to be violated.

59 Triggers: Motivation Assertions are powerful, but the DBMS often can’t tell when they need to be checked. Attribute- and tuple-based checks are checked at known times, but are not powerful. Triggers let the user decide when to check for a powerful condition.

60 Event-Condition-Action Rules Another name for “trigger” is ECA rule, or event-condition-action rule. Event : typically a type of database modification, e.g., “insert on Sells.” Condition : Any SQL boolean-valued expression. Action : Any SQL statements.

61 Preliminary Example: A Trigger Instead of using a foreign-key constraint and rejecting insertions into Sells(bar, beer, price) with unknown beers, a trigger can add that beer to Beers, with a NULL manufacturer.

62 Trigger: an example CREATE TRIGGER BeerTrig AFTER INSERT ON Sells REFERENCING NEW ROW AS NewTuple FOR EACH ROW WHEN (NewTuple.beer NOT IN (SELECT name FROM Beers)) INSERT INTO Beers(name) VALUES(NewTuple.beer); The event The condition The action

63 Trigger: CREATE TRIGGER CREATE TRIGGER Option: CREATE OR REPLACE TRIGGER –Useful if there is a trigger with that name and you want to modify the trigger.

64 Trigger: The Event AFTER can be BEFORE. –Also, INSTEAD OF, if the relation is a view. A great way to execute view modifications: have triggers translate them to appropriate modifications on the base tables. INSERT can be DELETE or UPDATE. –And UPDATE can be UPDATE... ON a particular attribute.

65 Trigger: FOR EACH ROW Triggers are either “row-level” or “statement-level.” FOR EACH ROW indicates row-level; its absence indicates statement-level. Row level triggers : execute once for each modified tuple. Statement-level triggers : execute once for an SQL statement, regardless of how many tuples are modified.

66 Trigger: REFERENCING INSERT statements imply a new tuple (for row-level) or new table (for statement-level). –The “table” is the set of inserted tuples. DELETE implies an old tuple or table. UPDATE implies both. Refer to these by [NEW OLD][TUPLE TABLE] AS

67 Trigger: The Condition Any boolean-valued condition is appropriate. It is evaluated before or after the triggering event, depending on whether BEFORE or AFTER is used in the event. Access the new/old tuple or set of tuples through the names declared in the REFERENCING clause.

68 Trigger: The Action There can be more than one SQL statement in the action. –Surround by BEGIN... END if there is more than one. But queries make no sense in an action, so we are really limited to modifications.

69 Another Example Using Sells(bar, beer, price) and a unary relation RipoffBars(bar) created for the purpose, maintain a list of bars that raise the price of any beer by more than $1.

70 The Trigger CREATE TRIGGER PriceTrig AFTER UPDATE OF price ON Sells REFERENCING OLD ROW AS ooo NEW ROW AS nnn FOR EACH ROW WHEN (nnn.price > ooo.price + 1.00) INSERT INTO RipoffBars VALUES (nnn.bar); The event – only changes to prices Updates let us talk about old and new tuples We need to consider each price change Condition: a raise in price > $1 When the price change is great enough, add the bar to RipoffBars

71 Triggers on Views Generally, it is impossible to modify a view, because it doesn’t exist. But an INSTEAD OF trigger lets us interpret view modifications in a way that makes sense. Example: We’ll design a view Synergy that has (drinker, beer, bar) triples such that the bar serves the beer, the drinker frequents the bar and likes the beer.

72 Example: The View CREATE VIEW Synergy AS SELECT Likes.drinker, Likes.beer, Sells.bar FROM Likes, Sells, Frequents WHERE Likes.drinker = Frequents.drinker AND Likes.beer = Sells.beer AND Sells.bar = Frequents.bar; Natural join of Likes, Sells, and Frequents Pick one copy of each attribute

73 Interpreting a View Insertion We cannot insert into Synergy --- it is a view. But we can use an INSTEAD OF trigger to turn a (drinker, beer, bar) triple into three insertions of projected pairs, one for each of Likes, Sells, and Frequents.

74 The Trigger CREATE TRIGGER ViewTrig INSTEAD OF INSERT ON Synergy REFERENCING NEW ROW AS n FOR EACH ROW BEGIN INSERT INTO LIKES VALUES (n.drinker, n.beer); INSERT INTO SELLS(bar, beer) VALUES(n.bar, n.beer); INSERT INTO FREQUENTS VALUES(n.drinker, n.bar); END;

75 Read Chapter 7 for more details.

76 secondary storage (disks) in tables (relations) database administrator DDL language database programmer DML (query) language DBMS file manager buffer manager main memory buffers index/file manager DML complier DDL complier query execution engine transaction manager concurrency control lock table logging & recovery A Quick Review on Undergraduate Database

77 secondary storage (disks) database administrator DDL language database programmer DML (query) language DBMS file manager buffer manager main memory buffers index/file manager DML complier DDL complier query execution engine transaction manager concurrency control lock table logging & recovery Gradiate Database


Download ppt "CPSC-608 Database Systems Fall 2008 Instructor: Jianer Chen Office: HRBB 309B Phone: 845-4259 Notes #4."

Similar presentations


Ads by Google