midterm examination cs 265 spring 2016 name: key

21
Midterm Examination CS 265 Spring 2016 Name: _____________KEY________________________ To request a regrade or to otherwise appeal your score, submit a one paragraph explanation of why you think the grade was “in error” and submit your explanation/request together with your exam to Doug after class or in office hours.

Upload: others

Post on 28-Jan-2022

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Midterm Examination CS 265 Spring 2016 Name: KEY

Midterm Examination CS 265 Spring 2016 Name: _____________KEY________________________ To request a regrade or to otherwise appeal your score, submit a one paragraph explanation of why you think the grade was “in error” and submit your explanation/request together with your exam to Doug after class or in office hours.

Page 2: Midterm Examination CS 265 Spring 2016 Name: KEY

Midterm Examination CS 265 Spring 2016 Name: _____________KEY________________________ I will not use notes, other exams, or any source other than my own brain on this exam: _________________________________________(please sign)

2

1. (5 pts) Consider the relational schema, R = [A B C D E F G] with applicable FDs

A, B à C, D A, E à G F à A A à F

Give all keys for this relational schema. Be clear.

Key(s): {A,B,E} and {B,E,F}

2. (5 pts) Consider the relational schema, R = [A B C ] with applicable FDs

A à B B à A B à C C à B C à A A à C

Give TWO minimal set of FDs consistent with those given. Do not take any short cuts in presenting your answers. Be clear.

FirstMinimalSet SecondMinimalSet

BandEarenotontheRHSofanyFD,andmustbepartofanykey.A<ributeclosureof{B,E}issimply{B,E}.Considerextendingthesetminimallyinallpossibleways.{A,B,E}è{A,B,E,C,D}è{A,B,E,C,D,G}è{A,B,E,C,D,G,F},so{A,B,E}isakeyC,D,andGarenotonLHSofanyFD,soaddsnoinferenHalpower;evenaddingallthreedoesnotresultinkey.But{B,E,F}è{B,E,F,A}è...è{A,B,C,D,E,F,G},so{B,E,F}isakey

3ptsfor1key,5pointsforboththesekeys;-2foreachaddi>onkey(cangetnolessthan0)

Thelowestpossibleonanyproblemis0(regardlessofhowmanynega>vepointsmightbeassignedbyrubric)

Seenextpage

Page 3: Midterm Examination CS 265 Spring 2016 Name: KEY

3

2. (5 pts) Consider the relational schema, R = [A B C ] with applicable FDs

A à B B à A B à C C à B C à A A à C

Give TWO minimal set of FDs consistent with those given. Do not take any short cuts in presenting your answers. Be clear.

A à B Is this FD redundant? A à ...B... without Aà B? A à A, C (w A à C) à A, C, B (w C à B}. So, redundant B à C Is this FD redundant? B à ...C... without Bà C (or with already eliminated FD)? B à B, A (w B à A) à B, A, C (w A à B}. So, redundant C à A Is this FD redundant? C à ...A... without Cà A (or with already eliminated FDs)? C à C, B (w C à B) à C, B, A (w B à A}. So, redundant B à A Is this FD redundant? B à ...A... Without Bà A (or with already eliminated FDs)? B à B, and that is all. So, NOT redundant C à B Is this FD redundant? C à ...B... Without Cà B (or with already eliminated FDs)? Cà C, and that is all. So, NOT redundant A à C Is this FD redundant? A à ...C... Without A à C (or with already eliminated FDs)? Aà A, and that is all. So, NOT redundant So one minimal set is obtained with an ordering that goes through the first column and then the second column: BàA, CàB, AàC

Now consider a row-by-row order given arrangement aboove A à B Is this FD redundant? A à ...B... without Aà B? A à A, C (w A à C) à A, C, B (w C à B}. So, redundant B à A Is this FD redundant? B à ...A... without Bà A (or with already eliminated FD)? B à B, C (w B à C) à B, C, A (w C à A}. So, redundant B à C Is this FD redundant? B à ...C... without Bà C (or with already eliminated FDs)? B à B, and that’ is all. So,NOT redundant C à B Is this FD redundant? C à ...B... without Cà B (or with already eliminated FDs)? Cà C, A and that is all. So, NOT redundant C à A Is this FD redundant? C à ...A...without CàA or with already eliminated FDs)? Cà C, B, and that is all. So, NOT redundant A à C Is this FD redundant? A à ...C... without A à C (or with already eliminated FDs)? Aà A, and that is all. So, NOT redundant So one minimal set is obtained with an ordering that goes through the first row, then second row, then third row: BàC, CàB, CàA, AàC

FirstMinimalSet

SecondMinimalSet

There are other minimal FD sets (and thus other possible answers to this problem

Page 4: Midterm Examination CS 265 Spring 2016 Name: KEY

4

2. (5 pts) Consider the relational schema, R = [A B C ] with applicable FDs

A à B B à A B à C C à B C à A A à C

Give TWO minimal set of FDs consistent with those given. Do not take any short cuts in presenting your answers. Be clear.

Any other “smallest” proper subset of the original FDs that allows any attribute to be determined from any other attribute is a minimal set that would be created by processing some ordering of the original FD set So, for example, AàB, BàC, CàA is a minimal set (and could be used as first or second alternative), as is AàB, BàA, AàC, CàA

3pointsforonecorrectminimalset;5pointsfortwocorrectminimalsets

Page 5: Midterm Examination CS 265 Spring 2016 Name: KEY

5

3. (5 pts) Consider the relational schema, R = [A B C D E F G H I J ] with applicable FDs

A, F à C, I B, E à G, H B à J B, C, E à D C à A, F

Reflect on the task of decomposing relation R into a set of BCNF relations. For example, I might use B à J as the first step to decompose R: Circle the FD(s) in the list above that would NOT be used as the first step to decompose R using the decomposition procedure described in class. Beside each circled FD, give a brief explanation of why you would not use that FD to decompose the relation R.

ABCDEFGHIJ

BàJ

BJ ABCDEFGHI

B,C,Eisakeyofrela>onR,andthusdoesnotviolateBCNF(isnotresponsibleforredundancy) +5pointsforthisFDcircled

andsomegoodapproxima>onofthereasongiven

SeenextpageforalternaHve

Page 6: Midterm Examination CS 265 Spring 2016 Name: KEY

6

3. (5 pts) Consider the relational schema, R = [A B C D E F G H I J ] with applicable FDs

A, F à C, I B, E à G, H B à J B, C, E à D C à A, F

Reflect on the task of decomposing relation R into a set of BCNF relations. For example, I might use B à J as the first step to decompose R: Circle the FD(s) in the list above that would NOT be used as the first step to decompose R using the decomposition procedure described in class. Beside each circled FD, give a brief explanation of why you would not use that FD to decompose the relation R.

ABCDEFGHIJ

CàAF

CAF BCDEGHI

WhileIonlyaskedforadecomposiHonintoBCNFtables,withnomenHonofadependencypreservingdecomposiHon,someanswersandexplanaHonswereclearlyknowledgeableofthemandIacceptedthoseanswers(happily!)BUTIWILLCOUNTTHEMWRONGONTHEFINALEXAMBECAUSETHEYARENOTENTIRELYCORRECT

CàAFAFàC

BEàGHBàJBCEàD

ABCDEFGHIJ

BàJ

BJ ABCDEFGHI

ButAFàInotassignabletoanyrela>onthatresultsfromthisdecomposi>on,sodependencypreserva>onappearstobeviolatedsoIDIDgivecreditforthischoice(butdependencypreserva>onisNOTviolated–seenextpage)

Page 7: Midterm Examination CS 265 Spring 2016 Name: KEY

7

3. (5 pts) Consider the relational schema, R = [A B C D E F G H I J ] with applicable FDs

A, F à C, I is equiv to A,FàC and A,FàI B, E à G, H B à J B, C, E à D C à A, F

Reflect on the task of decomposing relation R into a set of BCNF relations. For example, I might use B à J as the first step to decompose R: Circle the FD(s) in the list above that would NOT be used as the first step to decompose R using the decomposition procedure described in class. Beside each circled FD, give a brief explanation of why you would not use that FD to decompose the relation R.

ABCDEFGHIJ

CàAF

CAF BCDEGHICàAFAFàC

BEàGHBàJBCEàDCàI

ABCDEFGHIJ

BàJ

BJ ABCDEFGHI

Inthisalterna>veminimalset,CàIisassignabletoarela>oninthedecomposi>on,sodependencypreserva>onisNOTviolated

CàAFtogetherwithAFàIimplyCàI,sooneminimalsetwouldexcludeCàIinfavorofCàAFandAFàI(thisisthesetgiventotheleY)But,analterna>veminimalsetthatimpliesallthesameFDswouldincludeCàIandexcludeAFàI!!!

Page 8: Midterm Examination CS 265 Spring 2016 Name: KEY

8

3. (5 pts) Consider the relational schema, R = [A B C D E F G H I J ] with applicable FDs

A, F à C, I B, E à G, H B à J B, C, E à D C à A, F

Reflect on the task of decomposing relation R into a set of BCNF relations. For example, I might use B à J as the first step to decompose R: Circle the FD(s) in the list above that would NOT be used as the first step to decompose R using the decomposition procedure described in class. Beside each circled FD, give a brief explanation of why you would not use that FD to decompose the relation R.

ABCDEFGHIJ

AFàCI

CAF ABDEFGH

WhataboutthisFD?

AFàCICàAF

BEàGHBàJBCEàD

ABCDEFGHIJ

BàJ

BJ ABCDEFGHI

AlltheFDs(inaminimalset)areassignabletoarela>on,sodecomposingonAFàCImaintainsdependencypreserva>on.So,nothingwrongWithdecomposingbasedonthisFD.IdidNOTgivecreditforthischoice

B,C,A,F,Eisalsoakeyofrela>onR,andsoB,A,F,Eisakeyofthisrela>onaswell

Page 9: Midterm Examination CS 265 Spring 2016 Name: KEY

4. (5 points) Consider the following four table definitions, together with all entries in each of the four tables.

CREATE TABLE Customer ( SSN Integer, ... PRIMARY KEY (SSN)); CREATE TABLE Product ( ProdID Integer, ... PRIMARY KEY (ProdId));

CREATE TABLE Account ( SSN Integer NOT NULL, AccntNo Integer, ... PRIMARY KEY (AccntNo), FOREIGN KEY (SSN) REFERENCES Customer ON UPDATE CASCADE);

CREATE TABLE Transaction ( TransID Integer, AccntNo Integer, ProdId Integer, ... PRIMARY KEY (TransID), FOREIGN KEY (AccntNo) REFERENCES Account ON UPDATE NO ACTION, /* aka RESTRICT */ FOREIGN KEY (ProdId) REFERENCES Product ON UPDATE CASCADE); Customer SSN ...

Ssn1 ... Ssn2Ssn5... Ssn3 ...

Account SSN AccntNo ...

Ssn1 Acct1 ... Ssn2Ssn5 Acct4 ... Ssn1 Acct2 ... Ssn2 Ssn1 Acct3 ... Ssn2Ssn5 Acct5 ... Ssn3 Acct6 ...

Transaction TransID AcctNo ProdID ...

Product ProdID ...

Pid1 ... Pid2 ... Pid3 Pid4 ...

Change all attribute values as a result of performing these UPDATE operations in order (BE NEAT!!!). If an operation fails, and has no effect as a result, then move to the next operation. UPDATE Transaction SET AccntNo = Acct4 WHERE TransID = Tid2; UPDATE Account SET AccntNo = Acct1 WHERE AccntNo = Acct5; violates PK, fails UPDATE Account SET SSN = Ssn1 WHERE AccntNo = Acct3; UPDATE Product SET ProdID = Pid4 WHERE ProdID = Pid3; cascades to Trans UPDATE Customer SET SSN = Ssn5 WHERE SSN = Ssn2; cascades to Account UPDATE Account SET AccntNo = Acct7 WHERE SSN = Ssn3; blocked in Trans

Tid1 Acct6 Pid3Pid4 ... Tid2 Acct3 Acct4 Pid2 ... Tid3 Acct3 Pid3Pid4 ...

9

No change

+1pt+1pt

+1pt

+1pt+1pt

-2ptifthischanged;-1foranyotherchange

Page 10: Midterm Examination CS 265 Spring 2016 Name: KEY

5. (5 pts) Consider the UML fragment to the right and identify (circle) all equivalent table translations (i.e., those translations that faithfully enforce the constraints implied by the UML without regard to elegance) from those given below. You might receive partial credit for a brief explanation of your choices. UNIQUE(y) implies that y NOT NULL, but not vice versa. PK stands for PRIMARY KEY. FK stands for FOREIGN KEY.

CREATE TABLE XR ( x1, r1, role2, PK(x1), FK (role2) refs XR )

CREATE TABLE X ( x1, PK (x1) ) CREATE TABLE R ( r1, role1, role2 NOT NULL, PK(role1), FK (role2) refs X, FK (role1) refs X )

CREATE TABLE X ( x1, PK (x1), FK (x1) refs R ) CREATE TABLE R ( x1, r1, role1 NOT NULL, PK(r1), FK (role1) refs X, FK (x1) refs X )

(A) (B) (C)

(F) None of the above

CREATE TABLE XR ( x1, r1, role2 NOT NULL, PK(x1), FK (role2) refs XR )

(D) (E)

CREATE TABLE XR ( x1, r1, role2, PK(x1), UNIQUE(role2), FK (role2) refs XR )

X x1 PK

r1 R 0..*

10

0..1

role1

role2

Risanassocia>onclass

Thistransla>oncombinesXandR,role2isallowedtobeNULL,soeachXisassociatedwithatmostoneotherX(throughRole2).Notethatapar>cularXservinginarole2,candosowith0ormoreXs(x1).e.g.,role2=abccanbein3rowsoftableXR,represen>ngsitua>onwhereabcpar>cipateswiththreedifferentx1s(role1s)

+3ptsforoneand+5forboth

Inthistransla>onthereisnothingtorequirethatanXappearinRXandR,role2isallowedtobeNULL,soeachXisassociatedwithatmostoneotherX(throughRole2)

-5for(F)

-1forA,C,orE;-3foranytwo;-5forallthree

Thisrequiresrole2tobeNOTNULLandwouldbecorrectfor1..1,butnot0..1

TheUMLdoesnotimplythatrole2isacandidatekey,andindeed,eachX(andthusrole2)canpar>cipatewith0ormoreX’sthroughrole1

Thedefini>onforTableXindicatesthateveryXhastopar>cipateinR

Page 11: Midterm Examination CS 265 Spring 2016 Name: KEY

11

6. (5 points) A health facility wants to measure the AVERAGE (AVG) spread in the weight of clients between the ages of 45 and 60, inclusive, who have at least 100 weight entries in the facility’s DB. The spread of a client’s weight is the maximum weight on record in the facility’s DB minus the minimum weight on record in the DB (regardless of age at the time the weight entries were made). The DB contains two tables representing these two relations (among others). Client (cid, name, age, address, phone, ...) DailyRecord(cid, date, weight, ...) Primary key attributes of each table (relation) are bold-face and underlined. In the actual table definitions, the attribute of age is declared as NOT NULL, and weight can be NULL. Complete the following skeletal query to compute the AVERAGE (AVG) spread in the weight of clients between the ages of 45 and 60, inclusive, with at least 100 weight entries, by filling in the blanks.

SELECTAVG(Temp.Flux)FROM(SELECTMAX(D.weight)–MIN(D.weight)ASFluxFROMClientC,DailyRecordDWHEREC.id=D.idANDD.weightISNOTNULLANDC.age>=45ANDC.age<=60GROUPBYC.idHAVINGCOUNT(*)>=100)ASTemp

Asanaside,itislikelythatinsteadofrepresen>ng‘age’asanexplicitanribute,wewouldalterna>vely(orperhapsaddi>onally),storeBirthDateandcompute‘age’ondemandorsomehatproac>velywithaTriggeronaregularbasis.

Page 12: Midterm Examination CS 265 Spring 2016 Name: KEY

12

6. (5 points) A health facility wants to measure the AVERAGE (AVG) spread in the weight of clients between the ages of 45 and 60, inclusive, who have at least 100 weight entries in the facility’s DB. The spread of a client’s weight is the maximum weight on record in the facility’s DB minus the minimum weight on record in the DB (regardless of age at the time the weight entries were made). The DB contains two tables representing these two relations (among others). Client (cid, name, age, address, phone, ...) DailyRecord(cid, date, weight, ...) Primary key attributes of each table (relation) are bold-face and underlined. In the actual table definitions, the attribute of age is declared as NOT NULL, and weight can be NULL. Complete the following skeletal query to compute the AVERAGE (AVG) spread in the weight of clients between the ages of 45 and 60, inclusive, with at least 100 weight entries, by filling in the blanks.

SELECTAVG(Temp.Flux)FROM(SELECTMAX(D.weight)–MIN(D.weight)ASFluxFROMClientC,DailyRecordDWHEREC.id=D.idANDD.weightISNOTNULLANDC.age>=45ANDC.age<=60GROUPBYC.idHAVINGCOUNT(*)>=100)ASTemp

Asanaside,itislikelythatinsteadofrepresen>ng‘age’asanexplicitanribute,wewouldalterna>vely(orperhapsaddi>onally),storeBirthDateandcompute‘age’ondemandorsomewhatproac>velywithaTriggeronaregularbasis.

Alternatetakesaveragesofmaxandminfirst(inSELECTofnestedquery)andthentakesdifferencebetweenaveragesinouterquery(SELECT)--seenextpage

1ptforjoincondiCon

1pt

1pt

2ptsforrest,usediscreCon

Okifweightcheckismissing,butnotnextCme,parCcularlywiththecallout

Countrows(*),ratherthanthevaluesofaparHcularfield

Page 13: Midterm Examination CS 265 Spring 2016 Name: KEY

13

6. (5 points) A health facility wants to measure the AVERAGE (AVG) spread in the weight of clients between the ages of 45 and 60, inclusive, who have at least 100 weight entries in the facility’s DB. The spread of a client’s weight is the maximum weight on record in the facility’s DB minus the minimum weight on record in the DB (regardless of age at the time the weight entries were made). The DB contains two tables representing these two relations (among others). Client (cid, name, age, address, phone, ...) DailyRecord(cid, date, weight, ...) Primary key attributes of each table (relation) are bold-face and underlined. In the actual table definitions, the attribute of age is declared as NOT NULL, and weight can be NULL. Complete the following skeletal query to compute the AVERAGE (AVG) spread in the weight of clients between the ages of 45 and 60, inclusive, with at least 100 weight entries, by filling in the blanks.

SELECTAVG(Temp.MaxWeight)–AVG(Temp.MinWeight)(orAVG(Temp.MaxWeight-Temp.MinWeight))

FROM(SELECTMAX(D.weight)ASMaxWeight,MIN(D.weight)ASMinWeightFROMClientC,DailyRecordDWHEREC.id=D.idANDD.weightISNOTNULLANDC.age>=45ANDC.age<=60GROUPBYC.idHAVINGCOUNT(*)>=100)ASTemp

Asanaside,itislikelythatinsteadofrepresen>ng‘age’asanexplicitanribute,wewouldalterna>vely(orperhapsaddi>onally),storeBirthDateandcompute‘age’ondemandorsomewhatproac>velywithaTriggeronaregularbasis.

Alternate(topreviouspage)

Page 14: Midterm Examination CS 265 Spring 2016 Name: KEY

7. (5 pts) Consider the following table definition: CREATE TABLE HRel (ID integer, name integer, PRIMARY KEY (ID)) Circle all queries below that return the tuples of HRel with the top 5 values of ID

(b) SELECT H.ID, H.name FROM HRel H WHERE (SELECT COUNT (*) FROM HRel H2 WHERE H.ID < H2.ID) < 5 ORDER BY H.ID DESC (d) SELECT H.ID, H.name FROM HRel H EXCEPT SELECT H1.ID, H1.name FROM HRel H1, HRel H2 WHERE H1.ID < H2.ID GROUP BY H1.ID, H1.name HAVING COUNT(*)+1 > 5 ORDER BY ID DESC

(a) SELECT H.ID, H.name FROM HRel H WHERE NOT EXISTS (SELECT * FROM HRel H1, HRel H2 WHERE H.ID = H1.ID AND H1.ID < H2.ID GROUP BY H1.ID HAVING COUNT(*) >= 5) ORDER BY ID DESC (c) SELECT H.ID, H.name FROM HRel H EXCEPT SELECT H.ID, H.name FROM HRel H WHERE (SELECT COUNT (*) FROM HRel H2 WHERE H.ID < H2.ID) >= 5 ORDER BY H.ID DESC (e) None of the above

14

0pts

+2fora,b,c,ord;3foranytwo;4foranythree;5forallfour

Page 15: Midterm Examination CS 265 Spring 2016 Name: KEY

7. (5 pts) Consider the following table definition: CREATE TABLE HRel (ID integer, name integer, PRIMARY KEY (ID)) Circle all queries below that return the tuples of HRel with the top 5 values of ID

(a) SELECT H.ID, H.name FROM HRel H WHERE NOT EXISTS (SELECT * FROM HRel H1, HRel H2 WHERE H.ID = H1.ID AND H1.ID < H2.ID GROUP BY H1.ID HAVING COUNT(*) >= 5) ORDER BY ID DESC (c) SELECT H.ID, H.name FROM HRel H EXCEPT SELECT H.ID, H.name FROM HRel H WHERE (SELECT COUNT (*) FROM HRel H2 WHERE H.ID < H2.ID) >= 5 ORDER BY H.ID DESC

15

ThinkofH.IDasaconstantintheinnerquery.Ifthereare5ormoreotherrows(H2)withagreaterIDvaluethanH.ID,then(essenHally)returnallthoseotherrows.Theouterqueryisonlyinterestedinwhetherthatreturnedsetinemptyornot.IfH.IDis(1st)biggest,thentherewillbe0greaterIDsIfH.IDis2ndbiggest,thentherewillbe1greaterIDs…IfH.IDis5thbiggest,thentherewillbe4greaterIDs

ReturneachrowofHRelthatdoesNOThave5ormorerowswithagreaterIDvalue

ThequesHondidn’tinsistonordering,sothisislargelyirrelevant,butkeptitinallvariaHonssoasnottoconfuse

ReturnallrowsofHRelEXCEPTthosehavingthosewith5ormorerowshavingagreaterIDvalueCOUNTthenumberofrowswithgreaterIDvaluethanH.IDIsthiscountgreaterthanorequalto5?

Page 16: Midterm Examination CS 265 Spring 2016 Name: KEY

7. (5 pts) Consider the following table definition: CREATE TABLE HRel (ID integer, name integer, PRIMARY KEY (ID)) Circle all queries below that return the tuples of HRel with the top 5 values of ID

(b) SELECT H.ID, H.name FROM HRel H WHERE (SELECT COUNT (*) FROM HRel H2 WHERE H.ID < H2.ID) < 5 ORDER BY H.ID DESC (d) SELECT H.ID, H.name FROM HRel H EXCEPT SELECT H1.ID, H1.name FROM HRel H1, HRel H2 WHERE H1.ID < H2.ID GROUP BY H1.ID, H1.name HAVING COUNT(*)+1 > 5 ORDER BY ID DESC

16

ReturneachrowofHRelthatfewerthan5rowswithagreaterIDvalue

ReturnallrowsofHRelEXCEPTthoserows(H1)with5ormorerows(H2)withgreaterID

Page 17: Midterm Examination CS 265 Spring 2016 Name: KEY

17

8. (5 pts) Consider the following relational schema (underlined variables in each schema make up its primary key)

Supplier ( sid: integer, sname: string, address: string, city: string) Catalog (sid: integer, pid: integer, cost: real) Part (pid: integer, pname: string, color: string)

a) (3 pts) Give a relational algebra expression that implements the query specified as

Find the sids of Suppliers that supply any green part and are in the city of Nashville. Project(sid) ( select(color=Green and city=Nashville) (Supplier njoin Catalog njoin Part)) b) (2 pts) Give a left-deep expression tree for the relational algebra expression that you give in (a)

Technically, I might have required that only the left deep expression tree that would have been correct here is one that resulted in the expression of 8a when a post-order traversal was carried out on it. But any correct expression tree in which the right child of each join is a base table received full credit (see next page)

njoinmeansnaturaljoin

Page 18: Midterm Examination CS 265 Spring 2016 Name: KEY

18

Page 19: Midterm Examination CS 265 Spring 2016 Name: KEY

19

9. (5 pts) Assume that you have a DB with a table, Likes(a, b) (read ‘a’ likes ‘b’),with Primary Key (a,b). Write a trigger so that when a row is inserted into ‘Likes’ of the form Likes(X, 'Friendly’), where ‘Friendly’ is a constant and X can match any value, a tuple that indicates that ‘Friendly’ Likes X is inserted into Likes (unless it is already in the table). So if Likes(‘Abe’, ‘Friendly’) is inserted, then Likes(‘Friendly’, ‘Abe’) is inserted. MOREOVER, for each person, Y, who X Likes, the trigger also inserts Likes (‘Friendly’, Y) (unless it is already there). So if Likes(‘Abe’, ‘Mary’) and Likes(‘Abe’, ‘Hua’) are in Likes, and Likes(‘Abe’, ‘Friendly’) is inserted into Likes, then Likes(‘Friendly’, Abe) is inserted, and so is Likes(‘Friendly’, ‘Mary’) and Likes(‘Friendly’, ‘Hua’). Use as close to SQLite syntax as you can. CREATE TRIGGER RinsFriendly AFTER INSERT ON Likes REFERENCING NEW ROW AS new FOR EACH ROW /* Complete the Trigger definition */ WHEN new.b = 'Friendly' BEGIN INSERT INTO Likes VALUES (‘Friendly’, new.a); INSERT INTO Likes(a, b) SELECT ‘Friendly’, L.b FROM Likes L WHERE new.a = L.a END;

ImpliedbySQLite,butokifadded

1pt

1pt

3pt

Page 20: Midterm Examination CS 265 Spring 2016 Name: KEY

20

9. (5 pts) Assume that you have a DB with a table, Likes(a, b) (read ‘a’ likes ‘b’),with Primary Key (a,b). Write a trigger so that when a row is inserted into ‘Likes’ of the form Likes(X, 'Friendly’), where ‘Friendly’ is a constant and X can match any value, a tuple that indicates that ‘Friendly’ Likes X is inserted into Likes (unless it is already in the table). So if Likes(‘Abe’, ‘Friendly’) is inserted, then Likes(‘Friendly’, ‘Abe’) is inserted. MOREOVER, for each person, Y, who X Likes, the trigger also inserts Likes (‘Friendly’, Y) (unless it is already there). So if Likes(‘Abe’, ‘Mary’) and Likes(‘Abe’, ‘Hua’) are in Likes, and Likes(‘Abe’, ‘Friendly’) is inserted into Likes, then Likes(‘Friendly’, Abe) is inserted, and so is Likes(‘Friendly’, ‘Mary’) and Likes(‘Friendly’, ‘Hua’). Use as close to SQLite syntax as you can. CREATE TRIGGER RinsFriendly AFTER INSERT ON Likes REFERENCING NEW ROW AS new FOR EACH ROW /* Complete the Trigger definition */ WHEN new.b = 'Friendly’ BEGIN INSERT INTO Likes VALUES (new.b, new.a) WHERE <not redundant>; INSERT INTO Likes(a, b) SELECT new.b, L.b FROM Likes L WHERE new.a = L.a AND <not redundant> END;

Someanswersgeneralizedtheintendedanswer,byallowingavariableinplaceof“Friendly”and/oraddedteststoguaragainstanemptstoinsertduplicaterows.Ingeneral,bothwerefine.

Page 21: Midterm Examination CS 265 Spring 2016 Name: KEY

21

10. (5 points) Consider the following definitions, and give a UML diagram (on the right of the page) that is consistent with the definitions.

CREATE TABLE M ( m1, PRIMARY KEY (m1) ) CREATE TABLE Q ( q1, PRIMARY KEY (q1) ) CREATE TABLE R ( r1, m1, q1, PRIMARY KEY (m1, q1), FOREIGN KEY (m1) REFERENCES M, FOREIGN KEY (q1) REFERENCES Q ) CREATE ASSERTION MparticipatesQ CHECK (NOT EXISTS (SELECT * FROM M WHERE M.m1 NOT IN (SELECT m1 FROM R)))

M m1 PK

1..*

Q q1 PK

R r1

0..*

1pointfor1..*

1pointfor0..*

2pointsforR

1pointforboth(noteach)MandQclasses