Relational Model

  • Upload
    briar

  • View
    68

  • Download
    1

Embed Size (px)

DESCRIPTION

Relational Model. Outline. Relational Model Concepts Relational Model Constraints & Relational Database Schemas Update Operation & Dealing with Constraint Violations. Relational Model Concept. - PowerPoint PPT Presentation

Citation preview

  • Relational Modeldww-database system

    dww-database system

  • dww-database systemOutlineRelational Model ConceptsRelational Model Constraints & Relational Database SchemasUpdate Operation & Dealing with Constraint Violations

    Slide 5-*

    dww-database system

  • dww-database systemRelational Model ConceptFirst introduced by Dr. E.F. Codd of IBM Research in 1970 in paper titled Relational Model of Data for Large Shared Data Banks one of great papers in computer scienceThe Relational Model of Data is Based on the Concept of RelationsA Relation is a Mathematical Concept Based on the Concept of Sets The strength of the relational approach to data management comes from the formal foundation provided by the theory of relations.Slide 5-*

    dww-database system

  • dww-database systemRelationsRelational DBMS products store data in the form of relations, a special type of tableA relation is a two-dimensional table that has the following characteristicsRows contain data about an entityColumns contain data about attributes of the entityCells of the table hold a single valueAll entries in a column are of the same kindEach column has a unique nameThe order of the columns is unimportant concept of setThe order of the rows is unimportantNo two rows may be identicalSlide 5-*

    dww-database system

  • dww-database systemAttributesRelations (cont)Set of Tuples and Typically Shown as a Table With Columns and Rows.Column (Field) Represents an AttributeRow (Tuple) Represents an Entity Instance

    Slide 5-*

    dww-database system

  • dww-database systemEquivalent Relational TerminologyAlthough not all tables are relations, the terms table and relation are normally used interchangeably

    Slide 5-*

    dww-database system

    Sheet1

    Relational ModelProgrammerUser

    RelationFileTable

    Tuple (Row)RecordRow

    AttributeFieldColumn

    Sheet2

    Sheet3

  • dww-database systemExample: RelationSlide 5-*

    dww-database system

  • dww-database systemExample: Tables Not RelationsSlide 5-*

    dww-database system

  • dww-database systemEmployeeA B C Da2 {b1, b2} c1 d5a2 b7 c9 d5a2 b23 c22 d1...A B C Da2 b2 c6 d1a2 b7 c9 d5a2 b7 c9 d5...R1R2E# Ename AGE ADDRESSE1 Smith 30 3302 Peachtree Rd., Atlanta, GAE2 Diamond 45 1888 Buford Hyw. E3 Evan Baker Ct. AtlantaExamplesAre the Following Relations in a Relational Model? Why or Why Not?

    Slide 5-*

    dww-database system

  • dww-database systemFormal DefinitionA Relation may be defined in multiple ways.The Schema of a Relation: R (A1, A2, .....An)Relation schema R is defined over attributes A1, A2, .....An. For Example: CUSTOMER (Cust-id, Cust-name, Address, Phone#)Here, CUSTOMER is a relation defined over the four attributes Cust-id, Cust-name, Address, Phone#, each of which has a domain or a set of valid values. For example, the domain of Cust-id is 6 digit numbers.Slide 5-*

    dww-database system

  • dww-database systemFormal DefinitionA tuple is an ordered set of valuesEach value is derived from an appropriate domain.Each row in the CUSTOMER table may be referred to as a tuple in the table and would consist of four values. is a tuple belonging to the CUSTOMER relation.A relation may be regarded as a set of tuples (rows).Columns in a table are also called attributes of the relation.

    Slide 5-*

    dww-database system

  • dww-database systemFormal DefinitionA domain has a logical definition: e.g., USA_phone_numbers are the set of 10 digit phone numbers valid in the U.S.A domain may have a data-type or a format defined for it. The USA_phone_numbers may have a format: (ddd)-ddd-dddd where each d is a decimal digit. E.g., Dates have various formats such as monthname, date, year or yyyy-mm-dd, or dd mm,yyyy etc.An attribute designates the role played by the domain. E.g., the domain Date may be used to define attributes Invoice-date and Payment-date.Slide 5-*

    dww-database system

  • dww-database systemFormal DefinitionThe relation is formed over the Cartesian Pproduct of the sets; each set has values from a domain; that domain is used in a specific role which is conveyed by the attribute name.For example, attribute Cust-name is defined over the domain of strings of 25 characters. The role these strings play in the CUSTOMER relation is that of the name of customers.Formally,Given R(A1, A2, .........., An) r(R) dom (A1) X dom (A2) X ....X dom(An)R: schema of the relationr of R: a specific "value" or population of R.R is also called the intension of a relationr is also called the extension of a relationSlide 5-*

    dww-database system

  • dww-database systemFormal DefinitionLet S1 = {0,1}Let S2 = {a,b,c}

    Let R S1 X S2

    Then for example: r(R) = { , , } is one possible state or population or extension r of the relation R, defined over domains S1 and S2. It has three tuples.

    Slide 5-*

    dww-database system

  • dww-database systemTwo Versions of a Student RelationSlide 5-*

    dww-database system

  • dww-database systemEMPPROJWORKSENOENAMETITLESALRelation Schemes ExampleEMP(ENO, ENAME, TITLE, SAL)PROJ (PNO, PNAME, BUDGET)WORKS(ENO, PNO, RESP, DUR)Underlined Attributes are Relation Keys which Uniquely Distinguish Among Tuples (Rows)Tabular FormSlide 5-*

    dww-database system

  • dww-database systemRelation InstancesSlide 5-*

    dww-database system

  • dww-database systemExamplesExercise: R(A, B) is a Relation Schema Defined over A and BLet domain(A) = {a1, a2} and domain(B) = {0, 1, 2}Which of the Following are Relations of R?{(a1, 1), (a1, 2), (a2, 0)} {(a1, 0), (a1, 1), (a1, 2)}{(a1, 1), (a2, 2}, (a0, 0)}{(a1, 1), (a2, a2}, (a0, a0)}{(a1, 1, c1), (a2, 2)} What if Attribute A is a Key?Slide 5-*

    dww-database system

  • dww-database systemCharacteristics of AttributesAttribute Name An Attribute Name Refers to a Position in a Tuple by Name Rather than PositionAn Attribute Name Indicates the Role of a Domain in a RelationAttribute Names must be Unique Within RelationsBy Using Attribute Names we can Disregard the Ordering of Field Values in TuplesAttribute Value - Must have a ValueMust Be an Atomic ValueCan Be a Null Value Meaning Not Known, Not Applicable ...Slide 5-*

    dww-database system

  • dww-database systemConstraint in DatabaseInherent ConstraintConstraint that are inherent in the data modelCharacteristics relationSchema-based constraintConstraint that can be directly expressed in the schemas of the data model, typically specifying in DDLDomain constraint, key constraint, etcApplication-based constraintConstraint that can not be directly expressed in the data model and must be expressed and enforced by the application programTrigger, assertion, etcSlide 5-*

    dww-database system

  • dww-database systemRESERVATIONFLT#DATECUST#FLT-SCHEDULEFLT#CUSTOMERCUST#CUST-NAMEDepTDestArrTRelational Integrity ConstraintsIC: Conditions that Must Hold on All Valid Relation Instances at Any Given Database StateWhy are Integrity Constraints Needed? What Happens when we try to Delete a Flight?Slide 5-*

    dww-database system

  • dww-database systemRelational Integrity Constraints ClassificationThere are Three Main Types of Constraints:Key Constraints Entity Integrity ConstraintsReferential Integrity ConstraintsOther Types of Semantic Constraints:Domain ConstraintsTransition ConstraintsSet ConstraintsDBMSs Handle Some But Not All ConstraintsSlide 5-*

    dww-database system

  • dww-database systemTypes of KeysA key is one or more columns of a relation that identifies a rowComposite key is a key that contains two or more attributesA relation has one unique primary key and may also have additional unique keys called candidate keysPrimary key is used to Represent the table in relationshipsOrganize table storageGenerate indexesSlide 5-*

    dww-database system

  • dww-database systemKey ConstraintsSuperkey (SK): Any Subset of Attributes Whose Values are Guaranteed to Distinguish Among TuplesCandidate Key (CK):A Superkey with a Minimal Set of Attributes (No Attribute Can Be Removed Without Destroying the Uniqueness -- Minimal Identity)A Value of an Attribute or a Set of Attributes in a Relation That Uniquely Identifies a TupleThere may be Multiple Candidate KeysSlide 5-*

    dww-database system

  • dww-database systemKey ConstraintsPrimary Key (PK): Choose One From Candidate KeysThe Primary Key Attributed are UnderlinedForeign Key (FK): An Attribute or a Combination of Attributes (Say A) of Relation R1 Which Occurs as the Primary Key of another Relation R2 (Defined on the Same Domain)Allows Linkages Between Relations that are Tracked and Establish DependenciesUseful to Capture ER RelationshipsSlide 5-*

    dww-database system

  • dww-database systemSuperkeys and Candidate Keys: Examples Example: The CAR relation schema: CAR(State, Reg#, SerialNo, Make, Model, Year)Its primary key is {State, Reg#} It has two candidate keys Key1 = {State, Reg#} Key2 = {SerialNo} {SerialNo, Make} is a Superkey but not a Candidate Key Why?If Remove SerialNo, Make is not a Primary KeySlide 5-*

    dww-database system

  • dww-database systemAnother Schema with KeyWhat are Typically Used as Keys for Cars?Slide 5-*

    dww-database system

    CAR(License#, EngineSerialNumber, Make, Model, Year)

  • dww-database systemA Complete Schema with Keys ...Keys Allow us to Establish Links Between RelationsWhat is ThisSimilar to in ER?Slide 5-*

    dww-database system

  • dww-database system and Corresponding DB TablesWhich Represent Tuples/Instances of Each Relation1455ASCnullWBnullnullSlide 5-*

    dww-database system

  • dww-database system with Remaining DB TablesSlide 5-*

    dww-database system

  • dww-database systemExamplesRelational Schema PROJ(PNO, PNAME, BUDGET), we Assume that PNO is the Primary Key The Two Tables Below are Relations of PROJQuestions:Is (PNO,PNAME) a Superkey in Either? Both?Is PNAME a Candidate Key? Explain Your Answer.Is (PNAME,BUDGET) a Superkey in Either? Both?Slide 5-*

    dww-database system

  • dww-database systemRelational Database Schema: A Set S of Relation Schemas (R1, R2, ..., Rn) That Belong to the Same DatabaseS is the Name of the DatabaseS = {R1, R2, ..., Rn}Entity Integrity: For Any Ri in S, Pki is the Primary Key of RAttributes in Pki Cannot Have Null Values in any Tuple of R(ri)T[Pki] < > Null for Any Tuple T in R(r)

    Entity Integrity ConstraintSlide 5-*

    dww-database system

  • dww-database systemA Constraint Involving Two Relations Used to Specify a Relationship Among Tuples inReferencing Relation and Referenced RelationReferential Integrity ConstraintsSlide 5-*

    dww-database system

  • dww-database systemDefinition: R1and R2 have a Referential Integrity Constraint If Tuples in the Referencing Relation R1 have a Set of Foreign Key (FK) Attributes That Reference the Primary Key PK of the Referenced Relation R2 A Tuple T1 in R1( A1, A2 , ..., An) is Said to Reference a Tuple T2 in R2 if $ FK {A1, A2 , ..., An} such that T1[fk] = T2[pk]Referential Integrity ConstraintsSlide 5-*

    dww-database system

  • dww-database systemExamplesWORKSENOPNORESPDURE9 P3 Engineer 30Slide 5-*

    dww-database system

  • dww-database systemENO ENAME TITLEENO PNO RESP DURPNO PNAME BUDGETWORKEMPPROJWORK[ENO] is a subset of EMP[ENO]WORK[PNO] is a subset of PROJ[PNO]Referential Integrity ConstraintsA Referential Integrity Constraint Can Be Displayed in a Relational Database Schema as a Directed Arc From R1.FK to R2.PKSlide 5-*

    dww-database system

  • dww-database systemAnother Example: Referential IntegrityWhat Do theseArrows Representin ER Diagram?Slide 5-*

    dww-database system

  • dww-database systemTransition Integrity ConstraintCan be defined to deal with state changes in the databaseSometimes called dynamic constraintsExample: the salary of an employee can only increaseSlide 5-*

    dww-database system

  • dww-database system

    Integrity Constraints SummaryRelational Database: Set of Relations Satisfying the Integrity ConstraintsIntegrity Constraints (ICs): Conditions that Must Hold on All Valid Relation InstancesKey Constraints - Uniqueness of KeysEntity ICs - No Primary Key Value is NullReferential ICs Between Two Relations, Cross References Must Point to Existing TuplesDomain ICs are Limits on the Value of Particular AttributeTransition ICs Indicate the Way Values Changes Due to Database UpdateSlide 5-*

    dww-database system

  • dww-database systemOperations on RelationsA DBMS Operates via User Queries to Read and Change Data in a DatabaseChanges Can be Inserting, Deleting, or Updating (Equivalent to a Delete followed by Insert)One Critical Issue in DB Operations is Integrity Constraints Maintenance in the Presence ofINSERTING a TupleDELETING a TupleUPDATING/MODIFYING a Tuple.Slide 5-*

    dww-database system

  • dww-database systemProblem StatementsIntegrity Constraints (ICs) Should Not Be Violated by Update OperationsTo Maintain ICs, Updates may Need to be Propagated and Cause Other Updates AutomaticallyCommon Method: Group Several Update Operations Together As a Single TransactionIf Integrity Violation, Several Actions Can Be Taken:Cancel Operation that Caused Violation (REJECT)Perform the Operation but Inform User of ViolationTrigger Additional Updates So the Violation is Corrected (CASCADE Option, SET NULL Option)Execute a User-specified Error-Correction Routine Slide 5-*

    dww-database system

  • dww-database systemInsertion Operations on RelationsInsert a Duplicate Key Violates Key Integrity: Check If Duplicates OccurInsert a Null Key Violates Entity Integrity: Check If Null is in Any KeyInsert a Tuple Whose Foreign Key Attribute Pointing to an Non-existent Tuple Violates Referential Integrity: Check the Existence of Referred TupleSlide 5-*

    dww-database system

  • dww-database systemInsertion Operations on Relations Correction Actions:Reject the UpdateCorrect the Violation - Change Null, Duplicate, Etc.Cascade the Access - Insert a New Tuple That Did Not ExistSlide 5-*

    dww-database system

  • dww-database systemExamplesENOENAMETITLEEMPENOPNORESPE1P1Manager12DURE2P1Analyst24E2P2Analyst 6E3P3Consultant10E3P4Engineer48E4P2Programmer18E5P2Manager24WORKSSlide 5-*

    dww-database system

  • dww-database systemDeletion Operations on RelationsDeleting a Tuple Referred to by Other Tuples in Database (via FKs) would Violate Referential IntegrityAction:Check for Incoming Pointers of the Deleted Tuple.Group the Deletion and the Post-processing of the Referencing Pointers in a Single TransactionSlide 5-*

    dww-database system

  • dww-database systemDeletion Operations on RelationsThree Options If Deletion Causes a Violation Reject the DeletionAttempt to Cascade (Propagate) the Deletion by Deleting the Tuples which Reference the Tuple being or to be DeletedModify the Referencing Attribute Values that Cause the Violation; Each Values is Set to Null or Changed to Reference to Another Valid TupleSlide 5-*

    dww-database system

  • dww-database systemExampleENOENAMETITLEEMPENOPNORESPE1P1Manager12DURE2P1Analyst24E2P2Analyst 6E3P3Consultant10E3P5Engineer48E4P2Programmer18E5P2Manager24P4Manager48WORKSE6L. ChuElect. Eng.E6Slide 5-*

    dww-database system

  • dww-database systemModify Operations on RelationsModify Operation Changes Values of One or More Attributes in a Tuple (or Tuples) of a Given Relation RMaintaining ICs Requires to Check If the Modifying Attributes Are Primary Key or Foreign Keys.Slide 5-*

    dww-database system

  • dww-database systemModify Operations on RelationsIntegrity Check Actions: Case 1: If the Attributes to be Modified are Neither a Primary Key nor a Foreign Key, Modify Causes No Problems Must Check and Confirm that the New Value is of Correct Data Type and Domain Case 2: Modifying a Primary Key Value Similar to Deleting One Tuple and Insert Another in its PlaceSlide 5-*

    dww-database system

  • dww-database systemConstraints and Update Operations Three Types of Update Operations: INSERT, DELETE, MODIFY

    Constraint Maintenance During Updates:The Types of Constraints That Most DBMSs Maintain areKey ConstraintsEntity ConstraintsReferential Integrity ConstraintsSlide 5-*

    dww-database system

  • dww-database systemConstraints and Update OperationsOther Semantic Constraints Need to Be Maintained by Application Developers/ programmersTransition ConstraintsDomain ConstraintsEtc.Some DB Do Maintain Domain Constraints via Enumeration and Value-Range Data Types

    Slide 5-*

    dww-database system

  • dww-database systemRelational LanguagesA Relational LanguageDefines Operations to Manipulate RelationsUsed to Specify Retrieval Requests (Queries)Query Result is Expressed in the Form of a RelationClassificationRelational AlgebraRelational CalculusStructured Query Language

    Slide 5-*

    dww-database system

    Set Constraints: rules governing set of tuples. Key constraint: uniqueness of keys Entity integrity: no primary key value is null Domain Constraints: limit on values of particular attributes. Transition Constraints: how value changes due to database update. Referential Integrity Constraints: between two relations, cross references must point to existing tuples. Semantic Constraints: those need to be explicitly specified in the schema definition. Set Constraints: rules governing set of tuples. Key constraint: uniqueness of keys Entity integrity: no primary key value is null Domain Constraints: limit on values of particular attributes. Transition Constraints: how value changes due to database update. Referential Integrity Constraints: between two relations, cross references must point to existing tuples. Semantic Constraints: those need to be explicitly specified in the schema definition.Sometimes, relations are denoted by showing the name of the relation followed by the columns of the relation in parentheses. The primary key of the relation is underlined.

    YesNo since PNAME is not uniqueNo since BuDGET is not a key neither PNAME.Entity Integrity: The primary key attributes PK of each relation schema R in S cannot have null values in any tuple of r(R). This is because primary key values are used to identify the individual tuples. t[PK] null for any tuple t in r(R)Note: Other attributes of R may be similarly constrained to disallow null values, even though they are not members of the primary key.

    Relational calculusnon-proceduralstate what the properties that should hold in the result relation areRelational algebraproceduralclosed: use operators which work on one or two relations and produce another relationchaining of operations