Data Modeling Using the Entity- Relationship (ER)...

67
Data Modeling Using the Entity- Relationship (ER) Model

Transcript of Data Modeling Using the Entity- Relationship (ER)...

Data Modeling Using the Entity-Relationship (ER) Model

������������ ������������������������

������� �� ����� ���

An Introduction to designing a An Introduction to designing a DatabaseDatabase

�� AA databasedatabase isis aa collectioncollection ofof datadata thatthat isisorganizedorganized inin suchsuch aa mannermanner thatthat itsits contentscontents cancanbebe readilyreadily accessed,accessed, managedmanaged andand updatedupdated

�� AnAn EntityEntity RelationshipRelationship modelmodel (ERM)(ERM) maymay bebeusedused toto aidaid thethe developmentdevelopment ofof aa databasedatabase� An ER model may be represented pictorially by

ERDs

What is a Data Model?What is a Data Model?

�� AA detaileddetailed modelmodel thatthat capturescaptures overalloverall structurestructureofof organizationalorganizational datadata whilewhile beingbeing independentindependentofof anyany implementationimplementation considerationsconsiderations

Rationale for using Rationale for using Data Modelling?Data Modelling?

�� TypicallyTypically datadata modellingmodelling isis carriedcarried outout parallelparallel withwithotherother requirementsrequirements analysisanalysis andand structuringstructuring stepsstepsduringduring thethe systemssystems analysisanalysis phasephase

�� DuringDuring thisthis phasephase aa datadata modelmodel isis developeddeveloped forfor thethecurrentcurrent systemsystem

�� FollowingFollowing this,this, thethe datadata modelmodel supportingsupporting thethe scopescopeandand requirementsrequirements ofof thethe proposedproposed systemsystem isisdevelopeddeveloped

Entity Relationship Model (ER)Entity Relationship Model (ER)

�� ER model was proposed by ER model was proposed by Peter ChenPeter Chen in 1976in 1976

�� ER model has become the standard tool for ER model has become the standard tool for conceptual schemaconceptual schema designdesign

�� ER model consists of three basic constructs: ER model consists of three basic constructs: entitiesentities, , attributesattributes and and relationshipsrelationships..

What is an entity ?What is an entity ?

�� AnAn entityentity isis aa “thing”“thing” inin thethe realreal worldworld withwith ananindependentindependent existenceexistence..

�� ItIt maymay bebe anan objectobject withwith physicalphysical existenceexistence(e(e..gg.. person,person, car,car, house,house, employee),employee), oror itit maymaybebe anan objectobject withwith conceptualconceptual existenceexistence(company,(company, job,job, university,university, course)course)..

Entity and Entity SetEntity and Entity Set

�� TwoTwo typestypes ofof entitiesentities::

� Strong entity: can exist independently (orcan uniquely identify itself)

� Weak entity: existence depends on theexistence of other (strong) entity orentities

�� ExamplesExamples::

� An employee is a strong entity but thedependents of the employee could beweak entities

� An account in a bank is a strong entity buta transaction could be a week entity

Entity and Entity SetEntity and Entity Set

�� An An entity typeentity type defines a set of entities that defines a set of entities that have the same attributes.have the same attributes.

� STUDENT is an entity type (Schema)

�� An An entity setentity set is a collection of entities of the is a collection of entities of the same entity type same entity type

�� Examples:Examples:

� Rima, Amit, Kamal, Sameer, Ram are entity set of an entity type STUDENT

AttributesAttributes

�� An An entityentity has a set of has a set of attributeattributes that describes it.s that describes it.

� Person(Pan_No, Name, Address, Job-description, Salary).

�� An entity will have a value for each of its attributesAn entity will have a value for each of its attributes

� (ALINN7856R Naresh Potdar, ‘20 Amrita Residency, Pune, , Maharashtra, India’, ‘Manager’, 95000)

�� The properties of an entity set are called attributes of the entity The properties of an entity set are called attributes of the entity set. set.

� Students: Rollno, Name, Address, GPA, Status, ...

� Books: Title, ISBN, Authors, Publisher, Year, ...

Types of AttributesTypes of Attributes

�� SimpleSimple (or (or atomicatomic) attribute is a one which ) attribute is a one which cannot be divided into smaller parts.cannot be divided into smaller parts.

� Examples:

� RollNo, GPA, Salary.

�� CompositeComposite attribute is an attribute which can attribute is an attribute which can be divided into smaller subparts, these subparts be divided into smaller subparts, these subparts represent more basic attributes with represent more basic attributes with independent meanings of their ownindependent meanings of their own

� Examples:

� Name: First_Name, Middle_Name, Last_Name

� Address: Street_Address, City, State, Pincode

House No.

Address

Street-Address City State Post Code

Street Name

An Example of a composite attributeAn Example of a composite attribute

Types of AttributesTypes of Attributes

�� A A singlesingle--valuedvalued attribute is a one which has one attribute is a one which has one (single) value for a particular entity.(single) value for a particular entity.

� Example: Age, BirthDate

�� A A multimulti--valuedvalued attribute is a one which may attribute is a one which may have one or more values for the same entity. have one or more values for the same entity.

� College Degrees for Person: 0, 1, 2, 3, …

� Color for a Car: 1, 2, …..

� Authors of Books

� Phone Number

Types of AttributesTypes of Attributes

�� A A storedstored attribute is a one whose value is attribute is a one whose value is explicitly stored in the database.explicitly stored in the database.

� e.g. name, birth-date.

�� DerivedDerived--attributes: whose values are attributes: whose values are computed from other attributes. computed from other attributes.

� Age from Birthdate

� Annual Salary from Monthly Salary

� NoOfEmployees ==> Count number of employees in the Employee table.

ERD SymbolsERD Symbols

SSADM* Chen

Entity

Attribute

Relationship

����������

���� �

���� ��

�� �

����������

�����������

���� ��

*Structured systems analysis and design method

Relationship TypesRelationship Types

�� A relationship type is represented as A relationship type is represented as diamonddiamond--shaped boxshaped box which is connected by straight lineswhich is connected by straight lines

Degree of a relationship type is the number

of participating entity types: binary

relationships, ternary relationships, ….

EMPLOYEE COMPANYWorks-for

Binary Relationships

Relationship DegreeRelationship Degree

SUPPLIER PROJECT

PART

supplies

Ternary RelationshipsTernary Relationships

COMPANY PRODUCT

COUNTRY

Sells

Ternary Relationships

EMPLOYEE Supervises

PERSON Marry

Binary Recursive Relationships

RelationshipsRelationships

�� The The role namerole name signifies the role that a signifies the role that a participating entity from the entity type participating entity from the entity type plays in each relationship instanceplays in each relationship instance

�� entity entity ee11 plays the role of a plays the role of a supervisorsupervisor, while , while entity entity ee22 plays the role of a plays the role of a superviseesupervisee

EMPLOYEE Supervises

supervisorsupervisor

superviseesupervisee

ee11

ee22

Cardinality RatioCardinality Ratio

�� Specifies the Specifies the numbernumber of of relationship instancesrelationship instancesthat an entity can participate inthat an entity can participate in

�� Common cardinality ratios for Common cardinality ratios for binarybinaryrelationship types are relationship types are

� 1:1,

� 1:N, and

� M:N

EMPLOYEE Works_for COMPANYN 1

An employee works for one company,

and a company has many employees

working for it

1:N1:N

DEPARTMENT Has MANAGER1 1

A department has one manager and a

manager manages one department

11::11

EMPLOYEE Works-on PROJECTM N

An employee works on many projects,

and a project has many employees

working on it

M:NM:N

Participation ConstraintsParticipation Constraints

�� Specifies whether the Specifies whether the existenceexistence of an of an entity depends on its being related to entity depends on its being related to another entity via the relationship typeanother entity via the relationship type

�� There is There is totaltotal and and partialpartial participationparticipation

EMPLOYEE Works-for DEPARTMENTN 1

Every employee must be related to a department

via WORKS-FOR relationship. A department

must have at least one employee.

Total participation..

Total participation

PERSON Buys CAR1 N

A person may buy a car and car

may be bought by a person

Partial participation

PROFESSOR DEPARTMENT

1 1

Manages

A professor may manage a department

(partial participation), but a department

must be managed by a professor (total

participation).

Total & Partial participation

EMPLOYEE DEPARTMENTWorks-for

1N

Start-Date

We may keep a start date attribute to record for each

employee the date he/she started work for a certain

department.

Attributes of Relationship Types

EMPLOYEE DEPARTMENTWorks-for

Dependents

DEPENDENT

1

N

Fname

Sex

Birthdate

Relationship

identifying relationship

A weak entity type is an entity which does not have any key attributes

Weak Entity Types

• A weak entity type always has a total

participation with its identifying entity type

• A Weak entity type has a partial key, i.e. this

key is enough to identify its extension within

the scope of its identifying entity type

• In the previous example, the first name is

enough to identify kids within a single family,

but is not enough to identify entities as stand

alone entities (two families may use identical

names for their kids)

ER ER NNotations otations

<Name>

<Name>

<Name>

<Name>

Entity Type

Attribute

Key Attribute

Multi-valued

attribute

ER Diagram Notations

Weak Entity Type

Relationship Type

Identifying Relationship Type

<Name>

<Name>

<Name>

Composite Attribute

ER ER NNotations otations

Derived Attribute

partial key attribute

<Name>

<Name>

<Name>

<Name><Name>

NotationsNotations

�� Entity TypesEntity Types

� singular name, capital letters

�� Relationship TypesRelationship Types

� usually singular verbs, capital letters

�� AttributeAttribute

� nouns, capitalized

�� Role namesRole names

� are in lowercase letters

�� ERER diagramsdiagrams areare drawndrawn suchsuch thatthat theythey arearereadablereadable fromfrom leftleft toto rightright andand toptop toto bottombottom(Except(Except weakweak entityentity types)types)

RelationshipsRelationships

�� Several relationships may exist among the Several relationships may exist among the same set of entity sets.same set of entity sets.

EMPLOYEE DEPARTMENT

Works_in

Manages

Degree of a Relationship (Degree of a Relationship (11))

�� Definition:Definition:

� The degree of a relationship is the number of entity sets participating the relationship.

�� Recursive relationshipRecursive relationship

Examples: Examples:

SupervisesSupervises on Employeeson Employees

is_prerequisite_ofis_prerequisite_of on Courseson Courses

is_classmate_ofis_classmate_of on Studentson Students

Degree of a Relationship (Degree of a Relationship (22))

�� Binary relationshipBinary relationship (degree = (degree = 22) )

� Examples:

� takes between Students and Courses

� owns between Persons and Cars

�� Ternary relationshipTernary relationship (degree = (degree = 33) )

� Examples:

� orders among Customers, Parts and

Suppliers

� skill_used among Engineers, Skills and

Projects

Cardinality (Cardinality (11) )

�� OneOne--toto--one (one (11--toto--11) relationship) relationship between Ebetween E1 1 and Eand E22: :

� for each entity in E1, there is at most oneassociated entity in E2, and vice versa.

�� Examples of Examples of 11--toto--1 1 relationships:relationships:

� Binary 1-to-1 relationship

� manages between Employees and Departments

� recursive 1-to-1 relationship

� is_married_to on Persons

Cardinality (2)Cardinality (2)

�� OneOne--toto--many (many (11--toto--m) relationshipm) relationship from Efrom E1 1 to Eto E22: : for for eacheach entity of Eentity of E11, there are , there are zero or morezero or moreassociated entities of Eassociated entities of E22, but for , but for eacheach entity of Eentity of E22, , there is there is at most oneat most one associated entity of Eassociated entity of E11

�� Examples of Examples of 11--toto--m relationships:m relationships:

� binary 1-to-m relationship

� advises between Professors and Students

� recursive 1-to-m relationship

� is_mother_of on Persons

�� ManyMany--toto--one (mone (m--toto--11)) relationship from Erelationship from E1 1 to Eto E22: : same as same as 11--toto--m relationship from Em relationship from E2 2 to Eto E11

Cardinality (Cardinality (33))

�� ManyMany--toto--many (mmany (m--toto--m) relationshipm) relationship between Ebetween E1 1 and Eand E22: for : for eacheach entity in Eentity in E11, there are , there are zero or morezero or moreassociated entities in Eassociated entities in E22, and vice versa, and vice versa

�� Examples of mExamples of m--toto--m relationships:m relationships:

� binary m-to-m relationship

� takes between Students and Courses

� recursive m-to-m relationship

� is_component_of on Parts

ER Diagram (ER Diagram (11))

Recursive relationship

is_married_to

PERSON

PanNo Name Age

1 1

ER Diagram (ER Diagram (22))

binary relationship

advisesPROFESSOR

Emp_id Name Age

1 mSTUDENT

RollNo Name Age

ER Diagram (3)ER Diagram (3)

ternary relationship

Skill_used

SKILL PROJECT

ENGINEER

Role of an Entity Set (1)Role of an Entity Set (1)

Definition: The Definition: The rolerole of an entity set in a relationship is the of an entity set in a relationship is the function it performs in the relationship.function it performs in the relationship.

Case Case 11: Role can be determined from properly chosen : Role can be determined from properly chosen names.names.

takes

STUDENT

1

m

COURSE

is_TA_of

n

1

Role of an Entity Set (Role of an Entity Set (22))

Case Case 22: Roles need to be explicitly given.: Roles need to be explicitly given.

is_married_to

PERSON

1 1

wife husband

supervises

EMPLOYEE

1 m

supervisor supervisee

Attribute of Relationship (Attribute of Relationship (11))

Where to keep the grade information?Where to keep the grade information?

takesSTUDENTm n

COURSE

grade

Attribute of Relationship (Attribute of Relationship (22))

Another example:Another example:

orders

PART PROJECT

SUPPLIER

Quantitym

n r

Cardinality Constraint Cardinality Constraint min/max (min/max (11))

�� OneOne in ER model means in ER model means zero or onezero or one

�� ManyMany in ER model means in ER model means zero or morezero or more

�� Cardinality constraints make them more Cardinality constraints make them more preciseprecise

takesSTUDENT(1, 5) (15, 60)

COURSE

Cardinality Constraint Cardinality Constraint min/max (min/max (22))

�� General format:General format:

�� 0 0 ≤≤ min_card min_card ≤≤ max_card max_card

� Interpretation:

� Each entity in E may involve between min_card

and max_card relationships in R.

RE(min_card, max_card)

Cardinality Constraint Cardinality Constraint min/max (min/max (33))

�� Definition: Definition:

� If every entity in E involves at least onerelationship in R (i.e., min_card >= 1), E is said to have total participation in R

� If min_card = 0, E is said to have partialparticipation in R

Cardinality Constraint Cardinality Constraint min/max (min/max (44))

Employees has a partial participation.Employees has a partial participation.

Departments has a total participation.Departments has a total participation.

managesEMPLOYEE(0, 1) (1, 1)

DEPARTMENT

Representing Representing 11--toto--11, , 11--toto--m, mm, m--toto--mmRelationships Relationships

RE(0, 1) (0, 1)

Fone-to-one:

RE(0, m) (0, n)

Fmany-to-many:

RE(0, m) (0,1)

Fone-to-many:

RE1 m

F

Company Database

An Example Database Application

An Example Database An Example Database ApplicationApplication

�� TheThe CompanyCompany databasedatabase keepskeeps tracktrack ofof aacompany’scompany’s

� Employees, Departments, Projects

�� TheThe followingfollowing areare thethe requirementsrequirements andandspecificationsspecifications

�� TheThe companycompany isis organizedorganized intointo departmentsdepartments..

�� EachEach departmentdepartment hashas aa::

� unique name, unique number

� particular employee who manages thedepartment

�� WeWe keepkeep tracktrack ofof thethe startstart datedate whenwhen thatthatemployeeemployee beganbegan managingmanaging thethe departmentdepartment

�� AA departmentdepartment maymay havehave severalseveral locationslocations

An Example Database An Example Database ApplicationApplication

�� AA departmentdepartment controlscontrols aa numbernumber ofof projectsprojects,, eacheach ofofwhichwhich hashas aa� unique name, unique number, and single location

�� WeWe storestore eacheach employeeemployee’s’s� name, social security number, address, salary, sex,

and birth date.�� AnAn employeeemployee isis assignedassigned toto oneone departmentdepartment butbut maymay

workwork onon severalseveral projects,projects, whichwhich areare notnot necessarilynecessarilycontrolledcontrolled byby thethe samesame departmentdepartment

�� WeWe keepkeep tracktrack ofof thethe numbernumber ofof hourshours perper weekweek thatthatanan employeeemployee worksworks onon eacheach projectproject

�� WeWe keepkeep tracktrack ofof thethe directdirect supervisorsupervisor ofof eacheachemployeeemployee

An Example Database An Example Database ApplicationApplication

�� WeWe wantwant toto keepkeep tracktrack ofof thethe dependentdependentss ofofeacheach employeeemployee forfor insuranceinsurance purposespurposes..

�� WeWe keepkeep eacheach dependent’sdependent’s firstfirst namename,, sexsex,, birthbirthdatedate,, andand relationshiprelationship toto thethe employeeemployee

ER diagram for the company ER diagram for the company databasedatabase

Each Each departmentdepartment has a has a unique name, a unique number, particular employee who manages the department. A department may have several A department may have several locations.locations.

DEPARTMENT

Name Number Locations

NumberOfEmployee

ER diagram for the company ER diagram for the company databasedatabase

A department A department controlscontrols a number of a number of projectsprojects, each of which has a , each of which has a unique name, unique number, and single location

PROJECT

Name Number Location

ER diagram for the company ER diagram for the company databasedatabase

We store each We store each employeeemployee’s ’s name, social security number, address, salary, sex, and birth date.

EMPLOYEE

Name Emp_No Address

SalarySex

BDate

FnameMinit Lname

ER diagram for the company ER diagram for the company databasedatabase

We want to keep track of the We want to keep track of the dependentdependents of each employee for insurance s of each employee for insurance purposes. We keep each dependent’s purposes. We keep each dependent’s first namefirst name, , sexsex, , birth datebirth date, and , and relationshiprelationship to the employeeto the employee

DEPENDENT

Relationship

Sex

BDate

Fname

(0,1)

ER diagram for the company ER diagram for the company databasedatabase

EachEach departmentdepartment has a has a particular employee who manages the department

We keep track of the We keep track of the start datestart date when that when that employeeemployee began began managingmanaging the the departmentdepartment

EMPLOYEE DEPARTMENTManages

StartDate

(1,1)

managerdepartment

managed

employee

(1,1)

ER diagram for the company ER diagram for the company databasedatabase

An employee is An employee is assigned toassigned to one department.one department.

EMPLOYEE DEPARTMENTWorks_for(1,N)

department

ER diagram for the company ER diagram for the company databasedatabase

A A departmentdepartment controlscontrols a number of a number of projectsprojects

DEPARTMENT PROJECTControls(0,N) (1,1)

controlling

department

controlled

project

ER diagram for the company ER diagram for the company databasedatabase

An An employeeemployee is assigned to one department but may is assigned to one department but may work onwork on several several

projectprojects, which are not necessarily controlled by the same department. We s, which are not necessarily controlled by the same department. We

keep track of the keep track of the number of hoursnumber of hours per week that an employee works on each per week that an employee works on each

projectproject

EMPLOYEE PROJECTWorks_on(0,N) (1,N)

worker project

Hours

ER diagram for the company ER diagram for the company databasedatabase

We keep track of the directWe keep track of the direct supervisor ofsupervisor of each each employeeemployee

EMPLOYEE

Supervises

(0,N) (0,1)

supervisor supervisee

ER diagram for the company ER diagram for the company databasedatabase

We want to keep track of the We want to keep track of the dependentdependents of each s of each employeeemployee for insurance purposes.for insurance purposes.

EMPLOYEE DEPENDENThas(0,N) (1,1)

employee dependent