algebraanswers

Share Embed Donate


Short Description

Download algebraanswers...

Description

Relational Algebra Questions and Answers Database Systems, CSCI 4380-01 September 19, 2002

Question 1 Write the following queries using the relational algebra and show the result of each query as it applies to the tables below. You are not allowed to use any aggregates or the division operator. S(S#, SNAME, STATUS, CITY) //Supplier relation P(P#, PNAME, COLOR, WEIGHT, CITY) //Part relation J(J#, JNAME, CITY) //Job relation SPJ(S#, P#, J#, QTY) //Suppliers of Parts for Jobs relation

1. Find all suppliers with status ”30” that supply part ”P2”. For each supplier, output the name and the quantity of part ”P2” they supply. 2. Find and output the supplier numbers for all suppliers who either supply a ”Blue” part or supply to a job in ”Athens.”

Answer. 1. ΠSN AM E,QT Y ((σStatus=30 (S) ./S#=S# σP #=0 P 20 (SP J))), or ΠSN AM E,QT Y (σStatus=30 AND P #=0 P 20 (S ./S#=S# SP J)). Remember: you cannot find total quantity in relational algebra without the explicit aggregate functions. This finds the quantity of part P2 for some job. 2. Result := (ΠS# (σColor=0 Blue0 (P ) ./P #=P # SP J)) ∪ (ΠS# (σCity=0 Athens0 (P ) ./J#=J# SP J)).

1

Question 2 You are given the following relational schema for family relations.: Person ( PID, PersonName, Sex, Cityofbirth ) Parent ( ParentID, ChildID ) // both ParentID and ChildID are foreign keys referring to Person.PID Write the following queries in relational algebra using only selection, projection, join, cartesian product, set union, intersection and difference. a. Find the name of grandparents of all people who were born in New York city. b. Find the name of all people who were born in the same city as their father. Answer. a. T emp1 := σCityof Birth=0 N ewY ork0 P erson //people born in New York T emp2 := (ΠP arentId (P arent ./ChildId=P ID T emp1)[P arentId1] //parents of people in Temp1 T emp3 := ΠP ersonN ame (P erson ./P ID=P arentId (P arent ./ChildId=P arentId1 T emp2)) // name of grandparents b. T emp1 := P erson[P ID1, P ersonN ame1, Sex1, Cityof Birth1] Result := ΠP ersonN ame1 (σCityof Birth=Cityof Birth1 (P erson ./P ID=P arentId (σSex=0 M 0 (P arent) ./ChildId=P ID1 T emp1)))

2

Question 3 You are given the following relational schema for students. Student( SID, Sname, Curriculum ) Takes ( CourseID, SID, Semester, Grade ) //Semester is of the form ”Fall 98”, ”Spring 99”, etc. Write the following queries in relational algebra using only selection, projection, join, cartesian product, set union, intersection and difference. a. Find the id of all students who took the same course in two different semesters. b. Find the name of all students who never got an F. Answer. a. ΠSID (T akes ./CourseId=CourseId AND SID=SID AND SemesterSemester T akes) b. T emp1 := ΠSID Student − (ΠSID (σGrade=0 F 0 T akes)) //Id of students who never got an F Result := ΠSname (Student ./SID=SID T emp1).

3

Question 4 School Database: STUDENT( sid, lastname, firstname, major, entrydate ) COURSE( course number, dept id, course name) DEPARTMENT( dept id, department name, address ) INSTRUCTOR( instructor id, firstname,lastname, dept id ) SECTION ( section id, section number, course number, dept id, semester, instructor id ) TRANSCRIPT( sid, section id, grade ) REQUIREMENT( req id, major, course number, dept id ) The above database contains information about a school. Information about students are stored in the STUDENTS relation. All courses offered by all departments are listed in the COURSE relation. The DEPARTMENT relation contains various departments in the school and INSTRUCTOR contains the different instructors from different departments. A course may be offered in multiple sections in a given semester. This information is stored in the SECTION relation. The TRANSCRIPT contains the information about when a student took a specific section of a course and his or her grade. If a student is currently taking a course, then the grade attribute will have a null value. Finally, all the courses students are required to take for a given major are listed in the REQUIREMENT relation. Given the above relational schema, write the following queries using relational algebra. Try to use compact expressions for your queries. 1. Find the last name, first name and major of all students taking any section of the course ”4380” offered by the ”Computer Science” department in ”Fall 99”. 2. Find the first name and last name of all instructors who taught the course ”4380” offered by the ”Computer Science” department. 3. Find the number and department identifier of all courses in which no student ever got an ”F”. 4. Find the identifier of all instructors who are teaching at least three sections of a course in the same semester. 5. Find the identifier of all students who took all the required courses for their majors -even if they do not have a grade for some of the courses yet.

Answer. 1. Find the last name, first name and major of all students taking any section of the course ”4380” offered by the ”Computer Science” department in ”Fall 99”. CD := σ(course number=4380) AND (department DEP ART M EN T ) CS := CD ./dept

id=dept id

(Πsection

name=”ComputerScience”) (COU RSE

./dept

id=dept id

id (σsemester=”F all99” SECT ION ))

T S := Πlastname,f irstname,major (CS ./section

id=section id

4

T RAN SCRIP T ./sid=sid ST U DEN T )

Note: CD is all courses numbered 4380 offered by the Computer Science Department. CS is the identifier of all sections of this course offered in Fall99. TS is all students taking any of the sections in CS. 2. Find the first name and last name of all instructors who taught the course ”4380” offered by the ”Computer Science” department. IN := Πinstructor id (CD ./section id=section id SECT ION ) IN 2 := Πf irstname,lastname (IN ./instructor id=instructor id IN ST RU CT OR) Note. CD is the same as above. IN is the id of instructor who taught any section of course 4380 from Computer Science Department. IN2 is the result which has the name of the instructors. 3. Find the number and department identifier of all courses in which no student ever got an ”F”. F Sections := Πsection id (σgrade=0 F 0 T RAN SCRIP T ) F C := Πcourse number,dept id (F sections ./section id=section N oF := (Πcourse number,dept id COU RSE) − F C

id

Section)

Note. Fsections are the identifiers of all section in which a student got an F. FC is all courses (given by course number and department id) in which a student got an F. Finally, NoF is the result. We take all courses and subtract from this the courses in which a student got an F. 4. Find the identifier of all instructors who are teaching at least three sections of a course in the same semester.

S1 := SECT ION [sec id1, sec num1, course num1, dept id1, semester1, instr id1] S2 := SECT ION [sec id2, sec num2, course num2, dept id2, semester2, instr id2] T emp1 := σ(course

number=course num1) AND (course number=course num2) AND (course num1=course number2)

(S1 × S2 × SECT ION ) T emp2 := σ(instructor T emp3 := σ(dept

id=instr id1) AND (instructor id=instr id2) AND (instr id1=instr id2) T emp1

id=dept id1) AND (dept id=dept id2) AND (dept id1=dept id2) T emp2

T emp4 := σ(semester=semester1) AND (semester=semester2) AND (semester1=semester2) T emp3 T emp5 := σ(section

idsec1) AND (sec1 idsec2 id) AND (section idsec2 id) T emp4

Note. We first create three different copies of the SECTION relation. Then, we take the cartesian product. The cartesian product contains combinations of three tuples, all coming from the section relation. We are now looking for a tuple in the cartesian product that is composed of three different tuples from the SECTION relation, each tuple is for the same professor, same course number, same department id and the same semester, the three sections are different. The result is then what we are looking for. 5. Find the identifier of all students who took all the required courses for their majors -even if they do not have a grade for some of the courses yet. SR := σsid,course SC := σsid,course

number,department id (ST U DEN T number,department

./major=major REQU IREM EN T ) (SECT ION ./ id section id=section id T RAN SCRIP T ) 5

ReqsN otT aken := Πsid (SR − SC) T akenAll := Πsid ST U DEN T − ReqsN otT aken Note. SR is the requirements for each student. SC is the all courses students have taken. ReqsNotTaken is the identifier of all students who have not taken a required course. If we subtract this from all students, we are left with student who have taken all their required courses.

6

Question 5 EMPLOYEE( ssn, firstname, lastname, title, salary, dept id, mgr id) DEPARTMENT( dept id, departmentname, totalbudget) Use the two relations given above to write the following queries using relational algebra: 1. Find the first and last name of managers such that none of his/her employees work in the same department as their boss (i.e. the department of all employees is different than the department of their boss). 2. Find the name of all departments that has no employee working in them.

Answer. 1. T emp0 := EM P LOY EE[ssn1, f irstname1, lastname1, title1, salary1, dept id1, mgr id1] T emp1 := EM P LOY EE ./mgr id=ssn1 AND dept id=dept id1 T emp0 T emp2 := σf irstname,lastname (EM P LOY EE ./ssn=mgr id (Πmgr id EM P LOY EE−(Πssn1 T emp1)[mgr id])) 2. Πdepartmentname (DEP ART M EN T ./dept

id=dept id

7

(Πdept

id DEP ART M EN T −Πdept id EM P LOY

EE))

Question 6 Given BOOKS( ISBN, Author, Title, Publisher, Publish Date, Pages, Notes ) STORE( Store Id, Store Name, Street, State, City, Zip ) STOCK( ISBN, Store Id, Price, Quantity ) Use the three relations above to write the following queries using relational algebra: 1. Find the identifier of all stores that carry a non-zero quantity of every book in the ”BOOKS” relation. 2. Find the name and address of all stores that do not carry any books by ”J.D. Salinger”.

Answer. 1. Find the identifier of all stores that carry a non-zero quantity of every book in the ”BOOKS” relation. T 1 := (ΠStore Id ST ORE) × (ΠISBN BOOKS) T 2 := ΠStore Id (T 1 − (ΠStore id,ISBN (σQuantity>0 ST OCK))) T 3 := (ΠStore Id ST ORE) − T 2. T 1 is the set of all possible books a store can sell in terms of store and book identifiers. T 2 contains stores that have at least one book that they do not have a non-zero quantity of. T 3 is the final result. 2. T 1 := ΠStore T 2 := ΠStore

− ΠStore Id (σAuthor=0 J.D.Salinger0 BOOKS ./ISBN =ISN ST OCK) N ame,Street,State,Zip (T 1 ./Store Id=Store Id ST ORE)

Id ST ORE

8

Question 7 You are given the following set of relations for an Olympic database for events involving competition among individual athletes. All events in this database measure success by the shortest time (such as running). Athlete(id, name, birthdate, country, height, weight) Sports(id, name, description, category, mw) Participate(athlete, sport, pr) Records(type, sport, recordtime, athlete, date) Sports.category is one of ”running”, ”swimming”, Sports.mw refers to ”men” or ”women” events. Participate.pr is the personal record of an athlete for a sport. The ”pr” of an athlete may be better than the current records (just not been set at a race). Records.type is one of WR/OR for World and Olympic records. Records.sport, Participate.sport are foreign keys pointing to Sports.id Records.athlete, Participate.athlete are foreign keys pointing to Athlete.id Write the following queries in Relational Algebra: 1. Find all athletes who participate in only one sport. Return their name. 2. Find all record holder athletes whose personal record time is greater than their record. Return the name of the athletes. 3. Find all athletes who are not record holders for a specific sport and are faster than at least one of the current record holders for this sport. Return the name of the athlete and the name of the sport. 4. Find all pairs of sports S1, S2 such that there does not exist an athlete that participate in both S1 and S2. Return pairs of sports ids. Do not return repetitive tuples such as ”(1,2)” and ”(2,1)”.

Answer. 1. Find all athletes who participate in only one sport. Return their name. The result is in T 3. T 1 := P articipate ./athlete=athlete AND sportsport P articipate T 2 := (Πid Athlete)[athlete] − (Πathlete T 1) T 3 := Πname (T 2 ./athlete=id Athlete) 2. Find all record holder athletes whose personal record time is greater than their record. Return the name of the athletes. T 1 := P articipate ./athlete=athlete AND sport=sport AND pr>recordtime Records T 2 := Πname (T 1 ./athlete=id Athlete) 3. R1 is the set of all people with personal record better than the current record time. We then have to make sure that the people in R1 are not record holders for their specific sport, the 9

identifiers for athletes and sports are given in R2. The remaining joins are needed to find the names of sports and athletes.

R0 := P articipate[athlete1, sport1, pr1] R1 := σpr1>recordtime (Records ./athleteathlete1 AND sport=sport1 R0) R2 := (Πathlete,sport R1 − Πathlete,sport Records)[id, sport] R3 := (Πid,name Sports)[sport, sportname] Result := Πname,sportname (Athlete ./id=id R2 ./sport=sport R3) 4. Find first all pairs of sports for which there exists a common athlete (R3). Then, find all possible pairs of sports (R4 × R5). Final selection on sport > sport2 ensures that there are no duplicate entries.

R1 := (Πathlete,sport P articipate)[athlete2, sport2] R2 := P articipate ./sportsport2 AND athlete=athlete2 R1 R3 := Πsport,sport2 R2 R4 := (ΠidSports)[sport] R5 := (Πid Sports)[sport2] R6 := σsport>sport2 ((R4 × R5) − R3)

10

Question 8 In this question, you are given the following simple database of employees that work in specific departments. Each department has an inventory of items with specific quantity. EMPLOYEE(ssn, first-name, last-name, address, date-joined, supervisor-ssn) DEPARTMENT(dept-no, name, manager-ssn) WORKS-IN(employee-ssn, dept-no) INVENTORY(dept-no, item-id, quantity) ITEMS(item-id, item-name, type) Foreign keys: 1. EMPLOYEE.supervisor-ssn and WORKS-IN.employee-ssn point to EMPLOYEE.ssn. 2. WORKS-IN.dept no and INVENTORY.dept-no point to DEPARTMENT.dept no. 3. INVENTORY.item-id points to ITEMS.item-id.

1. You are given the below relational algebra query. Write an SQL query that returns the same answer as R5 below. Explain your answer by writing the meaning of this query in English. R1 := W ORKS − IN [ssn, dept − no] R2 := W ORKS − IN [ssn2, dept − no2] R3 := (EM P LOY EE ./ssn=ssn R1) × R2 R4 := σsupervisor−ssn=ssn2 AND dept−no=dept−no2 R3 R5 := Πf irst−name,last−name R4 2. You are given the below relational algebra query. Write an SQL query that returns the same answer as R5 below. Explain your answer by writing the meaning of this query in English. R1 := (Πitem−id IT EM S) − (Πitem−id IN V EN T ORY ) R2 := IT EM S ./item−id=item−id R1 R3 := σtype=”CD” R2 R4 := Πitem−name R3

Answer. 1. The query returns the firstname and lastname of all employees who work in the same department as their supervisor. 2. R4 is the name of all items of type ’CD’ that are NOT in any inventory.

11

Question 9 You are given the simple relational database below that shows students, courses they took and courses they are required to take. Student(ssn, name, major, year) // lists all students Course (cid, name, description, department) // lists course information Offered(cid, semester, section, ins id, location) // lists all course offerings for different semesters Instructor(ins id, name, department) // lists all instructors Took(ssn, cid, semester, section, grade) // lists when a student took a course Required(major, cid) // lists which courses are required for a specific major Took.cid, Required.cid Offered.cid are foreign keys, they refer to the course.cid. Offered.ins id is a foreign key, refers to Instructor.ins id. Took.ssn is a foreign key, refers to Student.ssn. Write the following queries in relational algebra using only set union, intersection, difference, select, project and Cartesian product operations:

1. Find the name of all instructors who have offered at least one course. 2. Find all students who have taken the same course (given by cid) twice. 3. Find the name of all courses (from Course) that have never been offered according to Offered. 4. Return pairs of student name and course names such that the student is required take this course for his/her listed major. 5. Use your answer from part d to find all students who have taken all the required courses for their major.

Answer. 1. Find the name of all instructors who have offered at least one course. R1 := (Πins id Of f ered)[ins id2] R2 := Πname (σins id=ins id2 (Instructor × R1)) 2. Find all students who have taken the same course (given by cid) twice. R1 := (Πssn,cid,semester1,section1 T ook)[ssn1, cid1, semester1, section1] R2 := σ(ssn1=ssn) AND (cid1=cid) AND ((semester1semester) OR (section1section) (R1 × T ook) R3 := σssn1=ssn (Πssn1 R2 × Student) R4 := Πname R3 3. Find the name of all courses (from Course) that have never been offered according to Offered. R1 := (Πcid Course − Πcid Of f ered)[cid1] R2 := Πname (σcid1=cid (R1 × Course)

12

4. Return pairs of student name and course names such that the student is required take this course for his/her listed major. R1 := Student[ssn1, sname, major1, year1] R2 := σmajor=major1 (R1 × Required) R3 := (Πcid,name Course)[cid2, cname] R4 := Πsname,cname (σcid2=cid (R2 × R3)) 5. Use your answer from part d to find all students who have taken all the required courses for their major. R1 := (Πssn,major Student)[ssn, major1] R2 := Πssn,cid (σmajor=major1 (R1 × Required)) R3 := Πssn,cid T ook R4 := Πssn (R2 − R3) R5 := (Πssn Student − R4)[ssn1] R6 := Πname (σssn1=ssn (R4 × Student)) Note. R2 lists all required courses for students. R4 is all students who still need to take some required courses, R5 is all students who have taken all the required courses.

13

Question 10 You are given the below relational model. Artist( ArtistName, ArtistYear, Origin, ArtistTones, Biography ) SimilarArtist(FromArtistName, FromArtistYear,ToArtistName, ToArtistYear) Song( SongId, SongName, DateComposed ) Album( AlbumId, AlbumTitle, Duration, Rating, Review, ReleaseDate, AlbumTones, ArtistName, ArtistYear, LabelName ) Track( AlbumId, TrackId, Recommended, SongId ) LyricsBy( SongId, ArtistName, ArtistYear ) MusicBy( SongId, ArtistName, ArtistYear ) MajorArtist( ArtistName ArtistYear, LabelName ) Foreign keys: Album(ArtistName, ArtistYear) references Artist(ArtistName, ArtistYear) SimilarArtist(FromArtistName, FromArtistYear) references Artist(ArtistName, ArtistYear) SimilarArtist(ToArtistName, ToArtistYear) references Artist(ArtistName, ArtistYear) Track(AlbumId) references Album(AlbumId) Track(SongId) references Song(SongId) LyricsBy(SongId) references Song(SongId) MusicBy(SongId) references Song(SongId) LyricsBy(ArtistName, ArtistYear) references Artist(ArtistName, ArtistYear) MusicBy(ArtistName, ArtistYear) references Artist(ArtistName, ArtistYear) MajorArtist(ArtistName, ArtistYear) references Artist(ArtistName, ArtistYear) Write the following queries using relational algebra. 1. Find all albums with 20 or more tracks, return the title and the duration of the album. 2. Find all artists that are similar to the artist named ’Prince’ return the name and year founded of these artists. 3. Find all artists who have never contributed to a song (either with lyrics or music). Return the name of the artist. 4. Find all albums that feature a song by ’Prince’ (composed by or lyrics by). 5. Find artists who are considered major artists for all labels that they recorded with. Return name, origin and biography of the artist (Hint. Use Album and MajorArtist relations first). 6. Find all songs that have never been recorded in an album. Return the name and dateComposed for these songs. 7. Find all albums such that all tracks in that album are recommended. If a track is recommended, then the ”Track.Recommended” attribute has value ’y’. Return the title of the album, duration and its rating. 8. Find all artists that have never recorded a song composed by themselves (use MusicBy relation only). Return the name, year of the artist.

Answer.

14

1. Find all albums with 20 or more tracks, return the title and the duration of the album. R := ΠAlbumId (σT rackId=20 T rack) S := R[Id] Result := ΠT itle,Duration (Album ./AlbumId=Id S) 2. Find all artists that are similar to the artist named ’Prince’ return the name and year founded of these artists. R := σF romArtistN ame=0 P rince0 SimilarArtist Result := ΠT oArtistN ame,T oArtistY ear R 3. Find all artists who have never contributed to a song (either with lyrics or music). Return the name of the artist. R := ΠArtistN ame,ArtistY ear LyricsBy ∪ ΠArtistN ame,ArtistY ear M usicBy Result := ΠArtistN ame (ΠArtistN ame,ArtistY ear Artist − R) 4. Find all albums that feature a song by ’Prince’ (composed by or lyrics by). R := ((ΠSongId (σArtistN ame=0 P rince0 LyricsBy)) ∪ (ΠSongId (σArtistN ame=0 P rince0 M usicBy)) S := ΠAlbum (T rack ./SongId=SongId R) 5. Find artists who are considered major artists for all labels that they recorded with. Return name, origin and biography of the artist (Hint. Use Album and MajorArtist relations first). V := ΠArtistN ame,ArtistY ear,LabelN ame Album S := ΠArtistN ame,ArtistY ear Artist − ΠArtistN ame,ArtistY ear (V − M ajorArtist) T := Artist ./ArtistN ame=ArtistN ame AND ArtistY ear=ArtistY ear S Result := ΠArtistN ame,Origin,Biography (T ) 6. Find all songs that have never been recorded in an album. Return the name and dateComposed for these songs. T 1 := ΠSongId Song − ΠSongId T rack T 2 := ΠSongN ame,DateComposed (Song ./SongId=SongId T 1 7. Find all albums such that all tracks in that album are recommended. If a track is recommended, then the ”Track.Recommended” attribute has value ’y’. Return the title of the album, duration and its rating. T 1 := ΠAlbumId (ΠAlbumId,T rackId T rack − ΠAlbumId,T rackId (σrecommended=0 y0 T rack)) T 2 := ΠAlbumT itle,Duration,Rating (Album ./AlbumId=AlbumId (ΠAlbumId Album − T 1)) 8. Find all artists that have never recorded a song composed by themselves (use MusicBy relation only). Return the name, year of the artist. T 0 := M usicBy[SongId1, ArtistN ame1, ArtistY ear1] T 1 := (T 0 ./SongId1=SongId T rack) ./AlbumId=AlbumId Album T 2 := σArtistN ame1=ArtistN ame AND ArtistY ear1=ArtistY ear T 1 Result := ΠArtistN ame,ArtistY ear Artist − ΠArtistN ame,ArtistY ear T 2 T 2 is the set of artists who have recorded a song that they composed.

15

Question 11 Given: ITEMS(iid, oid, name, location) BIDS(bidid, iid, buyid, amount, date) BUYERS(buyid, name, email) OWNERS(oid, name, email, status) Write the following queries in relational algebra. 1. Find all owners who never received bids of $25 or more for one their items. Return the name and email of owners. 2. Find all buyers who placed bids for the same amount on two different items. Return the name of the buyer, the amount and the name of the two items.

Answer. 1. Find all owners who never received bids of $25 or more for one their items. Return the name and email of owners. T 1 := Πoid OW N ERS − (Πoid (IT EM S ./oid=oid (σamount≥25 BIDS))) T 2 := Πname,email (T 1 ./oid=oid OW N ERS) 2. Find all buyers who placed bids for the same amount on two different items. Return the name of the buyer, the amount and the name of the two items. T 0 := BIDS[bidid1, iid1, buyid1, amount1, date1] T 1 := BIDS ./buyid=buyid1 AND iidiid1 AND amount=amount1 BIDS T 2 := IT EM S[iid1, oid1, name1, location1] T 3 := IT EM S[iid2, oid2, name2, location2] T 4 := BU Y ERS ./buyid=buyid T 1 ./iid=iid1 T 2 ./iid1=iid2 T 3 Result := Πname,name1,name2 T 4

16

Question 12 Consider the relations below: Passengers (Name, Address, Age) Reservations(Name, FlightNum, Seat) Flights(FlightNum, DepartCity, DestinationCity, DepartureTime, ArrivalTime, MinutesLate) 1. Get the names of passengers who had a reservation on a flight that was more than 30 minutes late. 2. Get the names of passengers who had reservations on all flights that were more than 60 minutes late. 3. Get the names of pairs of passengers who are the same age.

Answer. 1. Get the names of passengers who had a reservation on a flight that was more than 30 minutes late. T emp1 := σM inutesLate>30 F lights T emp2 := Reservations ./F lightN um=F lightN um T emp1 RESU LT := ΠN ame T emp2 2. Get the names of passengers who had reservations on all flights that were more than 60 minutes late. T emp1 := σM inutesLate>60 F lights T emp2 := ΠF lightN um T emp1 T emp3 := ΠN ame,F lightN um Reservations RESU LT := T emp3/T emp2 3. Get the names of pairs of passengers who are the same age. T emp0 := P assenger[N ame1, Address1, Age1] T emp1 := P assenger × T emp0 T emp2 := σAge=Age1 AND N ameN ame1 T emp1 RESU LT := ΠN ame1,N ame2 T emp2

17

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF