Algebra relacional

326 views

Published on

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
326
On SlideShare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
Downloads
39
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Algebra relacional

  1. 1. 1Relational AlgebraRelational Algebra
  2. 2. 2database Modulesdatabase ModulesModule 1: Database SystemsModule 1: Database SystemsModule 2: Relational ModelModule 2: Relational ModelModule 3: Entity Relationship ModelModule 3: Entity Relationship ModelModule 4: ER to Relational MappingModule 4: ER to Relational MappingModule 5: FDs and NormalizationModule 5: FDs and NormalizationModule 6: Relational AlgebraModule 6: Relational AlgebraModule 7: SQLModule 7: SQLModule 8: Database SystemsModule 8: Database SystemsArchitectureArchitectureFundamentalFundamentalss√√DataDataModelingModeling√√DataDataDesignDesign√√DataDataAccessAccessArchitectureArchitecture
  3. 3. 3MotivationMotivationThe relational data modelThe relational data modelprovides a means ofprovides a means ofdefining the databasedefining the databasestructure and constraintsstructure and constraintsA data model must alsoA data model must alsoprovide a set ofprovide a set ofoperations to manipulateoperations to manipulatethe datathe dataNAME SALARY ADDRESS DEPTSmith 50k St. Lucia PrintingDilbert 40k Taringa PrintingJones 60k Kenmore PrintingTrump 65k Auchenflower Head OfficeHarrison 78k St. Lucia Head OfficeFind the names and departments of allFind the names and departments of allemployees who earn more than 55Kemployees who earn more than 55KIncrement the salary of all employeesIncrement the salary of all employeesin the printing department by 10%in the printing department by 10%What is the address of employeeWhat is the address of employeeJonesJonesThe basic set of relational model operationsThe basic set of relational model operationsconstitute the Relational Algebraconstitute the Relational Algebra
  4. 4. 4ContentsContentsRelational AlgebraRelational Algebra• What is a Relational QueryWhat is a Relational Query• Relational Query LanguagesRelational Query Languages• Relational Algebra OperationsRelational Algebra Operations• Query Formulation in Relational AlgebraQuery Formulation in Relational Algebra• Exercises in Relational AlgebraExercises in Relational Algebra
  5. 5. 5What is a Relational QueryWhat is a Relational Query• Data in a relational database can beData in a relational database can bemanipulated in the following ways:manipulated in the following ways:–– INSERTINSERT : New tuples may be inserted: New tuples may be inserted–– DELETEDELETE : Existing tuples may be deleted: Existing tuples may be deleted–– UPDATEUPDATE : Values of attributes in existing: Values of attributes in existingtuplestuplesmay be changedmay be changed–– RETRIEVERETRIEVE: Attributes of specific tuples,: Attributes of specific tuples,entireentiretuples, or even entire relations may betuples, or even entire relations may beretrievedretrieved• Relational Query Languages should provide allRelational Query Languages should provide allof the aboveof the above
  6. 6. 6Relational Query LanguagesRelational Query LanguagesRelational Queries are formulated in RelationalRelational Queries are formulated in RelationalQuery LanguagesQuery Languages• Relational Algebra (RA)Relational Algebra (RA)–– Formal query language for a relational databaseFormal query language for a relational database• Structured Query Language (SQL)Structured Query Language (SQL)–– Comprehensive, commercial query language withComprehensive, commercial query language withwidely accepted international standardwidely accepted international standard• Query by Example (QBE)Query by Example (QBE)–– Commercial, graphical query language withCommercial, graphical query language withminimum syntaxminimum syntax
  7. 7. 7SQL and Relational AlgebraSQL and Relational AlgebraSQLSQL• Declarative languageDeclarative language–– Users specify what theUsers specify what theresult of the query shouldresult of the query shouldbe, DBMS decidesbe, DBMS decidesoperations and order ofoperations and order ofexecutionexecution• OperationsOperations–– Provides commands toProvides commands tocreate and modifycreate and modifydatabase structure anddatabase structure andconstraints (DDL)constraints (DDL)–– Provides commands toProvides commands toinsert, delete, update andinsert, delete, update andretrieve (DML)retrieve (DML)RARA• Procedural languageProcedural language–– Algebraic expressionsAlgebraic expressionsspecify an order ofspecify an order ofoperations ie. How theoperations ie. How thequery will be processedquery will be processed• OperationsOperations–– Provides operators, thatProvides operators, thatenable a user to specifyenable a user to specifyretrieval requests onlyretrieval requests only
  8. 8. 8ContentsContentsRelational AlgebraRelational Algebra• What is a Relational QueryWhat is a Relational Query• Relational Query LanguagesRelational Query Languages• Relational Algebra OperationsRelational Algebra Operations• Query Formulation in Relational AlgebraQuery Formulation in Relational Algebra• Exercises in Relational AlgebraExercises in Relational Algebra
  9. 9. 9Relational AlgebraRelational AlgebraOperationsOperations• Relational algebra operations are applied onRelational algebra operations are applied onrelationsrelations• Result of relational algebra operations are alsoResult of relational algebra operations are alsorelations, i.e the algebra operations producerelations, i.e the algebra operations producenew relations from oldnew relations from old• A sequence of relational algebra operationsA sequence of relational algebra operationsforms a relational algebra expression, whoseforms a relational algebra expression, whoseresult will also be a relationresult will also be a relation
  10. 10. 10Types of RA OperationsTypes of RA Operations• Set operations from mathematical set theorySet operations from mathematical set theory(Applicable because each relation is also a(Applicable because each relation is also a setsetof tuples)of tuples)–– UNIONUNION–– INTERSECTIONINTERSECTION–– DIFFERENCEDIFFERENCE–– CARTESIAN PRODUCTCARTESIAN PRODUCT• Operations developed specifically for RDBsOperations developed specifically for RDBs–– SELECTSELECT–– PROJECTPROJECT–– JOINJOIN–– DIVISIONDIVISION
  11. 11. 11Operators and NotationOperators and NotationTraditional SetTraditional SetOperatorsOperators• IntersectionIntersection ∩∩• UnionUnion ∪∪• DifferenceDifference ——• Cartesian ProductCartesian Product ××Specific DatabaseSpecific DatabaseOperatorsOperators• SelectSelect σσ• ProjectProject ΠΠ• JoinJoin ⋈⋈• DivisionDivision ÷÷
  12. 12. 12Understanding RAUnderstanding RAOperationsOperations• SELECTSELECT• PROJECTPROJECT• Assignment and NamingAssignment and Naming• UNIONUNION• INTERSECTIONINTERSECTION• DIFFERENCEDIFFERENCE• Properties of operatorsProperties of operators• CARTESIAN PRODUCTCARTESIAN PRODUCT• JOINJOIN• DIVISIONDIVISIONDiscuss FirstDiscuss FirstDiscuss SecondDiscuss SecondDiscuss ThirdDiscuss Third
  13. 13. 13SelectSelectσσ << selection condition >selection condition > ( < relation name > )( < relation name > )Select those rows which satisfy a given condition ThisSelect those rows which satisfy a given condition Thisoperation is also called “restriction”operation is also called “restriction”NAME SALARYADDRESS DEPTSmith 50k St. Lucia PrintingDilbert 40k Taringa PrintingJones 60k Kenmore PrintingTrump 65k AuchenflowerHead OfficeHarrison78k St. Lucia Head OfficeSelectedSelectedTuplesTuples
  14. 14. 14Select ExampleSelect Example1. List all details of employees working in1. List all details of employees working indepartment 4?department 4?EMPLOYEEEMPLOYEE [Ename,[Ename, SSNSSN, DOB, Address, Sex,, DOB, Address, Sex,Salary, SuperSSN, Dno]Salary, SuperSSN, Dno]σσ Dno = 4Dno = 4 (EMPLOYEE)(EMPLOYEE)
  15. 15. 15Select ExampleSelect Example2. List all details of employees earning more than2. List all details of employees earning more than$30000?$30000?EMPLOYEEEMPLOYEE [Ename,[Ename, SSNSSN, DOB, Address, Sex,, DOB, Address, Sex,Salary, SuperSSN, Dno]Salary, SuperSSN, Dno]σσ Salary > 30000Salary > 30000 (EMPLOYEE)(EMPLOYEE)
  16. 16. 16Select ExampleSelect Example3. List all details about employees who work in3. List all details about employees who work indepartment 4 and earn over $25000, or workdepartment 4 and earn over $25000, or workin department 5 and earn over $30000?in department 5 and earn over $30000?EMPLOYEEEMPLOYEE [Ename,[Ename, SSNSSN, DOB, Address, Sex,, DOB, Address, Sex,Salary, SuperSSN, Dno]Salary, SuperSSN, Dno]σσ (Dno = 4(Dno = 4 ∧∧ Salary > 25000)Salary > 25000) ∨∨(Dno = 5 ∧ Salary > 30000)(Dno = 5 ∧ Salary > 30000) (EMPLOYEE)(EMPLOYEE)
  17. 17. 17ProjectProjectΠΠ< atribute column name´s< atribute column name´s >> ( < relation name > )( < relation name > )Select those columns specified in the listSelect those columns specified in the listNAME SALARYADDRESS DEPTSmith 50k St. Lucia PrintingDilbert 40k Taringa PrintingJones 60k Kenmore PrintingTrump 65k AuchenflowerHead OfficeHarrison78k St. Lucia Head OfficeSelectedSelectedattributesattributes
  18. 18. 18Project ExampleProject Example4. For each employee, list their name, date of birth4. For each employee, list their name, date of birthand salary.and salary.EMPLOYEEEMPLOYEE [Ename,[Ename, SSNSSN, Bdate, Address, Sex,, Bdate, Address, Sex,Salary, SuperSSN, Dno]Salary, SuperSSN, Dno]ΠΠ Ename,Bdate,SalaryEname,Bdate,Salary (EMPLOYEE)(EMPLOYEE)
  19. 19. 19Project ExampleProject Example5. List the salaries paid to employees in each5. List the salaries paid to employees in eachdepartment and the department number.department and the department number.EMPLOYEEEMPLOYEE [Ename,[Ename, SSNSSN, DOB, Address, Sex,, DOB, Address, Sex,Salary, SuperSSN, Dno]Salary, SuperSSN, Dno]ΠΠ Dno, SalaryDno, Salary (EMPLOYEE)(EMPLOYEE)
  20. 20. 20Handling Complex QueriesHandling Complex QueriesFormulation of complex queries may requireFormulation of complex queries may requireseveral relational algebra operations one afterseveral relational algebra operations one afterthe otherthe other–– Operations can be written as a single relationalOperations can be written as a single relationalalgebraalgebra expressionexpression by nesting the operationsby nesting the operations–– Operations can be applied one at a time byOperations can be applied one at a time bycreatingcreating intermediateintermediate result relationsresult relationsIntermediate Results have to beIntermediate Results have to be “assigned”“assigned” tototemporary relations which must betemporary relations which must be “named”“named”
  21. 21. 21Relation Assignment and NamingRelation Assignment and Naming• Relation AssignmentRelation Assignment–– Result RelationResult Relation ←← Relational ExpressionRelational Expression• Relation NamingRelation Naming–– TEMPTEMP ←←• Attribute (re)NamingAttribute (re)Naming–– TEMP (dept, emp-salary)TEMP (dept, emp-salary) ←←
  22. 22. 22Assignment ExampleAssignment Example6. Create a new relation named RESULT,6. Create a new relation named RESULT,containing each employee and their date of birth.containing each employee and their date of birth.Label the resulting columns with ‘Employee’ andLabel the resulting columns with ‘Employee’ and‘DOB’.‘DOB’.EMPLOYEEEMPLOYEE [Ename,[Ename, SSNSSN, Bdate, Address, Sex,, Bdate, Address, Sex,Salary, SuperSSN, Dno]Salary, SuperSSN, Dno]RESULT(Employee,DOB )RESULT(Employee,DOB ) ←← ΠΠ Ename,BdateEname,Bdate (EMPLOYEE)(EMPLOYEE)
  23. 23. 23Assignment ExampleAssignment Example7. List the names and salaries of all employees who7. List the names and salaries of all employees whowork for department 5work for department 5EMPLOYEEEMPLOYEE [Ename,[Ename, SSNSSN, Bdate, Address,, Bdate, Address,Sex,Sex,Salary, SuperSSN, Dno]Salary, SuperSSN, Dno]ΠΠ Ename,SalaryEname,Salary (( σσ Dno = 5Dno = 5 (EMPLOYEE )(EMPLOYEE ) ))EMPS - DEP5EMPS - DEP5 ←← σσ Dno = 5Dno = 5 (EMPLOYEE )(EMPLOYEE )RESULTRESULT ←← ΠΠ Ename,SalaryEname,Salary (EMPS_ DEP5(EMPS_ DEP5))Query withQuery withExpressionExpressionQuery withQuery withIntermediateIntermediateRelationsRelations
  24. 24. 24Understanding RAUnderstanding RAOperationsOperations• SELECTSELECT• PROJECTPROJECT• Assignment and NamingAssignment and Naming• UNIONUNION• INTERSECTIONINTERSECTION• DIFFERENCEDIFFERENCE• Properties of operatorsProperties of operators• CARTESIAN PRODUCTCARTESIAN PRODUCT• JOINJOIN• DIVISIONDIVISION
  25. 25. 25Basic Set OperatorsBasic Set Operators• Relation is aRelation is a setset ofoftuples (no duplicates)tuples (no duplicates)• Set theory, andSet theory, andhence elementary sethence elementary setoperators also applyoperators also applyto relationsto relations–– UNIONUNION–– INTERSECTIONINTERSECTION–– DIFFERENCEDIFFERENCE–– CARTESIANCARTESIANPRODUCTPRODUCTUnionA∪BIntersectionA∩BDifferenceA - BA BA BA B
  26. 26. 26Union Compatibility in RelationsUnion Compatibility in RelationsTwo relations R(A1, A2, ..., An) and S(B1, B2,Two relations R(A1, A2, ..., An) and S(B1, B2,..., Bn) are..., Bn) are union compatibleunion compatible iffiff–– They have theThey have the same degree nsame degree n, (number of, (number ofcolumns)columns)–– Their columnsTheir columns have corresponding domainshave corresponding domains, i.e, i.edom(Ai) = dom(Bi) for 1dom(Ai) = dom(Bi) for 1 ≤≤ ii ≤≤ nnApplies to union, intersection and differenceApplies to union, intersection and difference
  27. 27. 27…… Union CompatibilityUnion CompatibilityAlthough domains need to correspond they doAlthough domains need to correspond they donot have to have the same namenot have to have the same nameWORKS_ONWORKS_ON [ESSN, Pno, Hours][ESSN, Pno, Hours]WORKED_ONWORKED_ON [Employee, Project, Duration][Employee, Project, Duration]wherewhere dom (ESSN) = dom (Employee)dom (ESSN) = dom (Employee)dom (Pno) = dom (project)dom (Pno) = dom (project)dom (Hours) = dom (Duration)dom (Hours) = dom (Duration)
  28. 28. 28UnionUnionR1R1 ∪∪ R2R2Produces a relation that includes all tuplesProduces a relation that includes all tuplesthat appear only in R1, or only in R2, or inthat appear only in R1, or only in R2, or inboth R1 and R2both R1 and R2Duplicate Tuples are eliminatedDuplicate Tuples are eliminatedR1 and R2 must be union compatibleR1 and R2 must be union compatible
  29. 29. 29Union ExampleUnion Example8.Identify the employees who either work on8.Identify the employees who either work onprojects or have dependents.projects or have dependents.WORKS_ONWORKS_ON [[ESSN, PNoESSN, PNo, Hours], Hours]DEPENDENTDEPENDENT [[ESSN, Dep_NameESSN, Dep_Name, Sex, DOB,, Sex, DOB,Relationship]Relationship]WORKS_ONWORKS_ON ∪∪ DEPENDENTDEPENDENTThe relations are not UNION compatible !The relations are not UNION compatible !
  30. 30. 30Union ExampleUnion Example9.List the ESSN’s of employees who either have9.List the ESSN’s of employees who either havedependents or work on projects.dependents or work on projects.WORKS_ONWORKS_ON [[ESSN, PNoESSN, PNo, Hours], Hours]DEPENDENTDEPENDENT [[ESSN, Dep_NameESSN, Dep_Name, Sex, DOB,, Sex, DOB,Relationship]Relationship]ΠΠ ESSNESSN (( DEPENDENT )DEPENDENT ) ∪∪ ΠΠ ESSNESSN (WORKS_ON )(WORKS_ON )
  31. 31. 31IntersectionIntersectionR1R1 ∩∩ R2R2Produces a relation that includes the tuplesProduces a relation that includes the tuplesthat appearthat appearin both R1 and R2.in both R1 and R2.R1 and R2 must be union compatible.R1 and R2 must be union compatible.
  32. 32. 32Intersection ExampleIntersection Example11. List the ESSN’s of employees who have11. List the ESSN’s of employees who havedependents and are managersdependents and are managers..DEPENDENTDEPENDENT [[ESSN, Dep_NameESSN, Dep_Name, Sex, DOB,, Sex, DOB,Relationship]Relationship]DEPARTMENTDEPARTMENT [DName,[DName, DNumberDNumber, MgrSSN, MgrStart], MgrSSN, MgrStart]ΠΠ ESSNESSN (( DEPENDENT )DEPENDENT ) ∩∩ ΠΠ MGRSSNMGRSSN (DEPARTMENT )(DEPARTMENT )
  33. 33. 33DifferenceDifferenceR1R1 -- R2R2Produces a relation that includes all theProduces a relation that includes all thetuples thattuples thatappear in R1, but do not appear in R2.appear in R1, but do not appear in R2.R1 and R2 must be union compatible.R1 and R2 must be union compatible.
  34. 34. 34Difference ExampleDifference Example11. List the ESSN’s of employees who have11. List the ESSN’s of employees who havedependents but do not work on projectsdependents but do not work on projects..WORKS_ONWORKS_ON [[ESSN, PNoESSN, PNo, Hours], Hours]DEPENDENTDEPENDENT [[ESSN, Dep_NameESSN, Dep_Name, Sex,, Sex,DOB,DOB,Relationship]Relationship]ΠΠ ESSNESSN (( DEPENDENT )DEPENDENT ) —— ΠΠ ESSNESSN (WORKS_ON )(WORKS_ON )
  35. 35. 35Properties of OperatorsProperties of Operators• Commutative and Associative OperatorsCommutative and Associative Operators• Precedence among operators in relationalPrecedence among operators in relationalalgebra expressionsalgebra expressions• De Morgan’s LawsDe Morgan’s Laws
  36. 36. 36Commutative and AssociativeCommutative and AssociativeA ∪ B Commutative A ∪ B = B ∪ Aassociative (A ∪ B) ∪ C = A ∪ ( B ∪ C )A∩ B commutative A ∩ B = B ∩ Aassociative (A ∩ B) ∩ C = A ∩ ( B ∩ C )A —Bnot commutative A — B ≠ B — Anot commutative (A — B) — C ≠ A — (B —C )
  37. 37. 37Operator PrecedenceOperator Precedence==, ≠,, ≠, <, >, ≤, ≥<, >, ≤, ≥notnotandandororσσ,, ΠΠ∩∩, ∪, —, ×, +, ⋈, ∪, —, ×, +, ⋈• Operators performed left to right in theOperators performed left to right in theexpressionexpression• ( ) can be used to alter operator precedence,( ) can be used to alter operator precedence,that is operations in ( ) will be performed beforethat is operations in ( ) will be performed beforeeven if they have a lower precedence ordereven if they have a lower precedence orderHigherHigherLowerLower
  38. 38. 38Precedence ExamplePrecedence Example12.12. List all employees who are male, and eitherList all employees who are male, and eitherearn less than $40000 or work for deptment 5.earn less than $40000 or work for deptment 5.EMPLOYEEEMPLOYEE [Ename,[Ename, SSNSSN, DOB, Address, Sex,, DOB, Address, Sex,Salary, SuperSSN, Dnum]Salary, SuperSSN, Dnum]ΠΠ EnameEname ((σσ (Sex = ‘M’ and (Salary < 40000 or Dnum = 5))(Sex = ‘M’ and (Salary < 40000 or Dnum = 5)) (EMPLOYEE )(EMPLOYEE ) ))How does the above solution differ from the following?How does the above solution differ from the following?ΠΠ EnameEname ((σσ (Sex = ‘M’ and Salary < 40000 or Dnum = 5)(Sex = ‘M’ and Salary < 40000 or Dnum = 5) (EMPLOYEE )(EMPLOYEE ) ))
  39. 39. 39De Morgan’s LawsDe Morgan’s Laws¬¬ ( p( p ∧∧ q )q ) ≡ ¬≡ ¬ pp ∨∨ ¬¬ qq¬¬ ( p( p ∨∨ q )q ) ≡ ¬≡ ¬ pp ∧∧ ¬¬ qqwhere p and q are predicates, e.g Age>20,where p and q are predicates, e.g Age>20,Dept=Research, e.gDept=Research, e.g¬¬ (Salary(Salary >> 40000)40000) ∧∧ (Dept(Dept == Research) )Research) )≡≡¬¬ (Salary(Salary >> 40000)40000) ∨∨ ¬¬ (Dept(Dept == Research)Research)
  40. 40. 40DeMorgan’s Law ExampleDeMorgan’s Law Example13. List all projects which are neither located in13. List all projects which are neither located inBrisbane, nor controlled by department 4.Brisbane, nor controlled by department 4.PROJECTPROJECT [PName,[PName, PNoPNo, Plocation, Dnum], Plocation, Dnum]ΠΠ PnamePname ((σσ not (Plocation = ‘Brisbane’) and not (Dnum=4)not (Plocation = ‘Brisbane’) and not (Dnum=4) (PROJECT)(PROJECT)))≡≡ΠΠ PnamePname ((σσ not (Plocation = ‘Brisbane’ or Dnum=4)not (Plocation = ‘Brisbane’ or Dnum=4) (PROJECT)(PROJECT) ))≡≡ΠΠ PnamePname ((σσ not (Plocation <> ‘Brisbane’ and Dnum <> 4)not (Plocation <> ‘Brisbane’ and Dnum <> 4) (PROJECT)(PROJECT) ))
  41. 41. 41Cartesian ProductCartesian ProductR1R1 ×× R2R2• Also known as a cross-product or cross-join R1Also known as a cross-product or cross-join R1and R2 needand R2 need NOT be union compatibleNOT be union compatible• The result of R1 (A1, A2, … An) x R2 (B1, B2, …The result of R1 (A1, A2, … An) x R2 (B1, B2, …Bm) is a relation Q withBm) is a relation Q with n + m attributesn + m attributes QQ(A1, A2, … An, B1, B2, … Bm) in that order(A1, A2, … An, B1, B2, … Bm) in that order• Q has one tuple for each combination of tuplesQ has one tuple for each combination of tuplesfrom R1 and R2, thus if R1 has r tuples and R2from R1 and R2, thus if R1 has r tuples and R2has t tuples, thenhas t tuples, then Q will haveQ will have r * t tuplesr * t tuples
  42. 42. 42Cartesian Product ExampleCartesian Product ExampleSubjectCS114CS115CS180Subject Student DegreeCS114 Anna BITCS114 Fred BScCS115 Anna BITCS115 Fred BScCS180 Anna BITCS180 Fred BScStudent DegreeAnna BITFred BSc=×
  43. 43. 43Cartesian Product ExampleCartesian Product Example14. For each female employee, list the names14. For each female employee, list the namesof all of her dependents.of all of her dependents.EMPLOYEEEMPLOYEE [Ename,[Ename,SSNSSN,DOB,Address,Sex,Salary,SuperSSN, Dno],DOB,Address,Sex,Salary,SuperSSN, Dno]DEPENDENTDEPENDENT [[ESSN, DepNameESSN, DepName, Sex, DOB, Relationship], Sex, DOB, Relationship]FEMALE_EMPSFEMALE_EMPS ←← σσ Sex = ‘F’Sex = ‘F’ (EMPLOYEE)(EMPLOYEE)EMP_NAMESEMP_NAMES ←← ΠΠ Ename, SSNEname, SSN (FEMALE_EMPS)(FEMALE_EMPS)EMP_DEPENDEMP_DEPEND ←← EMP_NAMESEMP_NAMES ×× DEPENDENTDEPENDENTACTUAL_DEPENDACTUAL_DEPEND ←← σσ SSN = ESSNSSN = ESSN (EMP_DEPEND)(EMP_DEPEND)RESULTRESULT ←← ΠΠ Ename, DepNameEname, DepName (ACTUAL_DEPEND)(ACTUAL_DEPEND)
  44. 44. 44Understanding RAUnderstanding RAOperationsOperations• SELECTSELECT• PROJECTPROJECT• Assignment and NamingAssignment and Naming• UNIONUNION• INTERSECTIONINTERSECTION• DIFFERENCEDIFFERENCE• Properties of operatorsProperties of operators• CARTESIAN PRODUCTCARTESIAN PRODUCT• JOINJOIN• DIVISIONDIVISION
  45. 45. 45Join OperationsJoin Operations• A Join is similar to Cartesian Product, but onlyA Join is similar to Cartesian Product, but onlyselected pairs of tuples appear in the resultselected pairs of tuples appear in the result• It is used to combine related tuples from twoIt is used to combine related tuples from tworelations into a single tuple in a new relation.relations into a single tuple in a new relation.This is needed when information is contained inThis is needed when information is contained inmore than one relationmore than one relation• There are three types of Join Operations:There are three types of Join Operations:–– Thieta-JoinThieta-Join–– Equi-JoinEqui-Join–– Natural JoinNatural Join
  46. 46. 46Thieta-JoinThieta-JoinR1R1 ⋈⋈ < join condition>< join condition> R2R2A join condition(s) is of the form AA join condition(s) is of the form A θθ B, where AB, where A∈∈ R1 and BR1 and B ∈∈ R2,R2,andand θθ is one of {=, <, ≤, >, ≥}is one of {=, <, ≤, >, ≥}
  47. 47. 47Thieta-Join ExampleThieta-Join Example15. For each employee, list all the employees who15. For each employee, list all the employees whoearn more (than the first employee).earn more (than the first employee).EMPLOYEEEMPLOYEE [Ename,[Ename, SSNSSN, DOB, Address, Sex, Salary,, DOB, Address, Sex, Salary,SuperSSN, Dno]SuperSSN, Dno]DEPARTMENTDEPARTMENT [DName,[DName, DNumberDNumber, MgrSSN, MgrStart], MgrSSN, MgrStart]AA ←← EMPLOYEEEMPLOYEEBB ←← EMPLOYEEEMPLOYEERESULTRESULT ←← ΠΠ A.Ename, B.EnameA.Ename, B.Ename (A(A⋈⋈ A.Salary< B.SalaryA.Salary< B.Salary BB))
  48. 48. 48Equi-JoinEqui-JoinR1R1 ⋈⋈ < join condition>< join condition> R2R2Specialization of JoinSpecialization of JoinJoin condition only hasJoin condition only has equalityequality comparisons onlycomparisons only
  49. 49. 49Equi-Join ExampleEqui-Join Example16. List the names of the managers of16. List the names of the managers ofeacheachdepartment.department.EMPLOYEEEMPLOYEE [ Ename,[ Ename, SSNSSN, DOB, Address, Sex, Salary,, DOB, Address, Sex, Salary,SuperSSN, Dno]SuperSSN, Dno]DEPARTMENTDEPARTMENT [ DName,[ DName, DNumberDNumber, MgrSSN, MgrStart], MgrSSN, MgrStart]DEPT_MGRDEPT_MGR ←← DEPARTMENTDEPARTMENT ⋈⋈ MGRSSN = SSNMGRSSN = SSN EMPLOYEEEMPLOYEERESULTRESULT ←← ΠΠ EnameEname (DEPT_MGR)(DEPT_MGR)
  50. 50. 50Natural JoinNatural JoinR1R1 ** R2R2• Similar to equi-join except that the attributes thatSimilar to equi-join except that the attributes thatare used for the join are those that have theare used for the join are those that have thesame name in each relationsame name in each relation• Consequently, they are not explicitly specifiedConsequently, they are not explicitly specified• The duplicate column is eliminatedThe duplicate column is eliminated
  51. 51. 51Natural Join ExampleNatural Join ExampleSubject Student DegreeCS114 Anna BITCS114 Anna BACS115 Fred BScCS180 Anna BITCS180 Anna BAStudent DegreeAnna BITAnna BAFred BSc* =Subject StudentCS114 AnnaCS115 FredCS180 AnnaCS214 Bobby
  52. 52. 52Natural Join ExampleNatural Join Example17. What is the result schema of the following17. What is the result schema of the followingquery? What attributes is the join performedquery? What attributes is the join performedon?on?DEPARTMENTDEPARTMENT [ DName,[ DName, DNumberDNumber, MgrSSN, MgrStart ], MgrSSN, MgrStart ]DEPT_LOCSDEPT_LOCS [[ DNumberDNumber,, DlocationDlocation ]]DEPARTMENT * DEPT_LOCSDEPARTMENT * DEPT_LOCS
  53. 53. 53Natural Join ExampleNatural Join Example18. What is the difference between the results of18. What is the difference between the results ofthe following queries? What attributes arethe following queries? What attributes arethethejoins performed on?joins performed on?EMPLOYEEEMPLOYEE [ Ename,[ Ename, SSNSSN, DOB, Address, Sex, Salary, SuperSSN,, DOB, Address, Sex, Salary, SuperSSN,Dno ]Dno ]DEPARTMENTDEPARTMENT [ DName,[ DName, DNumberDNumber, MgrSSN, MgrStart ], MgrSSN, MgrStart ]EMPLOYEE * DEPARTMENTEMPLOYEE * DEPARTMENTandandEMPEMP(MgrSSN ,Dnumber)(MgrSSN ,Dnumber) ←← ΠΠ SSN,DnoSSN,Dno (EMPLOYEE)(EMPLOYEE)RESULTRESULT ←← EMP * DEPARTMENTEMP * DEPARTMENT
  54. 54. 54DivisionDivisionR1R1 ÷÷ R2R2• Result relation contains columns in R1, but notResult relation contains columns in R1, but notin R2in R2• Relations R1 and R2 must beRelations R1 and R2 must be divisiondivisioncompatiblecompatible, i.e last n columns of R1 must be, i.e last n columns of R1 must beidentically named to columns in R2, where n isidentically named to columns in R2, where n isthe degree of R2the degree of R2• The result relation contains tuples t, such that aThe result relation contains tuples t, such that avalue in t appears in R1, in combination withvalue in t appears in R1, in combination withevery tuple in R2every tuple in R2
  55. 55. 55Division ExampleDivision ExampleStudent Degree SubjectAnna BIT CS114Anna BIT CS115Anna BIT CS180Fred BSc CS114Fred BSc CS180Student DegreeAnna BIT÷ =SubjectCS114CS115
  56. 56. 56Division ExampleDivision Example22. Retrieve the names of employees who work22. Retrieve the names of employees who workononall projects that John Smith works on.all projects that John Smith works on.EMPLOYEEEMPLOYEE [ Ename,[ Ename, SSNSSN, DOB, Address, Sex, Salary, SuperSSN,, DOB, Address, Sex, Salary, SuperSSN,Dno]Dno]WORKS_ONWORKS_ON [[ ESSNESSN,, PnoPno, Hours ], Hours ]SMITHSMITH ←← σσ Ename=‘John Smith’Ename=‘John Smith’ (EMPLOYEE)(EMPLOYEE)SMITH_PNOSSMITH_PNOS ←← ΠΠ PnoPno (WORKS_ON(WORKS_ON ⋈⋈ ESSN=SSNESSN=SSN SMITH)SMITH)SSN_PNOSSSN_PNOS ←← ΠΠ ESSN, PnoESSN, Pno (WORKS_ON)(WORKS_ON)SSNS(SSN)SSNS(SSN) ←← SSN_PNOSSSN_PNOS ÷÷ SMITH_PNOSSMITH_PNOSRESULTRESULT ←← ΠΠ EnameEname (SSNS * EMPLOYEE)(SSNS * EMPLOYEE)
  57. 57. 57ContentsContentsRelational AlgebraRelational Algebra• What is a Relational QueryWhat is a Relational Query• Relational Query LanguagesRelational Query Languages• Relational Algebra OperationsRelational Algebra Operations• Query Formulation in Relational AlgebraQuery Formulation in Relational Algebra• Exercises in Relational AlgebraExercises in Relational Algebra
  58. 58. 58Query Formulation in RAQuery Formulation in RA• Understand what the English query meansUnderstand what the English query means• Identify which relations, tuples (SELECT) and attributesIdentify which relations, tuples (SELECT) and attributes(PROJECT) that will be required for the query(PROJECT) that will be required for the query• Identify the relationships between required relations andIdentify the relationships between required relations andaccordingly which binary operators can be usedaccordingly which binary operators can be used(JOIN, PRODUCT, UNION, DIVISION, …)(JOIN, PRODUCT, UNION, DIVISION, …)• Formulate the query keeping in mind operator propertiesFormulate the query keeping in mind operator properties(Commutative/Associative, Order precedence, De(Commutative/Associative, Order precedence, DeMorgan’s Laws)Morgan’s Laws)
  59. 59. 59Which RA Operator to use ?Which RA Operator to use ?• SELECTSELECT ←←• PROJECTPROJECT ←←• UNIONUNION ←←• INTERSECTIONINTERSECTION• DIFFERENCEDIFFERENCE ←←• CARTESIAN PRODUCTCARTESIAN PRODUCT ←←• JOINJOIN• DIVISIONDIVISION• Use unary operators SELECT /Use unary operators SELECT /PROJECT when choosing tuples /PROJECT when choosing tuples /attributes respectively from a singleattributes respectively from a singlerelationrelation• Use binary operators UNION,Use binary operators UNION,PRODUCT, JOIN, … when definingPRODUCT, JOIN, … when definingthe relationship between 2 or morethe relationship between 2 or morerelationsrelations{{ σσ ,,ΠΠ,, U,U, ——,, × }× } Complete Set ofComplete Set ofOperationsOperations
  60. 60. 60Complete Set of RA OperatorsComplete Set of RA Operators• It has been proved thatIt has been proved that {{σσ,, ΠΠ,, ∪∪,, ——,, ×}×} is ais acomplete set of RA operatorscomplete set of RA operators• Each remaining relational algebra operator canEach remaining relational algebra operator canbe expressed as a sequence of operations frombe expressed as a sequence of operations fromthis setthis set• These remaining operators have been definedThese remaining operators have been definedprimarily for convenience !primarily for convenience !
  61. 61. 61Expressing other operatorsExpressing other operators• IntersectionIntersectionRR ∩ S ≡ ( R ∪ S ) – (( R — S ) ∪ ( S — R ))∩ S ≡ ( R ∪ S ) – (( R — S ) ∪ ( S — R ))• (Thieta/Equi) Join(Thieta/Equi) JoinRR <condition><condition> SS ≡≡ σσ <condition><condition> ( R( R ×× S)S)• Natural JoinNatural JoinS(B1,B2, B3, … Bm)S(B1,B2, B3, … Bm)R1 (B1, A2, A3, . . . An)R1 (B1, A2, A3, . . . An) ←← ΠΠ (A1, A2, A3, . . . An)(A1, A2, A3, . . . An) RRR * SR * S ≡≡ ΠΠ (B1, A2, A3, ... An, B2, ... Bm)(B1, A2, A3, ... An, B2, ... Bm) σσ <R.B1 = S.B1><R.B1 = S.B1> ( R1( R1××S)S)
  62. 62. 62Expressing other operatorsExpressing other operators• DivisionDivisionT1T1 ←← ΠΠ YY ( R )( R )T2T2 ←← ΠΠ YY ( ( S( ( S ×× T1 )T1 ) —— R )R )RR ÷ S ≡÷ S ≡ T1T1 — T2— T2
  63. 63. 63ContentsContentsRelational AlgebraRelational Algebra• What is a Relational QueryWhat is a Relational Query• Relational Query LanguagesRelational Query Languages• Relational Algebra OperationsRelational Algebra Operations• Query Formulation in Relational AlgebraQuery Formulation in Relational Algebra• Exercises in Relational AlgebraExercises in Relational Algebra
  64. 64. 64Relational Algebra ExercisesRelational Algebra ExercisesThese exercises use the Company database as anThese exercises use the Company database as anexample to illustrate relational algebra queries thatexample to illustrate relational algebra queries thatrequire the use of multiple relational algebra operatorsrequire the use of multiple relational algebra operators• EMPLOYEEEMPLOYEE [[SsnSsn, Fname, Mit, Lname, Dob, Address,, Fname, Mit, Lname, Dob, Address,Sex,Sex,Salary, Dno, SuperSSN]Salary, Dno, SuperSSN]• DEPARTMENTDEPARTMENT [[DnumberDnumber, Dname, MGRSSN,MgrStart], Dname, MGRSSN,MgrStart]• PROJECTPROJECT [[PnoPno, PName, Plocation, DNum], PName, Plocation, DNum]• DEPENDENTDEPENDENT [[ESSN,DepNameESSN,DepName, Sex, DOB,, Sex, DOB,Relationship]Relationship]• WORKS_ONWORKS_ON [[ESSNESSN,, PNoPNo, Hours], Hours]• DEPT_LOCSDEPT_LOCS [[DNumberDNumber,, DLocationDLocation]]
  65. 65. 65RA ExerciseRA Exercise23. Retrieve the name and address of all23. Retrieve the name and address of allemployeesemployeeswho work for the Research Department.who work for the Research Department.EMPLOYEEEMPLOYEE [ Ename,[ Ename, SSNSSN, DOB, Address, Sex, Salary, SuperSSN,, DOB, Address, Sex, Salary, SuperSSN,Dno ]Dno ]DEPARTMENTDEPARTMENT [ Dname,[ Dname, DnumberDnumber, MgrSSN, MgrStart ], MgrSSN, MgrStart ]RESEARCH_DEPTRESEARCH_DEPT ←← σσ Dname=‘Research’Dname=‘Research’ (DEPARTMENT)(DEPARTMENT)RESEARCH_DEPT_EMPSRESEARCH_DEPT_EMPS ←← (RESEARCH_DEPT(RESEARCH_DEPT⋈⋈ Dnumber=DnoDnumber=Dno EMPLOYEE)EMPLOYEE)RESULTRESULT ←← ΠΠ Ename,AddressEname,Address (RESEARCH_DEPT_EMPS)(RESEARCH_DEPT_EMPS)
  66. 66. 66RA ExerciseRA Exercise24. For every project located in Houston, list the project24. For every project located in Houston, list the projectnumber, the controlling department number, and thenumber, the controlling department number, and thedepartment manager’s name, address & birth datedepartment manager’s name, address & birth date..EMPLOYEEEMPLOYEE [ Ename,[ Ename, SSNSSN, DOB, Address, Sex, Salary, SuperSSN,, DOB, Address, Sex, Salary, SuperSSN,Dno]Dno]DEPARTMENTDEPARTMENT [ Dname,[ Dname, DnumberDnumber, MgrSSN, MgrStart], MgrSSN, MgrStart]PROJECTPROJECT [ PName,[ PName, PnumberPnumber, Plocation, Dnum], Plocation, Dnum]HOUSTON_PROJSHOUSTON_PROJS ←← σσ Plocation=‘houston’Plocation=‘houston’ (PROJECT)(PROJECT)CONTR_DEPTCONTR_DEPT ←← (HOUSTON_PROJS(HOUSTON_PROJS ⋈⋈ Dnum=DnumberDnum=Dnumber DEPARTMENT)DEPARTMENT)PROJ_DEPT_MGRPROJ_DEPT_MGR ←← (CONTR_DEPT(CONTR_DEPT⋈⋈ MgrSSN=SSNMgrSSN=SSN EMPLOYEE)EMPLOYEE)RESULTRESULT ←← ΠΠ Pnumber,Dnum,Ename,Address,BdatePnumber,Dnum,Ename,Address,Bdate (PROJ_DEPT_MGR)(PROJ_DEPT_MGR)
  67. 67. 67RA ExerciseRA Exercise25. Find the names of employees who work on all25. Find the names of employees who work on allprojects controlled by department 5.projects controlled by department 5.EMPLOYEEEMPLOYEE [ Ename,[ Ename, SSNSSN, DOB, Address, Sex, Salary, SuperSSN,, DOB, Address, Sex, Salary, SuperSSN,Dno]Dno]PROJECTPROJECT [ PName,[ PName, PnumberPnumber, Plocation, Dnum], Plocation, Dnum]WORKS_ONWORKS_ON [[ ESSNESSN,, PnoPno, Hours, Hours]]DEPT5_PROJS(Pno)DEPT5_PROJS(Pno) ←← ΠΠ PnumberPnumber ((σσ Dnum=5Dnum=5 (PROJECT))(PROJECT))EMP_PROJ(SSN,Pno)EMP_PROJ(SSN,Pno) ←← ΠΠ ESSN,PnoESSN,Pno (WORKS_ON)(WORKS_ON)RESULT_EMP_SSNSRESULT_EMP_SSNS ← E← EMP_PROJMP_PROJ ÷÷ DEPT5_PROJSDEPT5_PROJSRESULTRESULT ←← ΠΠ EnameEname (RESULT_EMP_SSNS * EMPLOYEE )(RESULT_EMP_SSNS * EMPLOYEE )
  68. 68. 68RA ExerciseRA Exercise26. List project numbers for projects that involve an employee26. List project numbers for projects that involve an employeewhose name is Smith, either as a worker or as a managerwhose name is Smith, either as a worker or as a managerofofthe department that controls the project.the department that controls the project.EMPLOYEEEMPLOYEE [ Ename,[ Ename, SSNSSN, DOB, Address, Sex, Salary, SuperSSN, Dno], DOB, Address, Sex, Salary, SuperSSN, Dno]PROJECTPROJECT [ PName,[ PName, PnumberPnumber, Plocation, Dnum], Plocation, Dnum]DEPARTMENTDEPARTMENT [ Dname,[ Dname, DnumberDnumber, MgrSSN, MgrStart], MgrSSN, MgrStart]WORKS_ONWORKS_ON [[ ESSN, PnoESSN, Pno, Hours], Hours]SMITHS(ESSN)SMITHS(ESSN) ←← ΠΠ SSNSSN ((σσ Ename=‘Smith’Ename=‘Smith’ (EMPLOYEE))(EMPLOYEE))SMITH_WORKER_PROJSSMITH_WORKER_PROJS ←← ΠΠ PnoPno (WORKS_ON * SMITHS)(WORKS_ON * SMITHS)MGRSMGRS ←← ΠΠ Ename,DnumberEname,Dnumber (EMPLOYEE(EMPLOYEE ⋈⋈ SSN=MgrSSNSSN=MgrSSN DEPARTMENT)DEPARTMENT)SMITH_MGRSSMITH_MGRS ←← σσ Ename=‘Smith’Ename=‘Smith’ (MGRS)(MGRS)SMITH_MANAGED_DEPTS(Dnum)SMITH_MANAGED_DEPTS(Dnum) ←← ΠΠ DnumberDnumber (SMITH_MGRS)(SMITH_MGRS)SMITH_MGR_PROJS(Pno)SMITH_MGR_PROJS(Pno) ←← ΠΠ PnumberPnumber (SMITH_MANAGED_DEPTS * PROJECT)(SMITH_MANAGED_DEPTS * PROJECT)RESULTRESULT ←← SMITH_WORKER_PROJSSMITH_WORKER_PROJS ∪∪ SMITH_MGR_PROJSSMITH_MGR_PROJS
  69. 69. 69RA ExerciseRA Exercise27. Retrieve the names of employees who have no27. Retrieve the names of employees who have nodependents.dependents.EMPLOYEEEMPLOYEE [ Ename,[ Ename, SSNSSN, DOB, Address, Sex, Salary, SuperSSN,, DOB, Address, Sex, Salary, SuperSSN,Dno]Dno]DEPENDENTDEPENDENT [[ ESSNESSN,, Dep_NameDep_Name, Sex, DOB, Relationship], Sex, DOB, Relationship]ALL_EMPSALL_EMPS ←← ΠΠ SSNSSN (EMPLOYEE)(EMPLOYEE)EMPS_WITH_DEPS(SSN)EMPS_WITH_DEPS(SSN) ←← ΠΠ ESSNESSN (DEPENDENT)(DEPENDENT)EMPS_WITHOUT_DEPSEMPS_WITHOUT_DEPS ←← ( ALL_EMPS( ALL_EMPS ——EMPS_WITH_DEPS)EMPS_WITH_DEPS)RESULTRESULT ←← ΠΠ EnameEname (EMPS_WITHOUT_DEPS * EMPLOYEE(EMPS_WITHOUT_DEPS * EMPLOYEE ))
  70. 70. 70RA ExerciseRA Exercise28. List the names of managers who have at least28. List the names of managers who have at leastone dependent.one dependent.EMPLOYEEEMPLOYEE [ Ename,[ Ename, SSNSSN, DOB, Address, Sex, Salary, SuperSSN,, DOB, Address, Sex, Salary, SuperSSN,Dno]Dno]DEPARTMENTDEPARTMENT [ Dname,[ Dname, DnumberDnumber, MgrSSN, MgrStart], MgrSSN, MgrStart]DEPENDENTDEPENDENT [[ ESSNESSN,, Dep_NameDep_Name, Sex, DOB, Relationship], Sex, DOB, Relationship]MGR(SSN)MGR(SSN) ←← ΠΠ MgrSSNMgrSSN (DEPARTMENT)(DEPARTMENT)EMPS_WITH_DEPS(SSN)EMPS_WITH_DEPS(SSN) ←← ΠΠ ESSNESSN (DEPENDENT)(DEPENDENT)MGRS_WITH_DEPSMGRS_WITH_DEPS ←← (MGRS(MGRS ∩∩ EMPS_WITH_DEPS)EMPS_WITH_DEPS)RESULTRESULT ←← ΠΠ EnameEname (MGRS_WITH_DEPS * EMPLOYEE)(MGRS_WITH_DEPS * EMPLOYEE)
  71. 71. 71ReviewReview• Relational algebra gives the theoretical foundations forRelational algebra gives the theoretical foundations forRelational Query LanguagesRelational Query Languages–– Relational algebra operations operate on entire relations,Relational algebra operations operate on entire relations,and produce results which are also relationsand produce results which are also relations–– Relational algebra expressions, consisting of a sequenceRelational algebra expressions, consisting of a sequenceof relational algebra operators, specify a high-levelof relational algebra operators, specify a high-levelprocedure to achieve a query resultprocedure to achieve a query result• However, relational algebraic query formulation isHowever, relational algebraic query formulation isprocedural, and therefore focuses on how a query resultprocedural, and therefore focuses on how a query resultcan be achievedcan be achieved• Declarative query languages, e.g., SQL, allow the user toDeclarative query languages, e.g., SQL, allow the user tospecifyspecify whatwhat info the user wants rather thaninfo the user wants rather than howhow the resultthe resultis to be obtainedis to be obtained
  72. 72. 72Recommended ReadingsRecommended ReadingsElmasri & NavatheElmasri & NavatheChapter 7Chapter 7
  73. 73. 73Next ...Next ...Module 7Module 7Structured QueryStructured QueryLanguage (SQL)Language (SQL)

×