unit ii – b. relational model -...
TRANSCRIPT
-
UNITII–B.RELATIONALMODEL
-
Agenda• StructureofRela9onalDatabases• Rela9onalAlgebra• ExtendedRela9onal-Algebra-Opera9ons• Modifica9onoftheDatabase• Views• TupleRela9onalCalculus• DomainRela9onalCalculus• Forma9onofQueries
-
Rela9onalModel• Rela9onalModelincludes:Rela%ons,Tuples,A/ributes,keysandforeign
keys.
— Rela/on:Atwodimensionaltablemakeupoftuples(Thisisasimpledefini9onthatwewilldefinemorerigorouslyinalaterchapter).
— Tuple:Arowofdatainarela9onmadeupofoneormoreaRributes.— A4ribute:Acharacteris9coftherela9oncontainedinatuple.
-
Rela9onalModel
-
ASampleRela9onalDatabase
-
BasicStructure• Formally,givensetsD1,D2,….Dn,arela/onrisasubsetof
D1xD2x…xDnThusarela9onisasetofn-tuples(a1,a2,…,an)whereeachai∈Di
• Example:if customer-name={Jones,Smith,Curry,Lindsay}
customer-street={Main,North,Park}customer-city={Harrison,Rye,PiRsfield}
Thenr={(Jones,Main,Harrison),(Smith,North,Rye),(Curry,North,Rye),(Lindsay,Park,PiRsfield)}isarela9onovercustomer-namexcustomer-streetxcustomer-city
-
ARributeTypes• EachaRributeofarela9onhasaname• Thesetofallowedvalues foreachaRribute is called thedomain of the
aRribute• ARributevaluesare(normally)requiredtobeatomic,thatis,indivisible
— E.g.mul9valuedaRributevaluesarenotatomic— E.g.compositeaRributevaluesarenotatomic
• Thespecialvaluenullisamemberofeverydomain• Thenullvaluecausescomplica9onsinthedefini9onofmanyopera9ons
— weshallignoretheeffectofnullvaluesinourmainpresenta9onandconsidertheireffectlater
-
Rela9onSchema• A1,A2,…,Anarea/ributes• R=(A1,A2,…,An)isarela%onschema
E.g.Customer-schema=(customer-name,customer-street,customer-city)
• r(R)isarela%onontherela%onschemaR E.g. customer(Customer-schema)
-
Rela9onInstance• Thecurrentvalues(rela%oninstance)ofarela9onarespecifiedbya
table• Anelementtofrisatuple,representedbyarowinatable
Jones Smith Curry
Lindsay
customer-name Main North North Park
customer-street Harrison
Rye Rye
Pittsfield
customer-city
customer
attributes (or columns)
tuples (or rows)
-
Keys• LetK⊆R• KisasuperkeyofRifvaluesforKaresufficienttoiden9fyauniquetuple
ofeachpossiblerela9onr(R)— by“possibler”wemeanarela9onrthatcouldexistintheenterprise
wearemodeling.— Example:{customer-name,customer-street}and
{customer-name}are both superkeys of Customer, if no two customers can possiblyhavethesamename.
• KisacandidatekeyifKisminimalExample: {customer-name} isacandidatekeyforCustomer,since it isasuperkey(assumingnotwocustomerscanpossiblyhavethesamename),andnosubsetofitisasuperkey.
-
DeterminingKeysfromE-RSets• Strongen/tyset.Theprimarykeyoftheen9tysetbecomestheprimary
keyoftherela9on.• Weaken/tyset. Theprimarykeyoftherela9onconsistsoftheunionof
theprimarykeyofthestrongen9tysetandthediscriminatoroftheweaken9tyset.
• Rela/onshipset. Theunionoftheprimarykeysoftherelated en9tysetsbecomesasuperkeyoftherela9on.— For binary many-to-one rela9onship sets, the primary key of the
“many”en9tysetbecomestherela9on’sprimarykey.— For one-to-one rela9onship sets, the rela9on’s primary key can be
thatofeitheren9tyset.— For many-to-many rela9onship sets, the union of the primary keys
becomestherela9on’sprimarykey
-
E-RDiagramfortheBankingEnterprise
-
SchemaDiagramfortheBankingEnterprise
-
Example• Design a rela9onal database corresponding to the E-R diagram given
below.
• Sol.Therela9onaldatabaseschemaisgivenbelow.— person(driver-id,name,address)— car(license,year,model)— accident(report-number,loca9on,date)— owns(driver-id,license)— par9cipated(report-number,driver-id,license,damage-amount)
-
QueryLanguages• Languageinwhichuserrequestsinforma9onfromthedatabase.• Categoriesoflanguages
— procedural— non-procedural
• “Pure”languages:— Rela9onalAlgebra— TupleRela9onalCalculus— DomainRela9onalCalculus
• Purelanguagesformunderlyingbasisofquerylanguagesthatpeopleuse.
-
Rela9onalAlgebra• Procedurallanguage• Sixbasicoperators
— select— project— Union— Intersec9on— setdifference— Cartesianproduct— rename
• The operators take one or more rela9ons as inputs and give a newrela9onasaresult.
-
SelectOpera9on
• Nota9on:σp(r)• piscalledtheselec9onpredicate• Definedas:
σp(r)={t|t∈randp(t)} Where p is a formula in proposi9onal calculus consis9ng of termsconnectedby:∧(and),∨(or),¬(not)Eachtermisoneof: op or
whereopisoneof:=,≠,>,≥.
-
SelectOpera9on–Example1
-
SelectOpera9on–Example2&3• SelectElectricalEngineersfromEmployeeRela9on.• Sol.
• SelectElectricalormechanicalengineersfromEmployeeRela9on.• Sol.
ENO ENAME TITLE
E1 J. Doe Elect. Eng E6 L. Chu Elect. Eng.
σ TITLE='Elect. Eng.'(EMP) ENO ENAME TITLE E1 J. Doe Elect. Eng. E2 M. Smith Syst. Anal. E3 A. Lee Mech. Eng. E4 J. Miller Programmer E5 B. Casey Syst. Anal. E6 L. Chu Elect. Eng. E7 R. Davis Mech. Eng. E8 J. Jones Syst. Anal.
EMP
σ TITLE='Elect. Eng.’ ∨ TITLE=‘Mech.Eng’(EMP)
-
SelectOpera9on–Example4• Findtheprojectswithbudgetlessthanequalto$200,000&greaterthan
$200,000 from the rela9on PROJ using select opera9on. Define therela9onsPROJ1&PROJ2basedonBudget.
• Sol: PROJ1=σBUDGET200000(PROJ)
PROJ1
PNO PNAME LOC
P1 Instrumentation 150000 Montreal
P2 Database Develop. 135000 New York
BUDGET PNO PNAME BUDGET LOC
P3 CAD/CAM 250000 New York
P4 Maintenance 310000 Paris
P5 CAD/CAM 500000 Boston
PROJ2
New York New York
PROJ
PNO PNAME BUDGET LOC
P1 Instrumentation 150000 Montreal
P3 CAD/CAM 250000 P2 Database Develop. 135000
P4 Maintenance 310000 Paris P5 CAD/CAM 500000 Boston
-
SelectOpera9on–Example5• If a new tuplewith a BUDGET value of, $600,000 is to be inserted into
PROJ of previous example. Define the rela9ons PROJ1, PROJ2 & PROJ3basedonBudget.
• Sol: PROJ1=σBUDGET
-
SelectOpera9on–Example6• Consider the rela9on PROJ. Using select opera9on define the rela9ons
PROJ1,PROJ2&PROJ3basedonLoca9on.
• Sol: PROJ1=σLOC=“Montreal”(PROJ) PROJ2=σLOC=“NewYork”(PROJ) PROJ3=σLOC=“Paris”(PROJ)
New York New York
PROJ
PNO PNAME BUDGET LOC
P1 Instrumentation 150000 Montreal
P3 CAD/CAM 250000 P2 Database Develop. 135000
P4 Maintenance 310000 Paris
-
SelectOpera9on–Example6contd.
PROJ1
PNO PNAME BUDGET LOC PNO PNAME BUDGET LOC
P1 Instrumentation 150000 Montreal P2 Database Develop. 135000 New York
PROJ2
CAD/CAM 250000 New York
PNO PNAME BUDGET LOC
Maintenance P4 310000 Paris
P3
PROJ3
-
CompanyDatabaseSchema
P.Query2
P.Query3
U.Query3
-
SelectOpera9on–Example7&8• Select the EMPLOYEE tuples whose department number is four. Sol. σDNO = 4 (EMPLOYEE)
• Select the EMPLOYEE tuples whose salary is greater than $30,000. Sol. σSALARY > 30,000 (EMPLOYEE)
-
SelectOpera9on–Example9• Select the EMPLOYEE tuples whose department number is four and
whose salary is greater than $25,000 or those employees whose department number is five and whose salary is greater than $30,000.
• Sol.
-
ProjectOpera9on
• Nota9on:∏A1,A2,…,Ak(r)
whereA1,A2areaRributenamesandrisarela9onname.• Theresultisdefinedastherela9onofkcolumnsobtainedbyerasingthe
columnsthatarenotlisted• Duplicaterowsremovedfromresult,sincerela9onsaresets• E.g.Toeliminatethebranch-nameaRributeofaccount
∏account-number,balance(account)
-
ProjectOpera9on–Example1
-
ProjectOpera9on–Example2• List each employee’s first and last name and salary from Employee
Rela9on.
Sol. πLNAME,FNAME,SALARY(EMPLOYEE)Companydatabaseschema
-
ProjectOpera9on–Example3• List each employee’s sex and salary fromEmployeeRela9on.
Sol. πSEX,SALARY(EMPLOYEE) Companydatabaseschema
-
ProjectExample4• SelectPNO&BUDGETfromtherela9onPROJ.
• Sol:π PNO,BUDGET(PROJ)
PNO BUDGET
P1 150000 P2 135000 P3 250000 P4 310000 P5 500000
PROJ
PNO BUDGET
P2 135000
P3 250000 P4 310000 P5 500000
PNAME
P1 150000 Instrumentation Database Develop.
CAD/CAM Maintenance CAD/CAM
-
Selec9onwithProjec9onExample• List each employee’s first and last name and salary from Employee
Rela9onwhoseDNOis5fromtheemployeerela9on.
• Sol.
-
UnionOpera9on
• Nota9on:r∪s• Definedas:
r∪s={t|t∈rort∈s}• Forr∪stobevalid.
1.r,smusthavethesamearity(samenumberofaRributes)2.TheaRributedomainsmustbecompa%ble(e.g.,2ndcolumnofrdealswiththesametypeofvaluesasdoesthe2ndcolumnofs)
• E.g.tofindallcustomerswitheitheranaccountoraloan∏customer-name(depositor)∪∏customer-name(borrower)
-
UnionOpera9on–Example1
-
UnionOpera9on:Example2• FindSTUDENT∪ ΙΝSTRUCTOR.
• Sol:
-
UnionOpera9on:Example3• Toretrievethesocialsecuritynumbersofallemployeeswhoeitherwork
in department 5 or directly supervise an employee who works indepartment5,usetheunionopera9on.
Sol. DEP5_EMPS←σDNO=5(EMPLOYEE) RESULT1←πSSN(DEP5_EMPS) RESULT2(SSN)←πSUPERSSN(DEP5_EMPS) RESULT←RESULT1∪RESULT2
-
Intersec9onOpera9on
-
Intersec9onOpera9on:Example1• FindSTUDENT∩ ΙΝSTRUCTOR.
• Sol:
-
SetDifferenceOpera9on
• Nota9onr–s• Definedas:
r–s={t|t∈randt∉s}• Setdifferencesmustbetakenbetweencompa%blerela9ons.
— randsmusthavethesamearity— aRributedomainsofrandsmustbecompa9ble
-
SetDifferenceOpera9on–Example1
-
SetDifferenceOpera9on–Example2• Find(a)STUDENT ΙΝSTRUCTOR
(b)INSTRUCTOR–STUDENT
• Sol:(a) (b)
-
Cartesian-ProductOpera9on• Nota9onrxs• Definedas:
rxs={tq|t∈randq∈s}• AssumethataRributesofr(R)ands(S)aredisjoint.(Thatis,
R∩S=∅).• IfaRributesofr(R)ands(S)arenotdisjoint,thenrenamingmustbeused.
-
Cartesian-ProductOpera9on-Example
-
Composi9onofOpera9ons• Canbuildexpressionsusingmul9pleopera9ons• Example:σA=C(rxs)
-
RenameOpera9on• Allows us to name, and therefore to refer to, the results of rela9onal-
algebraexpressions.• Allowsustorefertoarela9onbymorethanonename.Example:
ρx(E)returnstheexpressionEunderthenameXIfarela9onal-algebraexpressionEhasarityn,then
ρx(A1,A2,…,An)(E)returnstheresultofexpressionEunderthenameX,andwiththeaRributesrenamedtoA1,A2,….,An.
-
Example1:Queries• Consider the rela9onal database givenbelowwhere theprimary keys are
underlined.Giveanexpressionintherela9onalalgebratoexpresseachofthefollowingqueries:
a.FindthenamesofallemployeeswhoworkforFirstBankCorpora9on.Sol.Πperson-name(σcompany-name= FirstBankCorpora9on (works))b.Findthenamesandci9esofresidenceofallemployeeswhoworkforFirst
BankCorpora9on.Sol.
employee(person-name,street,city)works(person-name,company-name,salary)company(company-name,city)manages(person-name,manager-name)
-
Example1:Queriescontd.c. Find the names, street address, and ci9es of residence of all employeeswho work for First Bank Corpora9on and earn more than $10,000 perannum.Sol.d.Findthenamesofallemployeesinthisdatabasewholiveinthesamecityasthecompanyforwhichtheywork.Sol.
-
Example2:BankingQueries
branch(branch-name,branch-city,assets)customer(customer-name,customer-street,customer-only)account(account-number,branch-name,balance)loan(loan-number,branch-name,amount)depositor(customer-name,account-number)borrower(customer-name,loan-number)
-
ExampleQueries• Selectallloansofover$1200
• Find the loan number for each loan of an amount greater than $1200
-
ExampleQueries• Find thenamesof all customerswhohave a loan, an account, or both,
fromthebank
• Find the names of all customers who have a loan and an account at bank.
-
ExampleQueries• Find the names of all customers who have a loan at the Perryridge
branch.
• Find the names of all customers who have a loan at the Perryridge branch but do not have an account at any branch of the bank.
-
ExampleQueries• FindthenamesofallcustomerswhohavealoanatthePerryridgebranch.
- Query 2 ∏customer-name(σloan.loan-number = borrower.loan-number( (σbranch-name = “Perryridge”(loan)) x borrower))
Query 1 ∏customer-name(σbranch-name = “Perryridge” ( σborrower.loan-number = loan.loan-number(borrower x loan)))
-
ExampleQueriesFindthelargestaccountbalance• Renameaccountrela9onasd• Thequeryis:
∏balance(account) - ∏account.balance (σaccount.balance < d.balance (account x ρd (account)))
-
Summary:Rela9onAlgebra• Abasicexpression in therela9onalalgebraconsistsofeitheroneof the
following:— Arela9oninthedatabase— Aconstantrela9on
• Let E1 and E2 be rela9onal-algebra expressions; the following are allrela9onal-algebraexpressions:— E1∪E2— E1-E2— E1xE2— σp(E1),PisapredicateonaRributesinE1— ∏s(E1),Sisalistconsis9ngofsomeoftheaRributesinE1— ρx(E1),xisthenewnamefortheresultofE1
-
Addi9onalopera9onsWedefineaddi9onalopera9onsthatdonotaddanypowertotherela9onalalgebra,butthatsimplifycommonqueries.• Naturaljoin• Division• Assignment
-
■ Notation: r s
Natural-JoinOpera9on
• Letrandsberela9onsonschemasRandSrespec9vely.Then,rsisarela9ononschemaR∪Sobtainedasfollows:— Considereachpairoftuplestrfromrandtsfroms.— IftrandtshavethesamevalueoneachoftheaRributesinR∩S,add
atuplettotheresult,where– thasthesamevalueastronr– thasthesamevalueastsons
-
NaturalJoinOpera9on–Example1• Example1:
R=(A,B,C,D)S=(E,B,D)— Resultschema=(A,B,C,D,E)— rsisdefinedas:
∏r.A,r.B,r.C,r.D,s.E(σr.B=s.B∧r.D=s.D(rxs))
-
NaturalJoinOpera9on–Example1contd..
-
NaturalJoinOpera9on–Example2
-
NaturalJoinOpera9on–Example3
-
NaturalJoinOpera9on–Example4
-
NaturalJoinOpera9on–Example5
• Cartesianproductofr1&r2.
-
NaturalJoins:Canbeincomplete–Example6
-
NaturalJoins:CanbeNull–Example7
-
DivisionOpera9on
• Suitedtoqueriesthatincludethephrase“forall”.• Letrandsberela9onsonschemasRandSrespec9velywhere
— R=(A1,…,Am,B1,…,Bn)— S=(B1,…,Bn)Theresultofr÷sisarela9ononschemaR–S=(A1,…,Am) r÷s={t|t∈∏R-S(r)∧∀u∈s(tu∈r)}
r ÷ s
-
DivisionOpera9on
-
AssignmentOpera9on• The assignment opera9on (←) provides a convenientway to express
complexqueries.— Writequeryasasequen9alprogramconsis9ngof
– aseriesofassignments– followedbyanexpressionwhosevalue isdisplayedasaresultof the
query.— Assignmentmustalwaysbemadetoatemporaryrela9onvariable.
— Theresulttotherightofthe←isassignedtotherela9onvariableontheleyofthe←.
— Mayusevariableinsubsequentexpressions.
-
ExampleQueries• Findallcustomerswhohaveanaccountfromatleastthe“Downtown”
andtheUptown”branches.
where CN denotes customer-name and BN denotes branch-name.
Query 1 ∏CN(σBN=“Downtown”(depositor account)) ∩ ∏CN(σBN=“Uptown”(depositor account))
Query 2 ∏customer-name, branch-name (depositor account) ÷ ρtemp(branch-name) ({(“Downtown”),
(“Uptown”)})
-
• Find all customers who have an account at all branches located inBrooklyncity.
ExampleQueries
∏customer-name, branch-name (depositor account) ÷ ∏branch-name (σbranch-city = “Brooklyn” (branch))
-
ExtendedRela9onal-Algebra-Opera9ons• GeneralizedProjec9on• OuterJoin• AggregateFunc9ons
-
GeneralizedProjec9on• Extendstheprojec9onopera9onbyallowingarithme9cfunc9onstobe
usedintheprojec9onlist.
∏F1,F2,…,Fn(E)• Eisanyrela9onal-algebraexpression• EachofF1,F2,…,Fn are arithme9c expressions involving constants and
aRributesintheschemaofE.• Givenrela9oncredit-info(customer-name,limit,credit-balance),findhow
muchmoreeachpersoncanspend: ∏customer-name,limit–credit-balance(credit-info)
-
AggregateFunc9onsandOpera9ons• Aggrega/on func/on takes a collec9on of values and returns a single
valueasaresult. avg:averagevalue
min:minimumvaluemax:maximumvaluesum:sumofvaluescount:numberofvalues
• Aggregateopera/oninrela9onalalgebra
G1,G2,…,GngF1(A1),F2(A2),…,Fn(An)(E)— Eisanyrela9onal-algebraexpression— G1,G2…,GnisalistofaRributesonwhichtogroup(canbeempty)— EachFiisanaggregatefunc9on— EachAiisanaRributename
-
AggregateOpera9on–Example• Rela9onr:
A B α α β β
α β β β
C 7 7 3 10
g sum(c) (r) sum-C
27
-
AggregateOpera9on–Example
• Rela9onaccountgroupedbybranch-name:
branch-name g sum(balance) (account)
branch-name account-number balance Perryridge Perryridge Brighton Brighton Redwood
A-102 A-201 A-217 A-215 A-222
400 900 750 750 700
branch-name balance Perryridge Brighton Redwood
1300 1500 700
-
AggregateFunc9ons(Cont.)• Resultofaggrega9ondoesnothaveaname
— Canuserenameopera9ontogiveitaname— Forconvenience,wepermitrenamingaspartofaggregateopera9on
branch-name g sum(balance) as sum-balance (account)
-
OuterJoin• Anextensionofthejoinopera9onthatavoidslossofinforma9on.• Computes the join and then adds tuples form one rela9on that do not
matchtuplesintheotherrela9ontotheresultofthejoin.• Usesnullvalues:
— nullsignifiesthatthevalueisunknownordoesnotexist— All comparisons involving null are (roughly speaking) false by
defini9on.– Willstudyprecisemeaningofcomparisonswithnullslater
-
OuterJoin–Example• Rela9onloan
■ Relation borrower
customer-name loan-number Jones Smith Hayes
L-170 L-230 L-155
3000 4000 1700
loan-number amount L-170 L-230 L-260
branch-name Downtown Redwood Perryridge
-
OuterJoin–Example• InnerJoin
loanBorrower
loan-number amount L-170 L-230
3000 4000
customer-name Jones Smith
branch-name Downtown Redwood
Jones Smith null
loan-number amount L-170 L-230 L-260
3000 4000 1700
customer-name branch-name Downtown Redwood Perryridge
■ Left Outer Join loan Borrower
-
OuterJoin–Example• RightOuterJoinloanborrower
loan borrower ■ Full Outer Join
loan-number amount L-170 L-230 L-155
3000 4000 null
customer-name Jones Smith Hayes
branch-name Downtown Redwood null
loan-number amount L-170 L-230 L-260 L-155
3000 4000 1700 null
customer-name Jones Smith null Hayes
branch-name Downtown Redwood Perryridge null
-
NullValues• Itispossiblefortuplestohaveanullvalue,denotedbynull,forsomeof
theiraRributes• nullsignifiesanunknownvalueorthatavaluedoesnotexist.• Theresultofanyarithme9cexpressioninvolvingnullisnull.• Aggregatefunc9onssimplyignorenullvalues
— Isanarbitrarydecision.Couldhavereturnednullasresultinstead.— Wefollowtheseman9csofSQLinitshandlingofnullvalues
• For duplicate elimina9on and grouping, null is treated like any othervalue,andtwonullsareassumedtobethesame— Alterna9ve:assumeeachnullisdifferentfromeachother— Botharearbitrarydecisions,sowesimplyfollowSQL
-
NullValues• Comparisonswithnullvaluesreturnthespecialtruthvalueunknown
— Iffalsewasusedinsteadofunknown,thennot(A<5)wouldnotbeequivalenttoA>=5
• Three-valuedlogicusingthetruthvalueunknown:— OR:(unknownortrue)=true,
(unknownorfalse)=unknown(unknownorunknown)=unknown
— AND:(trueandunknown)=unknown,(falseandunknown)=false,(unknownandunknown)=unknown
— NOT:(notunknown)=unknown— InSQL“P isunknown”evaluatestotrue ifpredicatePevaluates
tounknown• Resultofselectpredicateistreatedasfalseifitevaluatestounknown
-
Modifica9onoftheDatabase• The content of the database may be modified using the following
opera9ons:— Dele9on— Inser9on— Upda9ng
• Alltheseopera9onsareexpressedusingtheassignmentoperator.
-
Dele9on• A delete request is expressed similarly to a query, except instead of
displaying tuples to theuser, the selected tuplesare removed from thedatabase.
• Can delete only whole tuples; cannot delete values on only par9cularaRributes
• Adele9onisexpressedinrela9onalalgebraby: r←r–Ewhererisarela9onandEisarela9onalalgebraquery.
-
Dele9onExamples• DeleteallaccountrecordsinthePerryridgebranch.
■ Delete all accounts at branches located in Needham. r1 ← σ branch-city = “Needham” (account branch) r2 ← ∏branch-name, account-number, balance (r1) r3 ← ∏ customer-name, account-number (r2 depositor) account ← account – r2 depositor ← depositor – r3
■ Delete all loan records with amount in the range of 0 to 50
loan ← loan – σ amount ≥ 0 and amount ≤ 50 (loan)
account ← account – σ branch-name = “Perryridge” (account)
-
Inser9on• Toinsertdataintoarela9on,weeither:
— specifyatupletobeinserted— writeaquerywhoseresultisasetoftuplestobeinserted
• inrela9onalalgebra,aninser9onisexpressedby: r←r∪Ewhererisarela9onandEisarela9onalalgebraexpression.
• The inser9on of a single tuple is expressed by le{ng E be a constantrela9oncontainingonetuple.
-
Inser9onExamples• Insert informa9oninthedatabasespecifyingthatSmithhas$1200in
accountA-973atthePerryridgebranch.
■ Provide as a gift for all loan customers in the Perryridge branch, a $200 savings account. Let the loan number serve as the account number for the new savings account.
account ← account ∪ {(“Perryridge”, A-973, 1200)} depositor ← depositor ∪ {(“Smith”, A-973)}
r1 ← (σbranch-name = “Perryridge” (borrower loan)) account ← account ∪ ∏branch-name, account-number,200 (r1) depositor ← depositor ∪ ∏customer-name, loan-number(r1)
-
Upda9ng• Amechanismtochangeavalue inatuplewithoutchargingallvalues in
thetuple• Usethegeneralizedprojec9onoperatortodothistask
r←∏F1,F2,…,FI,(r)• EachFiiseither
— theithaRributeofr,iftheithaRributeisnotupdated,or,— if the aRribute is to be updated Fi is an expression, involving only
constantsand theaRributesof r,whichgives thenewvalue for theaRribute
-
UpdateExamples• Makeinterestpaymentsbyincreasingallbalancesby5percent.
■ Pay all accounts with balances over $10,000 6 percent interest and pay all others 5 percent
account ← ∏ AN, BN, BAL * 1.06 (σ BAL > 10000 (account)) ∪ ∏AN, BN, BAL * 1.05 (σBAL ≤ 10000 (account))
account ← ∏ AN, BN, BAL * 1.05 (account)
where AN, BN and BAL stand for account-number, branch-name and balance, respectively.
-
Views• Insomecases, it isnotdesirableforalluserstoseetheen9relogical
model(i.e.,alltheactualrela9onsstoredinthedatabase.)• Considerapersonwhoneedstoknowacustomer’sloannumberbut
hasnoneedtoseetheloanamount.Thispersonshouldseearela9ondescribed,intherela9onalalgebra,by ∏customer-name,loan-number(borrowerloan)
• Anyrela9onthatisnotoftheconceptualmodelbutismadevisibletoauserasa“virtualrela9on”iscalledaview.
-
ViewDefini9on• Aviewisdefinedusingthecreateviewstatementwhichhastheform
createviewvas where is any legal rela9onal algebra queryexpression.Theviewnameisrepresentedbyv.
• Onceaviewisdefined,theviewnamecanbeusedtorefertothevirtualrela9onthattheviewgenerates.
• Viewdefini9on isnot thesameascrea9nganewrela9onbyevalua9ngthequeryexpression— Rather, a view defini9on causes the saving of an expression; the
expressionissubs9tutedintoqueriesusingtheview.
-
ViewExamples• Consider the view (named all-customer) consis9ng of branches and
theircustomers.
■ We can find all customers of the Perryridge branch by writing:
create view all-customer as ∏branch-name, customer-name (depositor account) ∪ ∏branch-name, customer-name (borrower loan)
∏customer-name (σbranch-name = “Perryridge” (all-customer))
-
UpdatesThroughView• Database modifica9ons expressed as views must be translated to
modifica9onsoftheactualrela9onsinthedatabase.• Consider thepersonwhoneeds to seeall loandata in the loan rela9on
exceptamount.Theviewgiventotheperson,branch-loan,isdefinedas: createviewbranch-loanas ∏branch-name,loan-number(loan)
• Since we allow a view name to appear wherever a rela9on name isallowed,thepersonmaywrite:
branch-loan←branch-loan∪{(“Perryridge”,L-37)}
-
UpdatesThroughViews(Cont.)• The previous inser9on must be represented by an inser9on into the
actualrela9onloanfromwhichtheviewbranch-loanisconstructed.• Aninser9oninto loanrequiresavalueforamount.Theinser9oncanbe
dealtwithbyeither.— rejec9ngtheinser9onandreturninganerrormessagetotheuser.— inser9ngatuple(“L-37”,“Perryridge”,null)intotheloanrela9on
• Someupdates through views are impossible to translate into databaserela9onupdates— createviewvasσbranch-name=“Perryridge”(account))v←v∪(L-99,Downtown,23)
• Otherscannotbetranslateduniquely— all-customer←all-customer∪{(“Perryridge”,“John”)}
– Havetochooseloanoraccount,andcreateanewloan/accountnumber!
-
ViewsDefinedUsingOtherViews• Oneviewmaybeusedintheexpressiondefininganotherview• Aviewrela9onv1 issaidtodependdirectlyonaviewrela9onv2 ifv2 is
usedintheexpressiondefiningv1• Aviewrela9onv1issaidtodependonviewrela9onv2ifeitherv1depends
directlytov2orthereisapathofdependenciesfromv1tov2• Aviewrela9onvissaidtoberecursiveifitdependsonitself.
-
ViewExpansion• Awaytodefinethemeaningofviewsdefinedintermsofotherviews.• Letviewv1bedefinedbyanexpressione1thatmayitselfcontainusesof
viewrela9ons.• Viewexpansionofanexpressionrepeatsthefollowingreplacementstep:
repeat Findanyviewrela9onviine1 Replacetheviewrela9onvibytheexpressiondefiningviun/lnomoreviewrela9onsarepresentine1
• Aslongastheviewdefini9onsarenotrecursive,thisloopwillterminate
-
TupleRela9onalCalculus• Anonproceduralquerylanguage,whereeachqueryisoftheform
{t|P(t)}• ItisthesetofalltuplestsuchthatpredicatePistruefort• tisatuplevariable,t[A]denotesthevalueoftupletonaRributeA• t∈rdenotesthattupletisinrela9onr• Pisaformulasimilartothatofthepredicatecalculus
-
PredicateCalculusFormula1. SetofaRributesandconstants2. Setofcomparisonoperators:(e.g.,,≥)3. Setofconnec9ves:and(∧),or(v)‚not(¬)4. Implica9on(⇒):x⇒y,ifxistrue,thenyistrue
x⇒y≡ ¬xvy5. Setofquan9fiers:
∃ t∈ r(Q(t))≡ ”thereexists”atupleintinrela9onrsuchthatpredicateQ(t)istrue
∀t∈ r(Q(t))≡ Qistrue“forall”tuplestinrela9onr
-
BankingExample• branch(branch-name,branch-city,assets)• customer(customer-name,customer-street,customer-city)• account(account-number,branch-name,balance)• loan(loan-number,branch-name,amount)• depositor(customer-name,account-number)• borrower(customer-name,loan-number)
-
ExampleQueries• Findtheloan-number,branch-name,and amountforloansofover
$1200
■ Find the loan number for each loan of an amount greater than $1200
Notice that a relation on schema [loan-number] is implicitly defined by the query
{t | ∃ s ∈ loan (t[loan-number] = s[loan-number] ∧ s [amount] > 1200)}
{t | t ∈ loan ∧ t [amount] > 1200}
-
ExampleQueries• Findthenamesofallcustomershavingaloan,anaccount,orbothat
thebank
{t | ∃s ∈ borrower( t[customer-name] = s[customer-name]) ∧ ∃u ∈ depositor( t[customer-name] = u[customer-name])
■ Find the names of all customers who have a loan and an account at the bank
{t | ∃s ∈ borrower( t[customer-name] = s[customer-name]) ∨ ∃u ∈ depositor( t[customer-name] = u[customer-name])
-
ExampleQueries• FindthenamesofallcustomershavingaloanatthePerryridgebranch
{t | ∃s ∈ borrower( t[customer-name] = s[customer-name] ∧ ∃u ∈ loan(u[branch-name] = “Perryridge” ∧ u[loan-number] = s[loan-number])) ∧ not ∃v ∈ depositor (v[customer-name] = t[customer-name]) }
■ Find the names of all customers who have a loan at the Perryridge branch, but no account at any branch of the bank
{t | ∃s ∈ borrower(t[customer-name] = s[customer-name] ∧ ∃u ∈ loan(u[branch-name] = “Perryridge” ∧ u[loan-number] = s[loan-number]))}
-
ExampleQueries• Find the names of all customers having a loan from the Perryridge
branch,andtheci9estheylivein
{t | ∃s ∈ loan(s[branch-name] = “Perryridge” ∧ ∃u ∈ borrower (u[loan-number] = s[loan-number]
∧ t [customer-name] = u[customer-name]) ∧ ∃ v ∈ customer (u[customer-name] = v[customer-name]
∧ t[customer-city] = v[customer-city])))}
-
ExampleQueries• Findthenamesofallcustomerswhohaveanaccountatallbranches
locatedinBrooklyn:
{t | ∃ c ∈ customer (t[customer.name] = c[customer-name]) ∧ ∀ s ∈ branch(s[branch-city] = “Brooklyn” ⇒
∃ u ∈ account ( s[branch-name] = u[branch-name] ∧ ∃ s ∈ depositor ( t[customer-name] = s[customer-name] ∧ s[account-number] = u[account-number] )) )}
-
SafetyofExpressions• It is possible to write tuple calculus expressions that generate infinite
rela9ons.• Forexample,{t|¬t ∈r}results inaninfiniterela9onifthedomainof
anyaRributeofrela9onrisinfinite• Toguardagainsttheproblem,werestrictthesetofallowableexpressions
tosafeexpressions.• An expression {t | P(t)} in the tuple rela9onal calculus is safe if every
componentoftappearsinoneoftherela9ons,tuples,orconstantsthatappearinP— NOTE:thisismorethanjustasyntaxcondi9on.
– E.g.{t|t[A]=5∨true}isnotsafe---itdefinesaninfinitesetwithaRribute values that do not appear in any rela9on or tuples orconstantsinP.
-
DomainRela9onalCalculus• A nonprocedural query language equivalent in power to the tuple
rela9onalcalculus• Eachqueryisanexpressionoftheform:
{<x1,x2,…,xn>|P(x1,x2,…,xn)}— x1,x2,…,xnrepresentdomainvariables— Prepresentsaformulasimilartothatofthepredicatecalculus
-
ExampleQueries• Find the loan-number, branch-name, and amount for loans of over
$1200
{< c, a > | ∃ l (< c, l > ∈ borrower ∧ ∃b(< l, b, a > ∈ loan ∧ b = “Perryridge”))} or {< c, a > | ∃ l (< c, l > ∈ borrower ∧ < l, “Perryridge”, a > ∈ loan)}
■ Find the names of all customers who have a loan from the Perryridge branch and the loan amount:
{< c > | ∃ l, b, a (< c, l > ∈ borrower ∧ < l, b, a > ∈ loan ∧ a > 1200)}
■ Find the names of all customers who have a loan of over $1200
{< l, b, a > | < l, b, a > ∈ loan ∧ a > 1200}
-
ExampleQueries• Findthenamesofallcustomershavingaloan,anaccount,orbothat
thePerryridgebranch:
{< c > | ∃ s, n (< c, s, n > ∈ customer) ∧ ∀ x,y,z(< x, y, z > ∈ branch ∧ y = “Brooklyn”) ⇒ ∃ a,b(< x, y, z > ∈ account ∧ < c,a > ∈ depositor)}
■ Find the names of all customers who have an account at all branches located in Brooklyn:
{< c > | ∃ l ({< c, l > ∈ borrower ∧ ∃ b,a(< l, b, a > ∈ loan ∧ b = “Perryridge”)) ∨ ∃ a(< c, a > ∈ depositor ∧ ∃ b,n(< a, b, n > ∈ account ∧ b = “Perryridge”))}
-
SafetyofExpressions {<x1,x2,…,xn>|P(x1,x2,…,xn)}
issafeifallofthefollowinghold: 1. All values that appear in tuples of the expression are values from dom(P) (that is, the values appear either in P or in a tupleofarela9onmen9onedinP).
2. For every “there exists” subformula of the form ∃ x (P1(x)), the subformula is true if and only if there is a value of x in dom(P1)suchthatP1(x)istrue.
3. For every “for all” subformula of the form ∀x (P1 (x)), the subformula is true if and only ifP1(x) is true for all values x fromdom(P1).
-
EndofChapter3
-
Result of σ branch-name = “Perryridge” (loan)
-
Loan Number and the Amount of the Loan
-
Names of All Customers Who Have Either a Loan or an Account
-
Customers With An Account But No Loan
-
Result of borrower × loan
-
Result of σ branch-name = “Perryridge” (borrower × loan)
-
Result of Πcustomer-name
-
Result of the Subexpression
-
Largest Account Balance in the Bank
-
Customers Who Live on the Same Street and In the Same City as Smith
-
Customers With Both an Account and a Loan at the Bank
-
Result of Πcustomer-name, loan-number, amount (borrower loan)
-
Result of Πbranch-name(σcustomer-city = “Harrison”(customer account depositor))
-
Result of Πbranch-name(σbranch-city = “Brooklyn”(branch))
-
Result of Πcustomer-name, branch-name(depositor account)
-
The credit-info Relation
-
Result of Πcustomer-name, (limit – credit-balance) as credit-available(credit-info).
-
The pt-works Relation
-
The pt-works Relation After Grouping
-
Result of branch-name ς sum(salary) (pt-works)
-
Result of branch-name ς sum salary, max(salary) as max-salary (pt-works)
-
The employee and ft-works Relations
-
The Result of employee ft-works
-
The Result of employee ft-works
-
Result of employee ft-works
-
Result of employee ft-works
-
Tuples Inserted Into loan and borrower
-
Names of All Customers Who Have a Loan at the Perryridge Branch
-
E-R Diagram
-
The branch Relation
-
The loan Relation
-
The borrower Relation