18
Relational Data Model At the end of this unit, you should be able to : Understand the terminology used in Relational Model Define the rules which preserve the integrity of a relational database Describe the operations in relational languages that are used in updating or retrieving data Relational Model Terminology Relational Data Model Based on the mathematical concept of a relation Organizes and represents data in a form of a table Relatio n A table with rows and columns Attribu te Named column of a relation Tuple Row of a relation Domain Set of allowable(valid) values for each attribute/ (e.g. integers,strings,…) Degree No. of attributes(columns) in each relation Cardina lity No. of tuples(rows) in the relation Example of a relation Student

DBMS - Relational Data Model Notes

Embed Size (px)

DESCRIPTION

Learn about relational databases

Citation preview

Relational Data ModelAt the end of this unit, you should be able to : Understand the terminology used in Relational Model Define the rules which preserve the integrity of a relational database Describe the operations in relational languages that are used in updating or retrieving data

Relational Model Terminology

Relational Data Model Based on the mathematical concept of a relation Organizes and represents data in a form of a tableRelationA table with rows and columns

AttributeNamed column of a relation

TupleRow of a relation

Domain Set of allowable(valid) values for each attribute/(e.g. integers,strings,)

DegreeNo. of attributes(columns) in each relation

CardinalityNo. of tuples(rows) in the relation

Example of a relation Student

Degree is 7, Cardinality is 5More on Domain..(data type?) Each tuple assigns a value to each attribute from its domainFor example, the domain of Cust-name is of character strings of max length 25(varchar25), an age from a domain of integers between 0 and 150, birthDate from a domain of date,, a gender might come from domain {male, female, unknown}View vs Base Relation

Base RelationView

A named relation corresponding to an entity in conceptual schema, whose tuples are physically stored in the database Not a derived relation Has physical existence While it can manipulate the conceptual or physical relations stored in the data, it does not provide security

The dynamic result of one or more relational operations operating on base relations to produce another relation A virtual relation that does not necessarily actally exist in the database but is produced upon request, at time of request(virtual existence) As views are dynamic, changes made to base relations that affect view attributes are immediately reflected in the view(if base relations update values of attributes/attributes in view will also be affected) Contents of a view are defined as a query on one or more base relations Modification through a view(e.g. insert,update,delete operations not permitted!)

Derived relation!

RelationTupleAttribute

TableRowColumn

FileRecordField

Alternate Terminology

Properties of Relations Relation name is DISTINCT from all other relation names in relational schemas Each cell of relation contains exactly ONE atomic value Each attribute as a DISTINCT name Values of an attribute are ALL from the same domain Each tuple is distinct, there are no DUPLICATE tuples(record) Order of attributes & tuples are NOT important

*Relational KeysType of relational keys : Candidate Key Primary Key Alternate Key Foreign Key

KeysDescriptionConditions/CriteriaExample

Candidate Key Minimal set of attributes that can uniquely identify each tuple in a relation Is a subset of the super key A relation may have one or more candidate keys Candidate keys can consist of a single attribute or multiple attributes(together) Multiple attribute keys are known as composite key1. Must contain unique values2. Must not contain null values since a null value is not guaranteed to be unique & we would not be able to identify each _ uniquely3. Must contain minimum no. of fields(attributes) to ensure uniqueness(as above)

StudentID, NRIC,firstName + lastName(combined)

Primary Key One candidate key is designated as primary key whose values are used to identify tuples uniquely in a relation Note : When choosing a primary key from a pool of candidate keys, always choose a single simple key over a composite key(studentId )1. Minimal set of attributes2. Less likely to have its value changed3. Less likely to lose uniqueness in the future4. With fewest characters5. Easier to use from the users point of viewNRIC,StudentId

Alternate Key Candidate keys that are not selected to be primary keysSame as abovefirstName + lastName(combined)

Foreign Key An attribute or a set of attributes within one relation that matches the primary key of some(possibly the same relation) A foreign key is an attribute which provides a logical link between tablesMore this later Linked to Referential IntegrityStudent(R1)Sch_code : SBM,SIT(FK)Student(R2)sch : SIT,SBM(PK)

Nulls Purpose : a way to deal with incomplete/exceptional data. Represents a value for an attribute that is currently unknown or is not applicable for this tuple OR represent an unknown piece of dataRelational Integrity

Integrity Rules Can be specified on a relational database schema Ensure accuracy & integrity of the data in the database (Applied to data items to make sure that the data is valid & consistent)

2 Principal Rules1. Entity Integrity Primary key in a base relation must not contain any nulls Why? A primary key is a minimal identifier that is used to identify tuples uniquely. Hence, no subset of the primary key is sufficient to provide unique identification of tuples. Example :

Description - The image cncpt055.gif shows Table DEPT, which has three columns: DEPTNO, DNAME, and LOC.The DEPTNO column has a Primary Key--no row may duplicate a value in the key and no null values are allowed.This illustration shows that two rows cannot be inserted into Table DEPT because one duplicates an existing value in the primary key, while the other contains a null value for the primary keyhttp://docs.oracle.com/cd/B19306_01/server.102/b14220/data_int.htm#i3771

2. Referential Integrity If foreign key exists in a relation, either foreign key value must match a candidate key value of some tuple in its home relation or foreign key must be wholly null Purpose? Ensures that relationships between tuples in related relations are consistent and valid AND ensures that related tuples are not accidentally deleted/ changed?

Example #1 Not violated :

If AGENT_CODE in Customer Table is not found in Agent Table, we would have a problem in identifying the agent of this customer. There is a data integrity problem!

Example #2 Violated :In the example scenario shown in Figure4.2, the record for customer OBrain (pink shaded) in the CUSTOMER table (dependant table) is disturbing the referential integrity of the database because there exist no reference for the records AGENT_CODE (504) in the related table, AGENT (primary table)

Example #3 Violated :

InFigure 21-7, the referential integrity constraint ensures that every value in themgrcolumn of theemptable corresponds to a value that currently exists in theempnocolumn of the same table, but not necessarily in the same row, because every manager must also be an employee. This integrity constraint eliminates the possibility of erroneous employee numbers in themgrcolumn.

Example 3 #4 Violated & Not Violated :

Some points to remember for referential integrity You cannot delete a parent record if any existing child record is there. If you have to first delete the child record before deleting the parent record. In the above example you cannot delete row of employee no. 101 since its child exist in the ATTENDANCE table. However, you can delete the row of employee no. 103 since no child record exist for this employee in ATTENDANCE table. If you define the FOREIGN KEY with ON DELETE CASCADE option then you can delete the parent record and if any child record exist it will be automatically deleted.

Enterprise Constraints Additional rules that are specified by the users or database administrator that the data must satisfy E.g. business rules no more than 25 students to be assigned to a mentor group

Relational Algebra Relational algebra operations work on one or more relations to define another relation without changing the original relations Both operands and results are relations Uses : - Define a scope of retrieval - Define a scope for update - Define a view - Define access rights - Define integrity constraintsOperations :

1. SELECT operation(horizontal!) Notation : sigma Select a subset of the tuples in a relation that satisfy a selection condition Note: SELECT operation in relational algebra has nothing to do with SQL keyword select. Selection in relational algebra returns those tuples in a relation that fulfill a condition!Examples

2. PROJECT operation(vertical!) Used to select certain attributes from the relation and discards the other attributes (Delete unwanted columns from relation)Examples :

*Combining SELECTION & PROJECTION

Show the names of all employees working in the CS department:name(Dept = 'CS'(EMP) )Results:

Show the name and rank of those Employees who are not in the CS department or Adjuncts:name, rank((Rank = 'Adjunct'Dept = 'CS')(EMP) )Result:

3. UNION operation(R S) The result is a relation that includes all tuples that are either in relation R or in relation S or in both. Duplicate tuples are elimintated. Relation with tuples from R and S with duplicates removed.Example : RRS

FirstLastAge

BillSmith22

SallyGreen28

MaryKeen23

TonyJones32

SFirstLastAge

ForrestGump36

SallyGreen28

DonJuanDeMarco27

4. INTERSECTION operation(R S) The result is a relation that includes all tuples in both relation R & S (Relation with tuples that appear in both R & S)Example : RSFirstLastAge

SallyGreen28

FirstLastAge

BillSmith22

MaryKeen23

TonyJones32

5. DIFFERENCE operation(R S) The result is a relation that includes all tuples that are in relation R but not in relation SExample :

6. CARTESIAN PRODUCT(X) The operation is used to combine tuples from two relations so that related tuples can be identified My definition repeat the second relation?

Employees Projects EmployeeProject

SmithA

PritchettA

PritchettB

CodeName

AVenus

BMars

Employees X ProjectsEmployeeProjectCodeName

SmithAAVenus

SmithABMars

PritchettAAVenus

PritchettABMars

PritchettBAVenus

PritchettBBMars

7. JOIN operation( ) This operation is used to combine related tuples from two relations into a single tuple Types of joins: Inner Join Combines tuples from two relations using comparison operators in a condition - Condition can be = , >= ,