You are on page 1of 74

Database Systems

Basic Relational Data Model


Relational Model, Keys & Constraints
By Dr. Ejaz Ahmed
Objectives
• Terminology - Relational
• Characteristics of Relations
• Relational Data Model Notations
• Key constraints
• Others Constraints

Dr. Ejaz Ahmed 2


Terminology
• A relation is a table with columns and rows.
– Only applies to logical structure of the database, not the physical structure.

• Attribute is a named column of a relation.

• Domain is a set of allowable values for one or more attributes.

• Tuple is a row of a relation.

• Degree is a number of attributes in a relation.

• Cardinality is a number of tuples in a relation.

• Relationship is a link or dependency between relations.

• Relational Database is a collection of relations.


Dr. Ejaz Ahmed 38
Terminology
A relation is a table with columns and rows.

A table can be written as


STUDENT(ID, Name, Nat_ID, DOB, DeptCode)
Relation name Columns or Attributes t2[DOB]

STUDENT: R
ID NAME NAT_ID DOB DEPTCODE

201111 KHALED 1111111111 16-05-1984 ICS

Rows 202222 ADEL 2222222222 23-09-1984 COE


or
r(R) 203333 AHMED 3333333333 11-08-1984 COE Cardinality
Tuples
211111 HASSAN 4444444444 23-10-1985 SWE

204444 MUSTAFA 55555555555 16-11-1984 ICS

Degree
4
Dr. Ejaz Ahmed
Characteristics of Relations

1. Each relation in the same relational database schema has a distinct


name
2. Each value in a tuple is atomic
3. Each attribute in a relation has a distinct name.
4. Values of an attribute are all from the same domain.
5. Each tuple is distinct.
6. Order of attributes has no significance.
7. Order of tuples has no significance, theoretically.

Dr. Ejaz Ahmed 5


Relational Data Model Notations
• The letters Q, R, S denote the abstract relation names.

• R(A1, A2, A3, …., An) denotes a relation schema R of degree n.


– Example: STUDENT(RollNo, Name, Phone, Address, Mobile, DOB)
– COURSE(CourseID, Title, CreditHours)

• Both t[Ai] and t.Ai refers to the value vi in t for attribute Ai


– Example: in second tuple, both t[name] and t.name refers to “Adel”

• Dom(DEPTCODE) = {‘COE’,’ICS’,’SWE’}

Additional Notes: Relational Model & Keys.docs

Dr. Ejaz Ahmed 6


Relation’s Definition
Relation: A relation is a subset of Cartesian product of all domains
R(r)  Dom(A1) x dom(A2) x …… x Dom(An)
Where A1, A2, …., An represent attributes of a relation r.
Evaluation:
Given
A1 = {1, 2}, A2 = {a}, A3 = {x, y}
Then relation
X = {(1, a, y), (2, a, x), (2, a, y)}; 3 tuples of a relation
is a subset of
Y = Dom(A1) x dom(A2) x Dom(A3)
= {(1, a, x), (1, a, y), (2, a, x), (2, a, y)}
Note: Degree of a relation is the number of attributes, in above case degree of relation
is 3.
Alternate Definition of Relation
For each tuple ti is a mapping from R to D
Where D = Dom(A1)  Dom(A2) …  Dom(An)
And t[Ai]  Dom(Ai)
Then a tuple can be considered as attribute and value.
For example: The following representation shows a tuple definition
t = <(id, 21587), (Name, Muhammad,), (Hphone, Null), (Wphone, 866-1141)>
Dr. Ejaz Ahmed 7
Example – Relational Analysis
Evaluate Cartesian product of the following relations A & B:
1 2 3 a b c
A=4 5 6 B= x y z
7 8 9
1 2 3 a b c
1 2 3 x y z
4 5 6 a b c
A x B=4 5 6 x y z
7 8 9 a b c
7 8 9 x y z
Dr. Ejaz Ahmed 8
Conceptual Modeling
• Conceptual schema is the core of a
system supporting all user view
• Should be completed and accurate
representation of an organization’s data
requirements
• Conceptual modeling is a process of
developing a model of information use that
is independent of implementation details
• Result is conceptual data model
Dr. Ejaz Ahmed 9
Data Model
• Integrated collection of concepts for
describing data, relationships between data,
and constraints on the data in an
organization

• Data Model comprises:


– A structural part
– A manipulative part
– Possibly a set of integrity rules
Dr. Ejaz Ahmed 10
Data Model
• Purpose
– To represent data in an understandable way

• Categories of data model include:


– Object-based
– Record-based
– Physical

Dr. Ejaz Ahmed 11


Data Models
• Object-Based Data Models
– Entity-Relationship
– Semantic
– Functional
– Object-Oriented
• Record-Based Data Models
– Relational Data Model
– Network Data Model
– Hierarchical Data Model
• Physical Data-Models
Dr. Ejaz Ahmed 12
Journey of Design

Dr. Ejaz Ahmed 13


Keys

• A key is a combination of one or more


columns that is used to identify rows in a
relation
• A composite key is a key that consists of
two or more columns

Dr. Ejaz Ahmed 14


Keys – Unique or Fewer
Duplications
Student Profile

Medicine

Dr. Ejaz Ahmed 15


Super Key
• A super key is a combination of columns that
uniquely identifies any row within a relational
database management system (RDBMS) table.
• Entry Search Attribute and verbal
Communications/ Validations or Confirmations

{Roll#}, {Roll#, NIC#}, {NIC#}, {Roll#, FirstName, LastName}


{Roll#, FirstName, LastName, Address, City, NIC#, Deptno}

Additional Notes: Relational Model & Keys.docs


16
Example-1
Roll Number First Name Last Name
CSU0001 Shabbir Bhimani
CSU0002 Jain Rao
CSU0003 Nitin Uday

Now we have the following as super keys

Roll Number First Name

Roll Number First Name Last Name

Dr. Ejaz Ahmed 17


Example-2
Following table consists of four columns
 EmployeeID, Name, Job, DeptID
– Examples of superkeys in this table would be {employeeID,
Name}, {employeeID, Name, job}, and
{employeeID, Name, job, departmentID}
• In a real database we don't need values for all of those
columns to identify a row
• We only need, per our example, the set {EmployeeID}.
– This is a minimal superkey
– So, employeeID is a candidate key.
– EmployeeID can also uniquely identify the tuples.
• FirstName and FatherName (for NADRA)
Dr. Ejaz Ahmed 18
Candidate Keys
• A candidate key is a key that determines all of the other
columns in a relation
• Candidate key columns help in searching fewer
duplicated or unique records.
• Examples
In PRODUCT relation
Prod# is a candidate key
Prod_Name is also a candidate key
In ORDER_PROD
(OrderNumber, Prod#) is a candidate key
If BirthDate (or DrivingLicense#) is known then Name,
address, telno etc. can be found from fewer searched
records.
(Candidate key can be called as Alternate Key)
Dr. Ejaz Ahmed 19
File: Candidate keys-Additional Notes.docs
Example (Use of Invoice)

Items are sold to the Customers

Customer should buy Items with Invoice

Same items can be sold on many invoices …

Invoice# and Item# will identifying exact record, what other columns are required

If some one tells you inv# and Qty, can you find exact Item?
Dr. Ejaz Ahmed 20
Identifying Candidate Keys
Each Enterprise Level
For ONE Bank: AccountHolder (or Customer)
ACC#, Fname, Lname, DOB, CNIC#, Addr, City, TelNo, Mobile#,
DriveLic#

For PTCL: Customer (single telno holders)


Consumer#, Fname, Lname, DOB, CNIC#, Addr, City, TelNo,
Mobile#

For NADRA: Citizen (CNIC#, Fname, Lname, FatherName, DOB,


OldCNIC#, PAddr, PCity, TAddr, TCity, TelNo, Mobile#)

TelNo, Mobile#: Old


value, Null, fewer
duplications, changeable

Dr. Ejaz Ahmed 21


Identifying right record using
Candidate Key – an Example
Let’s analyze the following set of columns

{FirstName, LastName, DOB, TelNo, NatCardID}

{First Name, Branch name}  {Acc#, First Name, Last Name, NIC, Branch name}

Dr. Ejaz Ahmed 22


Candidate Keys cont….
Example-1: Branch (branch-name, assets, branch-city)
Candidate Key: {branch-name}

Example-2: Customer (cname, natid, address, city, telno)


cname, address, city can be duplicated individually and cannot determine a record.

The following combinations distinguish customer records or tuples.


{cname, telno}
{natid}
{natid, cname}
As {natid}  {natid, cname}, then {natid, cname} is not candidate key and {natid} is a
candidate key

Example-3: Employee(empno, name, birth_date, address, city, telno, citizenship_id)


empno, telno, citizenship_id are possible candidate keys ???

Exercise:
Course (cid, cname, deptno)
Semester (sid, syear, startdate)
ClassAllocation (sid, cid, sec#, building#, room#)
Identify candidate keys in each of the above relations

Dr. Ejaz Ahmed 23


Question: With one CNIC, there may be many consumer nos (houses/
shops) , explain? Dr. Ejaz Ahmed 24
Candidate Key during search

DBA can create Index on searching attributes (candidate Keys) 25


Candidate Key during search …

Dr. Ejaz Ahmed 26


Dependents

For example: Dependent means family


members (wife, son, daughter etc.), who are
depend on father. Father is an employee in
some organization

Dr. Ejaz Ahmed 27


Primary Keys
• A primary key is a candidate key selected as
the primary means of identifying rows in a
relation:
– There is one and only one primary key per
relation
– The primary key is NOT NULL, UNIQUE
– The ideal primary key is short, numeric(alpha),
indexed, fixed length and never changes
– Key that has its ownership of an Enterprise
– The primary key may be a composite key

Any drawback or weakness of PK? 28


Primary Keys cont….

Although, candidate keys are STU_ID, CIT_ID. Organization ITSELF issues its own
identifier PK. PK is a property of an organization. Driving license# is a property of
Ministry of Motors/ transportation, it must not be used PK in university or other
organizations. It is a candidate key for other organization for search purposes.
Note: It is not recommended to create PKs for columns like Quantity, Salary, Price
and column that has datatype DATE 29
Primary Keys cont…
Example-1:
STUDENT(StuID, FirstName, FamilyName, DOB, …)

Example-2: Building (B#, BName, Location, Region),


B# is a primary key. Although, BName is unique, not null but it is not short.

Example-3: Customer (cname, citizenid, address, city, telno)


This relation indicates the information about personal details. There is a chance
that cname is duplicated, some may have citizenid and telno as null. This forces
us to introduce new a attribute such as cust# that would be a primary key.
Customer (cust#, cname, citizenid, address, city, telno)
Example-4:
BankBranch(Branch-Name, City, TotalAsset)

• What will be a PK that you will suggest?


• What is a candidate key?
• Which attribute is unique

• There may be many branches in one city then finalize this relation with possible
constraints

30
Primary Keys …

V_Name can be candidate key to provide fewer records during search


31
Primary Key Instances - Samples
512235665 Social Security Number
610112654 (By Birth Asian, Europian, HomeLand)

200338900 Student ID (With Registration year)

DMM051 Product ID (with Manufacturing Loc, branches)


JUB004

312668852369 Bank Account# (followed by Branch Code)

100211 SKU# (By Category) or a barcode


300411

Serial# Serial# starts with 1 and incremented by 1

005384 Company has many branches with code 005, 007 etc.,
007004 invoices issued from branches are recognized with branch codes

Dr. Ejaz Ahmed 32


PK used in Apps SAP & as IBAN - Fixed Length

33
Use of PK or Indexing

Dr. Ejaz Ahmed 34


World Population 7.9 Billions

Dr. Ejaz Ahmed 35


Surrogate Keys
• A surrogate key as an artificial column
added to a relation to serve as a primary
key:
– DBMS supplied
– Short, numeric and never changes – an ideal
primary key!
– Has artificial values that are meaningless to
users
– Normally hidden in forms and reports

Dr. Ejaz Ahmed 36


Surrogate Keys cont….
NOTE: The primary key of the relation is underlined below:
• RENTAL_PROPERTY without surrogate key:

RENTAL_PROPERTY (Street, City,


State/Province, Zip/PostalCode, Country, Rental_Rate)

• RENTAL_PROPERTY with surrogate key:


RENTAL_PROPERTY (PropertyID, Street, City,
State/Province, Zip/PostalCode, Country, Rental_Rate)

Other examples include Invoice#, ComplaintRef#

Dr. Ejaz Ahmed 37


Surrogate Keys …
• ATM card is being used in machine to
draw some amount as a transaction.

Attributes will be
Card#, Amount, DrawDate

(Card will be used many times)

Dr. Ejaz Ahmed 38


Surrogate Keys …

Introducing column as a Surrogate Key

ATMTransaction (Card#, Serial#, Amount, DrawDate)

Need more attributes

What about if DrawDate is a surrogate key

Dr. Ejaz Ahmed 39


Surrogate Keys cont….
Other examples include
Invoice#

ComplaintRef#

ATMTransaction (Card#, Serial#, Amount, TransDate, TransType)

InsurancePaid(Policy#, PaidYear, PaidDate, VehicleReg#, Amount)

Dr. Ejaz Ahmed 40


ATM Transaction Sample

Dr. Ejaz Ahmed 41


Surrogate Keys cont….

Dr. Ejaz Ahmed 42


Surrogate Keys cont….

Dr. Ejaz Ahmed 43


Example – End User View

Dr. Ejaz Ahmed 44


Example – End User View …

Dr. Ejaz Ahmed 45


Foreign Keys (FK)
• A foreign key is an attribute that refers to a
primary key of same or different relation to
form a link (constraint) between the relations:
– A foreign key can be a single column or a
composite key
– The term refers to the fact that key values are
foreign to the relation in which they appear as
foreign key values
– Ideally Data type, Length/ Size of FK and referring
PK must be same
Dr. Ejaz Ahmed 46
Foreign Keys
NOTE: The primary keys of the relations are underlined and any foreign keys
are in italics in the relations below:
Name of FK column may be different from the name of referencing PK

Example-1:
DEPARTMENT (DeptID, DepartmentName, BudgetCode, ManagerName)
EMPLOYEE (EmployeeNumber, EmployeeName, DeptID)

Dr. Ejaz Ahmed 47


Customer-Sales Orders

48
Customer-Sales Orders

Example-2:
CUSTOMER(CustId, Name, Address, Telno, Email)
ORDERS(Invoice#, InvType, InvDate, Empno,CustomerId)

Can we call Invoice# as a Surrogated Key?


Does Invoice# always contain serial numbers?
Dr. Ejaz Ahmed 49
Foreign Key with a
Referential Integrity Constraint

Dr. Ejaz Ahmed 50


Foreign Key with a
Referential Integrity Constraint

Dr. Ejaz Ahmed 51


Creating Foreign Key in
MS Access & Oracle

Dr. Ejaz Ahmed 52


FK and Recursive Relationship

Dr. Ejaz Ahmed 53


Recursive Relationship - Example

Part (Part#, PName, Weight, MakeYear, Price, PType, RefPart#)


PType: Assembled product/ parts (e.g., Motorcycle) or single part

Datasets? Dr. Ejaz Ahmed 54


The Referential Integrity Constraint
• A referential integrity constraint is a
statement that limits the values of the
foreign key to those already existing as
primary key values in the corresponding
relation

Dr. Ejaz Ahmed 55


Foreign Key with a
Referential Integrity Constraint
NOTE: The primary key of the relation is underlined and any
foreign keys are in italics in the relations below:

ITEM (Item#, Item_Name, Department, Buyer, Price, TotalQTY)


ORDER_ITEM (OrderNumber, Item#, Quantity, Price, ExtendedPrice)

Where ORDER_ITEM.ITEM# must exist in ITEM.ITEM#


OrderNumber is an alternate name of InvoiceNumber

Datasets? Dr. Ejaz Ahmed 56


Integrity (Fig. from C.J. Date)
S# SNAME STATUS CITY S# P# QTY
S SP
S1 Smith 20 London S1 P1 300
S2 Jones 10 Paris S1 P2 200
S3 Blake 30 Paris S1 P3 400
S4 Clark 20 London S1 P4 200
S5 Adams 30 Athens S1 P5 100
S1 P6 100
S2 P1 300
P# PNAME COLOR WEIGHT CITY S2 P2 400
P P1 Nut Red 12 London S3 P2 200
P2 Bolt Green 17 Paris S4 P2 200
P3 Screw Blue 17 Rome S4 P4 300
P4 Screw Red 14 London S4 P5 400
P5 Cam Blue 12 Paris
P6 Cog Red 19 Ahmed
Dr. Ejaz London 57
Master/ Parent – Child Tables
Master Tables
DEPARTMENT (DeptID, DeptName, BudgetCode, ManagerName, Loc, TelNo)
CUSTOMER(CustId, Name, Address, Telno, Email)
Part (Part#, PName, Weight, MakeYear, Price, PType, RefPart#)
Product (Item#, Name, Price, Department, Buyer)
Course(CourseID, Name, CrHrs)
Semester(SemID, StartDate, EndDate, SGPA)
Student(StuId, FName, LName, DOB, NIC#, Address, City, Telno, Deptno)
Patient(PatID, FName, LName, DOB, Address, City, Telno, NIC#, PType)
ATM(Machine#, MName, MType, Size, Brand, Colour)

Some of the above table’s and their Child Tables (FK with and without Comp. Keys)
CourseReg(StuID, SemID, CourseID, Sec#, Grade)
PatientVisit(PatID, DependSNO, VisitSNO, VDate, DocID, Diagnosis, VStatus)
EMPLOYEE(EmpNo, EmpName, DOB, Addr, City, TelNo, Job, HireDate, DeptID)
ATMTransaction (Card#, Serial#, Amount, TransDate, TransType, Machine#)
Dr. Ejaz Ahmed 58
Integrity Rules
• Entity integrity
– No two rows with the same primary key value
– No null values in a primary key
• Referential integrity
– Foreign keys must match candidate key of
source table
– Foreign keys in some cases can be null
– The database must not contain any unmatched
foreign key values.
– If B references A, A must exist.
Dr. Ejaz Ahmed 59
Integrity Constraints in Schema

Representation of standard constraints


60
Referential Actions (Cont.)
• When we update a tuple from a table, say S,
that is referenced by another table, say SP,
• There are similar choices of referential actions
for update and delete:
– ON UPDATE CASCADE
– ON UPDATE RESTRICT
– Use with SQL Drop Table command
• There could be other choices besides these
three. , e.g.,
– ON UPDATE SET DEFAULT.
– ON UPDATE SET NULL.
Dr. Ejaz Ahmed 61
Composite Keys

Any drawback or weakness of CompKey? 62


Composite Keys …
Course(CourseID, Name, CrHrs)
Semester(SemID, StartDate, EndDate)
Student(StuId, FName, LName, DOB, …)

Courses are issued/ offerred or allocated for registration

CourseIssue(SemID, CID, Sec#, InstID, B#, R#, Days, Time, MaxStu)

Students will register in issued courses:

CourseReg(StuID, SemID, CID, Sec#, Grade)


(Student can see instructor of course by using SQL, SemID, CID and
Sec# will be FK refer to CourseIssue)

XL file of course offering! 63


Meaningful Learning
• Analysis and Semantics
• Evaluations

Semantics: Creating two tables with relevant data


Analysis: Y.x=1 cannot be mapped exactly with
X.x records 1, 3 or 1, 6

Evaluations: Default FK Y.x cannot be created.


Trigger can be created on Y.x to make sure Y.x will
be a subset of X.x. Otherwise, data can be put in Y.x
which does not belong to or mapped to X.x.

Dr. Ejaz Ahmed 64


Composite Key…

Meaningful Learning?

Dr. Ejaz Ahmed 65


Composite Key …

How data is shown to a user?

How data is stored in a table?

SKU: Stock Keeping Unit or Prod#


Dr. Ejaz Ahmed 66
Composite Keys and Foreign Keys
PatientVisit(PatID, VisitSNO, Vdate, DocID, Diagnosis,…)

PatLabTest(PatID, VisitSNO, TestID, Tdate, …)

PatLabTest has FKs PatID, VisitSNO, referring to same


corresponding composite keys in PatientVisit

Datasets?
Dr. Ejaz Ahmed 67
Indexing Columns – Comp. Keys

Dr. Ejaz Ahmed 68


Other or Additional Constraints
Null: Represents a value of an attribute that is currently unknown or is no
applicable for this tuple, means nothing.

Entity integrity Constraint: In a base relation, no attribute of a primary key


(PK) can be null.

Referential Integrity Constraint: If a foreign key (FK) exists in a relation,


either the foreign key value must match a candidate key (or PK) value of
some tuple in its home relation or the foreign key value must be wholly null.

Domain Constraint: Specifies that the value of attribute A must be an atomic


value from the domain DOM(A). E.g., Width of column or Check on column.

Additional Constraints: Default, NOT NULL, UNIQUE(Unique Key), CHECK;


Business Constraints using DB triggers and client’s programming. For
performance Indexes are also constraints.

Dr. Ejaz Ahmed 69


Type or Domain Constraints …
• The check clause in SQL permits domains to be
restricted:
– Use check clause to ensure that an hourly-wage
domain allows only values greater than a specified
value.
– create domain hourly-wage numeric(5,2)
constraint value-test check(value > = 4.00)
– The domain hourly-wage is declared to be a decimal
number with 5 digits, 2 of which are after the decimal
point
– The domain has a constraint that ensures that the
hourly-wage is greater than 4.00

Dr. Ejaz Ahmed 70


Attribute Constraints
• An attribute constraint is just a declaration to the effect
that a specified attribute is of a specified type.
• For example:
create table BRANCH
(branch_code CHAR(10),
Branch_name VARCHAR2(15),
Assett NUMBER(10) not null,
bal NUMBER(10,2),
……);
alter table BRANCH
add constraint chk_acc_bal check (bal >= 0); --integrity constraint
• Attribute constraints are part of the definition of the
attribute.
• Any attempt to introduce an attribute value into the
database that is not a type of the relevant type will simply
rejected.
–Such a situation should never arise.
Dr. Ejaz Ahmed 71
Table Constraints
• A table constraint is a constraint on an individual
table.

• Example:
– Suppliers in London must have status 20.
– Two attributes, CITY and STATUS, of table S are
involved.
– GPA cannot exceed 4.00

Dr. Ejaz Ahmed 72


Other Constraints Examples
Unique constraint can be applied on single or multiple columns

CHECK (Max_Participants>=Enrolled_Participants)
CHECK (Deptno>0)
CHECK (RelType IN ('S', 'D', 'W'))
Default 'Y‘
Database Triggers

Dr. Ejaz Ahmed 73


END

Dr. Ejaz Ahmed 74

You might also like