DBMS Module I - Merged
DBMS Module I - Merged
INTRODUCTION
Data (used as both singular and plural) is the known fact that can be recorded and have
implicit meaning.
Information is the refined data. When data is processed and presented in a form
suitable for human interpretation, it is called information. Data is the raw material and
information is the finished goods.
For Example: A list of students showing Regd. No, Name, Address, Course, Marks
obtained in each paper is called student’s data.
Data base: A collection of logically interrelated data stored together with controlled
redundancy to meet the needs of an organization is called database.
Components of Database:
Example: Banking system is an example of DBMS which keeps information about the
customers and has a number of application programs:
Dr. A. K. Panda
2
Advantages of DBMS:
Dr. A. K. Panda
3
design.
5. It is not secure It is more secure.
6. It is often single user oriented It is multiple user oriented.
7. It has isolated data It has shared data.
8. It has simple primitive It has complex and sophisticated
backup/recovery mechanism backup/recovery.
Characteristics of DBMS:
1. Self describing nature of DBMS: A database system contains not only the
database itself but also a complete definition or description of the database
structure and constraints. This definition is called metadata i.e. data about data
which is stored in a catalog called data dictionary. Hence data dictionary is a
data structure that stores metadata.
2. Data independence and data abstraction: In DBMS there is insulation between
data and programs called program-data independence. Hence data can be
changed without changing application programs. A DBMS provides users with a
conceptual representation of data that does not include many of the details of
how the data is stored or how the operations are implemented. This is called
program-operation independence. The characteristic that allows program-data
independence and program-operation independence is called data abstraction.
3. Support of multiple views of the data: A database typically has many users,
each of whom may require a different perspective or view of the database. A
view is a virtual data that is derived from the database files. Users may not need
to aware of whether the data they refer to is stored derived. A multiuser DBMS
provides different views for multiple users of the same database.
4. Data sharing and multiuser transaction processing: A multiuser DBMS allow
multiple users to access the database at the same time. A concurrency control
s/w is loaded to control multiple transactions.
Components of DBMS:
The database management system can be divided into five major components, they are:
1. Hardware: Hardware consists of hard disks, I/O channels for data, and any
other physical component involved before any data is successfully stored into
the memory.
2. Software: It is a set of programs which is used to work with such hardware
3. Data: It is the fact that can be recorded.
4. Procedures: It is the set of instructions in a certain order to achieve desired
results.
5. Database Access Language: It is a simple language designed to write
commands to access, insert, update and delete data stored in any database.
Dr. A. K. Panda
4
An individual person or group of persons having central control over DBMS is called
DBA. They are the persons who are most familiar with the database and responsible for
creating, modifying and maintaining three levels of database. The DBA is also
responsible for authorizing access to the database, coordinating and monitoring its use
and acquiring software and hardware resources as needed.
Functions of DBA:
2. Database Designers:
3. Application Programmers:
4. End-Users:
The end-users are the clients for the database, which has been designed and
implemented. There are two types of end-users:
Dr. A. K. Panda
5
1. Naïve users: There users are typically unaware of the DBMS. They access the
database through specially written application programs. They invoke database
operations by entering simple commands or choosing options from the menu.
They do not know anything about the database.
2. Sophisticated users: These users are familiar with the structure of the database
and the facilities offered by the DBMS. Sophisticated users may use a high level
query language such as SQL to perform the required operation.
Schema: The overall description of the database is called as database schema. It is also a
plan or outline that describes the records at a particular level.
Employee
Department
Dr. A. K. Panda
6
Subschema: A subschema (or, scheme) is a subset of the schema and inherits the same
property that a schema has. It is an application programmer’s or, user’s view of the data
item types and record types. It gives the users a window through which he or, she can
view only part of the databases.
Fig: Subschema viewed by two application programs derived from above schema.
Instance: The collection of information stored in the database at any point of time is
called as an instance of the database.
Dr. A. K. Panda
7
Physical Data
Organization Database
1. External Level: This level describes the part of the database that is relevant to
each user.
2. Conceptual level: This level describes what data is stored in the database and
the relationships among the data.
3. Internal Level: This level describes how data is stored in the database.
Data Independence:
It means that upper levels are unaffected by changes in lower levels. It is achieved
through use of three levels of data abstraction.
Dr. A. K. Panda
8
DATA MODEL
Dr. A. K. Panda
9
Data Model
2. Physical data model: It provides concepts that describe the details of how data
is stored in the computer. Concepts provided by physical data models are
generally meant for computer specialists, not for the typical end-users. Physical
data models describes how data is stored as files in computer by representing
information such as record format, record orderings, and access paths. EX:
unifying model, frame memory model.
Hierarchical Model:
A hierarchical data model is a data model which the data is organized into a tree like
structure with one-to-many relationships between different types of data. The structure
allows repeating information using parent/child relationships: each parent can have
many children but each child only has one parent. All attributes of a specific record are
listed under an entity type.
Dr. A. K. Panda
10
Network Model:
The data in the network model are represented by collection of records and
relationships among data are represented by links, which can be viewed as pointers.
The main difference between this model and the hierarchical model is that any record
can have several parents in the network model. It uses a graph instead of a hierarchical
tree. This data model is used to map many-to-many relationship.
Relational Model:
The Relational Model uses a collection of tables both data and the relationship among
those data. Each table have multiple columns and each column has a unique name.
ENTITY-RLATIONSHIP MODEL
Entities
Attributes
Relationships
Entity: An entity is a person, place, object, event or concept that is uniquely identifiable.
An entity is called entity instance or entity occurrence.
Entity type (or set): It is a collection of entities that share common properties or
characteristics.
Dr. A. K. Panda
11
Example:
Classification of attributes:
An attribute that cannot be broken down into smaller components that are meaningful
for the organization is called simple attribute or atomic attribute.
Dr. A. K. Panda
12
An attribute that holds a single value for a single entity is called single-valued attribute
and an attribute that holds multiple values for a single entity is called Multivalued
attribute.
An attribute whose value is derived from value of another attribute is called derived
attribute and from which it is derived is called stored attribute.
An attribute that must be present for each entity instance is called a required attribute,
whereas an attribute that may not have a value is called an optional attribute.
Attribute Domain: Every attribute has a domain. A domain determines the type of data
values that are permitted for that attribute.
Dr. A. K. Panda
13
KEYS:
Super Key: An attribute or, a set of attributes that uniquely identifies an entity
in the entity type is called Super Key.
Candidate Key: A super key is said to be a candidate key if no proper subset of it
is a super key. That means minimal super key is called candidate key.
Primary Key: An entity type may have one or more possible candidate keys, one
of which is selected to be primary key. Database designer selects one of the
candidate key as primary key.
Composite key or concatenated key: A primary key that consists of two or
more attributes is called a composite key.
Alternate key: A candidate key that is not selected as primary key is called an
alternate key.
Secondary key: An attribute or, a set of attributes that is used to identify the
entities which have a certain property is called secondary key.
Relationship:
It is an association between instances of one or more entity types that is interest to the
organization.
Relationship type:
Degree of a Relationship:
It is the number of entity types that participate in that relationship. The three most
common relationship degrees in E-R models are unary (degree 1), binary (degree 2),
and ternary (degree 3).
PERSON
EMPLOYEE
Is married
to
Manages
Dr. A. K. Panda
14
STUDENT Registers
COURSE
for
Quantity
PART
Hours
TEACHER
Structural Constraints:
1. Cardinality Constraint:
It specifies the number of instances of one entity that can be associated with each
instance of another entity. There are three basic types of cardinality constraints:
Dr. A. K. Panda
15
1 1
A R B
M N
A R B
2. Participation Constraint:
It specifies whether the existence of an entity depends on its being related to
another entity via the relationship type. There are two types of participation
constraints:
The participation is said to be partial (Optional) if the occurrence of one entity does not
require the occurrence of another corresponding entity in a relationship.
Example:
3. MIN/MAX Constraints:
The participation of an entity type in relationship type can be associated by a
pair of integers (MIN, MAX) as follows:
(MIN, MAX)
A R
Dr. A. K. Panda
16
It means that each entity instance of the entity type A participates in at least MIN
and at most MAX relationship instances at any point of time.
Note: If MIN = 0, then the participation is partial and if MIN > 0, then the
participation is total.
Example:
(1, 1) (4, N)
EMPLOYEE Works for DEPARTMENT
Each employee works for at least one department and at most one department and
each department have at least 4 employees and at most unlimited employees.
The entity type that does not have sufficient attributes to form a primary key is
called a weak entity type. On the other hand, an entity type that has a primary key is
called strong entity type.
Note: The participation of weak entity type is always total but the converse is not
true.
Example:
EMPLOYEE Claims DEPENDENT
Identifying Relationship:
A relationship in which the primary key of the parent entity is used as a part of the
primary key of the dependent entity is called identifying relationship.
Representation in ERD:
Partial Key:
It is a set of attributes that uniquely identify weak entities that are related to the
same owner entity.
Dr. A. K. Panda
17
Representation in ERD:
Example:
City
Street
Ename
Sex
Empid State Dname Birth date
Addres
s (1, 1)
(0, N)
EMPLOYEE Claims DEPENDENT
3. Attribute
4. Multi-valued Attribute
5. Derived Attribute
…
8. Composite Attribute
9. Relationship
Dr. A. K. Panda
18
1 1
14. E1 R E2 One-to-One relationship
1 N
15. E1 R E2 One-to-Many relationship
M N
16. E1 R E2 Many-to-Many relationship
(MIN, MAX)
17. E R MIN/ MAX Constraint
Example:
Draw an ER diagram of book club. The book club has members. The book club sells
books to its members. The members place orders for books, which the book club
fulfils. Each order contains one or more than one book. An author can write more
than one book and a book can have more than one author. A book is published by a
publisher but a publisher publishes many books. The book club sells many books.
(1, 1) (1, N)
MEMBER Enrolls in BOOK_CLUB
AUTHOR
Fulfils
Places
Sells (1, N)
(1, 1)
(1, 1) (1, N)
(1, 1)
ORDER
BOOK Writes
(1, 1)
(1, N)
(1, 1)
Publishes
(1, N)
Contains PUBLISHER
Dr. A. K. Panda
19
Controls
(1, 1)
Supervises (1, N)
Works on PROJECT
Proj-id Location
Hours Pname
Dr. A. K. Panda
20
Locality City
Plot-No State
Locality City
M N
CUSTOMER Cust-Banker EMPLOYEE Manages
1
1
N
Balance
Deposits ACCOUNT
A/C-No
N
Borrows
Transaction-Date
Opens
N 1
Loan-No N 1
LOAN Loan-branch BRANCH
Amount 1
Branch-Name Assets
City
Loan
Payment
PAYMENT
Payment-No Payment-Date
Payment-Amount
Dr. A. K. Panda
21
Dr. A. K. Panda
22
The EER model consists of all the concepts of E-R model together with the following
additional concepts:
Specialization
Generalization
Categorization
Supertype or, Superclass: It is a generic entity type that has a relationship with one or
more subtypes.
Example:
Shared Attributes
SUPERTYPE
Dr. A. K. Panda
23
Attribute Inheritance:
It is a property by which subtype entities inherit values of all attributes and instance of
all relationships of the Supertype.
Specialization:
Pname S
Patient-id Admin-Date P
G E
E C
PATIENT
N I
E A
R L
A I
L Z
I A
Z T
INPATIENT OUT-PATIENT
A I
T O
I N
O
N Check-back-Date Date-discharged
Generalization:
Participation constraint
Disjointness constraint
Dr. A. K. Panda
24
Participation Constraint:
Total Participation
Partial participation
Total participation constraint: It specifies that each entity of the supertype must be a
member of some subtype in the Specialization/ Generalization.
Representation in ERD:
SUPERTYPE
Example:
Ename
Empid Address
EMPLOYEE
It specifies that a member of the Supertype need not belong to any of its subtypes of a
specialization/generalization.
Dr. A. K. Panda
25
Example:
Make Model
V-Name Engine-No
Vehicle-No Chassis-No
VEHICLE
Disjointness Constraint:
Disjoint Constraint
Overlapping constraint
Disjoint Constraint:
Representation in ERD:
SUPERTYPE
Dr. A. K. Panda
26
Example:
Name
A/C-No Address
ACCOUNT
Overlapping Constraint:
Representation in ERD:
SUPERTYPE
Example:
Ename Description
Empid Salary Part-No Type
EMPLOYEE PART
O
O
Routine-No Unit-Price
Dr. A. K. Panda
27
Disjoint, total
Disjoint, partial
Overlapping, total
Overlapping, partial
Example:
Name
Person-id Address
PERSON
O
Major
Date-hired
Year
Section
Regd-no
FACULTY STAFF GRADUATE UNDER GRADUATE
Rank Position
CGPA Percentage
Categorization:
It is the process of modeling of a single subtype (or subclass) with a relationship that
involves more than one distinct supertype (or superclass).
…
Representation in ERD: Supertype-1 Supertype-2 Supertype-n
Example:
EMPLOYEE DEPARTMENT COMPANY
OWNER
Total-Cost
I-code Unit-Price
Name
T-Code Price
N
Is billed ITEM
for TEST
Name Specialty
Name
Phy-id
Patient-id Admit-date Tel-No
M
PATIENT Advices PHYSICIAN
Age [Link]
Name
d
Prescribes
DRUG
OUT-PATIENT IN-PATIENT 1
Date Quantity N
Company
Checkbackdate Discharge-date
[Link] Name
Type 1 Price
ROOM PHARMACY
Treat-Code Room-No Bed-No
Roomid
TREATMENT Treats
Date Result
Description Time
Dr. A. K. Panda
RELATIONAL DATA MODEL
The relational model was first introduced in 1970 by Dr. E. F. Codd of IBM. The relational model
represents data in the form of tables.
Relation: It is a named two dimensional table of data with rows and columns.
Attribute: It is a named column of a relation.
Domain: It is a set allowable value of an attribute.
Tuple: It is a row of a relation.
Degree: The degree of a relation is the no. of attributes it contains.
Cardinality: The cardinality of a relation is the number of tuples it contains.
Relational Database: It is a collection of normalized or structured relations with distinct
relation names.
Types of Keys:
Super key: An attribute or, a set of attributes that uniquely identifies a tuple with in a
relation is called Super Key.
Candidate Key: A super key is said to be a candidate key if no proper subset of it is a
super key. That means minimal super key is called candidate key.
Primary Key: A relation may have one or more possible candidate keys, one of
which is selected to be the primary key. Database designer selects one of the candidate key
as primary key.
Composite key or concatenated key: A primary key that consists of two or more
attributes is called a composite key.
Alternate key: A candidate key that is not selected as primary key is called an
alternate key.
AK = CK - PK
Secondary key: An attribute or, a set of attributes that is used to identify the entities
which have a certain property is called secondary key.
Foreign key: An attribute in a relation that serves as the primary key of another relation is
called in the same database is called foreign key.
Properties of relations:
Integrity Constraints:
Relational data model includes several constraints whose purpose is to maintain the accuracy and
integrity of the data in the database. The major types of integrity constraints are:
Domain constraint (Check): It specifies that the value of each attribute A must be atomic
value from the domain of A.
Key constraint (unique): It specifies that all tuples in a relation must be distinct.
Entity Integrity constraint (not null): It specifies that primary key cannot accept null
values.
Referential Integrity Constraint (Foreign key): It specifies the value of the referencing
attribute (Foreign key) is either null or it is equal to value of the referenced attribute.
Example:
In the referencing relation EMPLOYEE, value of the referencing attribute Dept-id is either null or it takes
any value of the Dept-id column in DEPT relation.
Query Languages:
A query language is a language in which user requests information from the database. Query languages
can be categorized as either procedural or non-procedural.
Procedural language: In a procedural language the user instructs the system to perform a
sequence of operations on the database to compute the desired result (e.g. relational algebra).
Non-procedural language: In a non-procedural language, the user describes the desired
information without giving a specific procedure for obtaining that information (e.g. tuple calculus
and domain calculus).
Dr. A. K. Panda
RELATIONAL ALGEBRA
It is a procedural query language. It consists of a set of relational operators that takes one or more
relations as input and produces a new relation as its result.
Unary operations:
1. Select ()
2. Project ()
3. Assignment ()
4. Rename()
Binary operations:
Set theoretic operations:
5. Union (U)
6. Intersection()
7. Difference (-)
8. Cartesian product (×)
Other binary operations:
9. Join (⋈)
10. Division(÷)
The select operator () is used to extract specified rows from a table that satisfies a selection condition.
The result of it is a horizontal subset of the relation.
Example:
Dr. A. K. Panda
Q: Get all departments of location north:
Location = ‘north’ (Dept)
The project operator () is used to extract specified columns from a table. The result of it is a vertical
subset of the relation.
Example:
Name (Employee)
The assignment operator () is used to assign part of a relational expression into temporary relation
variable. This relation variable may be used in subsequent expressions.
Example:
Q: Get the name and address of all female employees who work in dept-no 5:
The rename operator () is used to rename either the relation names or, the attribute names or, both.
Dr. A. K. Panda
General form 2: (B1, B2, …, Bn) (R): It renames attribute Ai as Bi for i = 1 to n.
General form 3: S (B1, B2, … , Bn) (R): It renames attribute Ai as Bi for i = 1 to n and relation R as
S.
Example:
Emp (Employee)
Q: Find the name and salary of all employees and rename the new relation as Esal and name as
Ename and salary as sal.
The union, intersection and difference operations between two relations R 1 and R2 are valid if the
following conditions are satisfied.
The union of two relations R1 and R2 denoted by R1 U R2 is a relation that includes all tuples that appear
either in R1 or, in R2 or, in both.
Dr. A. K. Panda
R 1 R2 Emp-no Name Phone
The intersection of two relations R1 and R2 denoted by R1 R2 is a relation that includes only those tuples
that appear in both of R1 and R2.
The difference of two relations R1 and R2 denoted by R1 - R2 is a relation that includes only those tuples
that appear in R1 but not in R2.
The Cartesian product (×) of two relations is the concatenation of tuples belonging to two relations.
Dr. A. K. Panda
R1 Emp-no Name Phone R3 Dept-no D-name
001 Ashok 9437091129 D1 Mca
002 Satya 9437229391 D2 Mba
003 Sunil 8895730489
Example:
R3 R1 × R2
The join operator (⋈) is used to combine related tuples from two relations into single tuples. It is the
combination of Cartesian product and selection. There are various forms of join operations such as theta
join, equijoin, natural join, semi join, and outer join.
Theta join (-join) is used to define a relation that contains tuples satisfying the predicate F from the
Cartesian product of two relations.
General Form:
2. Equijoin:
Example:
Q: Get the name of all employees who work for the department located at south.
Dr. A. K. Panda
3. Natural Join (⋈):
The natural join operator performs a Cartesian product of two relations, performs a selection forcing
equality on those attributes that are common to two relations and finally removes duplicate attributes. It
performs an equijoin over all the attributes in two relations that have the same name.
Example:
R A B C S C D E A B C D E
R⋈ S
a1 b1 c1 c1 d1 e1 a1 b1 c1 d1 e1
a2 b2 c2 a3 b3 c3 d2 e2
c3 d2 e2
a3 b3 c3
c4 d3 e3
a5 b4 c5
c6 d4 e4
Example:
Express the following queries in relational algebra for the given schema of the above example:
R1 Employee ⋈ Dependent
Q: Get the name of all employees who work for the department located at north.
R1 Employee ⋈ Dept
The semi join operator (⊳) performs a natural join of two relations and then projects over the attributes
of the first operand. The advantage of semi join is that it decreases the number of tuples that need to be
handled to form the join.
Dr. A. K. Panda
General form: R⊳S
Example:
R A B C S C D E A B C
R⊳S
a1 b1 c1 c1 d1 e1 a1 b1 c1
a2 b2 c2 a3 b3 c3
c3 d2 e2
a3 b3 c3
c4 d3 e3
a5 b4 c5
c6 d4 e4
Example:
Express the following query in relational algebra for the given schema of the above example:
Q: Get the information of all employees who work for the department located at north.
5. Outer join:
The outer join operation is an extension of the join operation to deal with missing information. There are
three forms of the operation: left outer join ( ), right outer join (⋉) and full outer join ( ).
The left outer join ( ) is a join in which the tuples from the left relation that do not have matching values
in the common attributes of the right relation are also included in the result relation. Missing values in
the right relation are set to null.
The right outer join ( ) is symmetric with the left outer join. It is a join in which the tuples from the
right relation that do not have matching values in the common attributes of the left relation are also
included in the result relation. Missing values in the left relation are set to null.
R S = (R S) U (R S).
Dr. A. K. Panda
A left outer join keeps every tuple in the left relation in the result. Similarly, a right outer join keeps every
tuple in the right relation in the result. A full outer join keeps all tuples in the both relations, padding
tuples with nulls when no matching tuple are found.
Example:
R A B C S C D E A B C D E
R⋈ S
a1 b1 c1 c1 d1 e1 a1 b1 c1 d1 e1
a2 b2 c2 a3 b3 c3 d2 e2
c3 d2 e2
a3 b3 c3
c4 d3 e3
a5 b4 c5
c6 d4 e4
R S A B C D E
a1 b1 c1 d1 e1
a2 b2 c2 Null null
a3 b3 c3 d2 e2
a5 b4 c5 Null null
R S A B C D E
R S A B C D E
a1 b1 c1 d1 e1
a1 b1 c1 d1 e1
a3 b3 c3 d2 e2 a2 b2 c2 Null null
Null Null c4 d3 e3 a3 b3 c3 d2 e2
Null Null c6 d4 e4 a5 b4 c5 Null null
Null Null c4 d3 e3
Null Null c6 d4 e4
Dr. A. K. Panda
Division operation ():
The division relation divides a dividend relation R of degree (m + n) by a divisor relation S of degree n
and produces a resultant relation of degree m.
Let Z be the set of attributes of R and X be the set of attributes of X, then set of attributes of R S is Z – X.
A tuple t is in R S if for every tuple ts in S there is a tuple tr in R satisfying the following two conditions:
tr [X] = ts [X]
tr [Z – X] = t [Z – x]
This means that the tuple t will appear in R S if t appears in R in combination with every tuple in S.
R A B S B RS A
a1 b1 b1 a1
a1 b2 b2 a3
a1 b3 b3
a2 b1
a3 b1
a3 b2
a3 b3
a4 b3
Aggregate Functions:
Aggregate functions take collection of values and return a single value as a result. These functions are
used in simple statistical queries that summarize information from the database tuples. Common
aggregate functions are COUNT, SUM, AVG, MAX and MIN
General form:
Dr. A. K. Panda
Example:
Q: Retrieve each department number, the number of employees in the department and their
average salary:
R(Dno, No-of-employees, average-sal) (Dno, ℱ COUNT Eno, AVGsalary(EMPLOYEE))
Q: Find number of employees and maximum salary of all employees:
ℱ COUNT Eno, MAXsalary(EMPLOYEE)
Q: Count number of departments:
ℱ COUNT Dno (DEPT)
Relational algebra consists of operations to add, delete and update information in a database. The
modification operations are expressed using the assignment operation.
1. Deletion:
RR–E
Where R is the existing relation and E is the relational algebraic expression to select required tuples to be
deleted.
Example:
2. Insertion:
Where R is the relation to which the tuples to be inserted and E is either a specified tuple to be inserted
or it is a relational algebraic expression whose result is a set of tuples.
Q: Insert the fact that mathematics department having department number d5 is opened in the
location south.
Q: Assume that there exist a relation ‘Emp’ having same field as Employee to keep information of
part time employees. Insert the employees of department d2 of table emp to employee.
3. Updating:
where each Fi is either the ith attribute of R, if the ith attribute is not updated or, if the ith attribute is to be
updated, Fi is an algebraic expression involving only constants and the attributes of R, that gives the new
value for the attribute.
Exercises
Dr. A. K. Panda
e) Get name of suppliers who supply all parts.
f) Get supplier numbers for suppliers who supply at least all those parts supplied by supplier
S2.
g) Get supplier names for suppliers who do not supply part P2.
h) Get full details of all projects in Mumbai.
i) Get supplier number for suppliers who supply project j1.
j) Get all shipments where the quantity is in the range 300 to 750 inclusive.
k) Get part number for parts supplied by a supplier in Mumbai to a project in Mumbai.
l) Get all pairs of city names such that a supplier in the first city supplies a project in the
second city.
m) Get part number for parts supplied to any project by a supplier in the same city as that
project.
n) Get project numbers for projects supplied by at least one supplier not in the same city.
o) Get the total number projects supplied by supplier S1.
p) Get the total quantity of part P1 supplied by supplier S1.
q) For each part being supplied to a project, get the part number, the project number, and the
corresponding total quantity.
r) Get part numbers of parts supplied to some project in an average quantity of more than
350.
Solution:
c) Sname, Color (SUPPLIERS ⋈ (SHIPMENT ⋈ PARTS)) Color(color = ‘blue’ or color = ‘black’ (PARTS))
k) Pno (Sno (city = ‘Mumbai’ (SUPPLIERS)) ⋈ ((Jno (city = ‘Mumbai’ (PROJECTS)) ⋈ SHIPMENT))
l) City,City1 ((Sno = Sid Jno = Jid City City1) (Sno, Jno, City (SUPPLIERS ⋈ SHIPMENT) ((Sid, Jid, City1) (Sno,
Jno, City (PROJECTS ⋈ SHIPMENT)))) )
n) Jno ((Sno = Sid Jno = Jid City City1) (Sno, Jno, City (SUPPLIERS ⋈ SHIPMENT) ((Sid, Jid, City1) (Sno, Jno,
City (PROJECTS ⋈ SHIPMENT)))))
Exercise 2:
Dr. A. K. Panda
e) Find the names of all employees who live in the same city and the same street as do their
managers.
f) Find the names of all employees in this database who do not work for TCS.
g) Find the names of all employees in this database who earn more than every employee of
Infosys.
h) Assume that the companies are located in several cities. Find all companies located in every
city in which TCS is located.
i) Delete all tuples in the WORKS relation for employees of Infosys.
j) Modify the database so that Ashok now lives in Chennai.
k) Give all employees a 10% salary raise.
l) Find the sum of the salaries of all employees in the WORKS relation.
Solution:
c) person-name, street, city (salary > 500000 ^ company-name = ‘TCS’ (WORKS ⋈ EMPLOYEE)
Dr. A. K. Panda
Exercise 3:
Solution:
Dr. A. K. Panda
FUNCTIONAL DEPENDENCY & DECOMPOSITION OF A RELATION
Functional dependency:
It is a constraint between two attributes or two set of attributes of the same relation. Let r
be a relation and X and Y be arbitrary subset of set of attributes of r. Then we say that X
functionally determines Y or, Y is functionally dependent on X denoted by:
XY
if 𝑡1 [𝑋] = 𝑡2 [𝑋] then 𝑡1 [𝑌] = 𝑡2 [𝑌] for all pair of tuples t1 and t2 in r. In other words,
whenever two tuples of r agree on their X value, they also agree on their Y value.
The left side and right sides of an FD are called determinant and dependent respectively.
Note: Armstrong’s Axioms are sound and Complete, They are sound because for a given set
of functionally dependencies F, no additional FDs not implied by F can be derived by using
these axioms. They are complete because all FDs implied by F can be derived from F by
using these axioms.
Dr. A. K. Panda
Proof of Decomposition Rule:
1. X YZ (Assumption)
2. YZ Y (Using reflexive rule as Y YZ)
3. XY (From 1 & 2 and by using transitive rule)
4. YZ Z (Using reflexive rule as Z YZ)
5. XZ (From 1 & 4 and by transitive rule)
1. XY (Assumption)
2. XZ (Assumption)
3. X XY (From 1 and by Augmentation rule)
4. XY YZ (From 2 and by Augmentation rule)
5. X YZ (From 3 & 4 and by transitive rule)
1. XY (Assumption)
2. WY Z (Assumption)
3. WX WY (From 1 and by Augmentation Rule)
4. WX Z (From 3 & 2 and by transitive rule)
Let X be a set of attributes that appears in the left hand side of some functional
dependencies in F. Then the closure of X i.e. X + is the set of attributes that are functionally
determined by X.
Initialize X+ = X.
repeat
oldX+ = X+.
for each functional dependency Y Z in F do
if Y X+ then X+ = X+ U Z.
until (X+ = oldX+)
Dr. A. K. Panda
Example:
Compute closure {A, B}+ under the following set of functional dependencies F:
Solution:
Iteration 1:
Iteration 2:
Iteration 3:
Example:
Compute closure {B, C, D}+ under the following set of functional dependencies F:
Example: Compute the closure of {A, B}, i.e. {A, B} + under the set of functional
dependencies F = {AB C, BC AD, D E, CF B}
1. Set F = F – {A B}
2. Find closure of the determinant A i.e. A+ under F.
3. If the dependent B A+ then the FD: A B is redundant;
else A B is non-redundant.
Example:
Remove any redundant functional dependencies from the following set of functional
dependencies:
F = {A B, C D, AC E, BD E }
Solution:
1. F = F – {A B} = {C D, AC E, BD E }
A + = {A} which is not a super set of B.
Hence, A B is non-redundant.
2. F = F – {C D} = {A B, AC E, BD E }
C + = {C} which is not a super set of D.
Hence, C D is non-redundant.
Dr. A. K. Panda
3. F = F – {AC E} = {A B,C D, BD E}
{A, C} + = {A, B, C, D, E} which is a super set of E.
Hence, AC E is redundant.
4. F = F – {BD E} = {A B,C D, AC E}
{B, D} + = {B, D} which is not a super set of E.
Hence, BD E is non-redundant.
Cover:
Two set of functional dependencies E and F over a relation scheme R are said to be
equivalent if the closure of E is identically equal to the closure of F i.e. E + = F+.
Note: Two set of FDs E and F are equivalent if and only if E covers F and F covers E.
F1: A B, AB C, D AC, D E
F2: A BC, D AE
2. AB C (Given in F1)
3. D AC (Given in F1)
4. D E (Given in F1)
Dr. A. K. Panda
8. D AE (From 6 & 4 and by union rule)
1. A BC (Given in F2)
2. D AE (Given in F2)
3. A B (From 1 and by decomposition rule)
4. A C (From 1 and by decomposition rule)
5. AB CB (From 4 and by augmentation rule)
6. AB C (From 5 and by decomposition rule)
7. D A (From 2 and by decomposition rule)
8. D C (From 7 & 4 and by transitive rule)
9. D AC (From 7 & 8 and by union rule)
10. D E (From 2 and by decomposition rule)
A set of functional dependencies F is minimal or, irreducible if and only if it satisfies the
following conditions:
(i) The R.H.S. of every FD in F involves just one attribute i.e. it is a singleton set.
(ii) The L.H.S. (determinant) of every FD in F is minimal, that means no attribute can be
discarded from the determinant without changing the closure F +.
(iii) No FD in F can be discarded from F without changing the closure F +.
Example:
Find the minimal set of functional dependencies that is equivalent to the following set of
FDs:
F = {A BC, B C, A B, AB C, AC D}
Ans: {A B, B C, A D}
The minimal cover of a set of functional dependencies F is the minimal set of dependencies
Fmin that is equivalent to F.
Dr. A. K. Panda
Example:
Ans: {A B, B C, A D}
1. Initialize Fmin = F.
2. Replace each FD A B1 B2 B3 ... Bn in Fmin by n different FDs A B1, A B2, A B3,
…, A Bn.
3. for each functional dependency A B in Fmin
for each attribute X A
if ((Fmin – {A B}) U ((A – {X}) B)) is equivalent to Fmin then
replace A B with (A – {X}) B in Fmin
4. for each remaining functional dependency A B in Fmin
if (Fmin – {A B}) is equivalent to Fmin then remove A B from Fmin.
Example:
Find the minimal cover Fmin for the following set of FDs F:
Ans:
Fmin = {AB C, C A, BC D, BE C, CE F, CF B, D E, D F}
Fmin = {AB C, C A, BC D, CD B, BE C, CE F, CF D, D E, D F}
Example:
Find the minimal cover Fmin for the following set of FDs F:
Ans: Fmin = {A B, A C, E C, D A, D E, D H, AH D}
Example:
Find the minimal cover Fmin for the following set of FDs F:
Dr. A. K. Panda
F = {A BC, AC D, D B, AB D}
Ans: Fmin = {A B, A C, A D, D B}
Decomposition of a relation:
The decomposition of a relation scheme R = {A1, A2, … , An} is its replacement by a set of
relation schemes D = {R1, R2, …, Rk}, such that
Ri R for 1 i k
and R1 R2 … Rk = R.
R1 = projection of R over A, B
R2 = projection of R over A, C
The decomposition is lossless if R = R 1 ⋈ R2 and the decomposition is lossy if R R1 ⋈ R2.
Dr. A. K. Panda
R A B C
a1 b1 c1
F: A B
AC a2 b2 c2
a3 b2 c1
a3 b1 c2
DECOMPOSE
R1 A B R2 A C
F2: A C
a1 b1 a 1 c1
F1: A B
a2 b2 a 2 c2
a3 b2 a 3 c1
a3 b1 a 3 c2
Join
R A B C
a 1 b 1 c1
F: A B
AC a 2 b 2 c2
a 3 b 2 c1
a 3 b 1 c2
Dr. A. K. Panda
Algorithm to determine whether decomposition is Lossless:
Input: A relation scheme R with a set of FDs F and a decomposition D = {R 1, R2, …, Rk} of R.
1. Construct a blank table S with n columns and k rows, where each column j
corresponds to attribute Aj and each row i corresponds to relation scheme Ri.
2. for each row i representing relation scheme Ri
for each column j representing attribute Aj
if Aj is in Ri then set S[i, j] = aj
else
set S[i, j] = bij.
3. repeat
for each FD X Y in F
for all rows in S that have the same symbols in the columns
corresponding to attributes in X
if one of the symbol in the Y column is aj then make the other aj
else if the symbols are bij and blj then make them both bij or blj
4. If there is at least one row with all ‘a’ symbols i.e. a1, a2, …, ak then the D is Lossless
else D is lossy.
Example:
Solution:
Dr. A. K. Panda
Iteration 1: C D implies Iteration 1: DE C implies Iteration 1: CE A implies
A B C D E A B C D E A B C D E
R1 a1 b12 b13 a4 b15 R1 a1 b12 b13 a4 b15 R1 a1 b12 b13 a4 b15
R2 a1 a2 b13 a4 b25 R2 a1 a2 b13 a4 b25 R2 a1 a2 b13 a4 b25
R3 b31 a2 b13 a4 a5 R3 b31 a2 a3 a4 a5 R3 a1 a2 a3 a4 a5
R4 b41 b42 a3 a4 a5 R4 b41 b42 a3 a4 a5 R4 a1 b42 a3 a4 a5
R5 a1 b52 b13 a4 a5 R5 a1 b52 a3 a4 a5 R5 a1 b52 a3 a4 a5
Since third row of the table contains all ‘a’ symbols, the decomposition is lossless.
Example:
Solution:
F+ = { A B, A C, A D, B C, B D, B A, C D, C A, C B, D A, D B, D
C}
F1 F2 F3 = {A B, B A, B C, C B, C D, D C}
{F1 F2 F3}+ = { A B, A C, A D, B C, B D, B A, C D, C A, C B, D A,
D B, D C}
Dr. A. K. Panda
Since, F+ = {F1 F2 … … Fk}+ , the decomposition preserves dependency.
EXERCISE
No.1: Consider the relation scheme SUPPLIES (Supplier, Part, Contract, Quantity) with a set
of functional dependencies:
F= {Contract Part,
Part Supplier
No.2: A relation R (A, B, C, D) is given. For each of the following set of FDs, assuming they
are the only dependencies that hold for R, state whether or not the proposed
decomposition of R into smaller relations is a good decomposition. Briefly explain your
answer why or why not.
No.3: Remove any redundant FDs from the following set of FDs:
F1: A B, B C, AD C
F2: XY V, ZW V, VX Y, W Y, Z X
F3: PQ R, PS Q, QS P, PR Q, S R
No.4: Given the set of functional dependencies {A BCD, CD E, E CD, D AH, ABH
BD, DH BC}, find a minimal cover. Is this the only minimal cover?
Dr. A. K. Panda
No.6: For each of the following relation schema Ri with a set of functional dependencies
determine key(s) of Ri.
Dr. A. K. Panda
Normalization
It is a process of converting complex data structure into simple and stable data structure. It
is also the process of successively reducing relations with anomalies to produce smaller,
well structured relations.
Redundancy
Update Anomalies.
Insertion Anomalies.
Deletion Anomalies.
Objectives of Normalization:
Steps of Normalization:
Dr. A. K. Panda
Table with Multivalued
attributes
Remove multivalued
attributes
Remove remaining
anomalies
Fifth Normal Form
(5NF/ PJNF)
A relation is in first normal form (1NF) if there are no repeating groups i.e. the value at the
intersection of each row and column is atomic.
Dr. A. K. Panda
Grade Regd- Name Addres Major Subject Sub- Teache Taddre Grade
Report No s -code title r ss
085001 Ashis GGP HRM PCS01 HRP C.S. CSPur A
PCS02 HRD BMD MV B
085013 Anup BJB System PCS05 DS SSM ABC O
PCS06 DBMS AKP XYZ B
PCS07 AI PKM PQR D
085016 Rahul VSS Finance PCS08 SAPM AS MV A
PCS09 FS SD VSS C
PCS11 PA MB MNO B
The above table is not in 1NF because there are entries with more than one value, which
can be converted into 1NF relation by filling in the missing entries of each incomplete row
of the table with the copies of their corresponding non-repeating attributes.
Grade Regd- Name Addres Major Subject Sub- Teache Taddre Grade
Report No s -code title r ss
085001 Ashis GGP HRM PCS01 HRP C.S. CSPur A
085001 Ashis GGP HRM PCS02 HRD BMD MV B
085013 Anup BJB System PCS05 DS SSM ABC O
085013 Anup BJB System PCS06 DBMS AKP XYZ B
085013 Anup BJB System PCS07 AI PKM PQR D
085016 Rahul VSS Finance PCS08 SAPM AS MV A
085016 Rahul VSS Finance PCS09 FS SD VSS C
085016 Rahul VSS Finance PCS11 PA MB MNO B
1NF contains redundant information. For example the above relation GRADE-REPORT is in
1NF with primary key {Regd.-No, Subject-code} which has the following problems:
1. Redundancy: The student’s name, address and major are repeated for each subject
he is registered for.
2. Update Anomaly: As a consequence of the redundancy, we may update the address
in one tuple, while leaving it unchanged in another. Thus we would not have a
unique address for each student.
3. Insertion Anomaly: It is not possible to record the address of a teacher, unless he is
assigned to at least one subject.
4. Deletion anomaly: If a subject is registered by only one student and a teacher is
assigned to teach only that subject and if the said student discontinues the course,
Dr. A. K. Panda
the information of the student cannot be deleted. If we do so information of the
teacher will be lost.
A relation is in second normal from (2NF) if it is in 1NF and every non-key (nonprime)
attribute is fully functionally dependent on the primary key.
Note: A relation that is in first normal form will be in second normal form if any one of
following conditions is satisfied:
Teacher T-Address
Dr. A. K. Panda
SUBJECT (Sub-Code, Sub-Title, Teacher, T-Address)
A relation is in third normal form if it is in second normal form and there exists no
transitive dependency.
Transitive Dependency: Let X and Y be the set of attributes such that X Y holds but Y
X does not hold and Z be a set of attributes that in not in X and not in Y for which Y Z
holds, then Z is transitively dependent on X.
In other words, a functional dependency between two or more non-key attributes is called
transitive dependency.
1. For each non-key attribute (or set of attributes) that is a determinant in a relation,
create a new relation. The attribute becomes the primary key of the new relation.
2. Move all of the attributes that are functionally dependent on the attribute from the
old to the new relation.
3. Leave the attribute (which serves as a primary key in the new relation) in the old
relation to serve as foreign key that allows us to associate the two relations.
The relations STUDENT and GRADE-REPORT are in 3NF, But the relation SUBJECT is not in
3NF because there is a functional dependency between non-key attributes (Teacher T-
Address).
BCNF:
Dr. A. K. Panda
1. Initialize D = R.
2. repeat
Choose a relation scheme Ri in D that is not in BCNF
if X Y be a FD of Ri that violates BCNF then
Replace Ri in D by two relation schemes Ri – Y and X Y.
Note: This algorithm guarantees Lossless, but does not guarantee dependency preserving.
Note: This algorithm guarantees both Lossless and dependency preserving. If step 4 is
removed, the algorithm will guarantee dependency preserving, but will not guarantee
lossless.
Example:
F = {D A, DF C, DA B, A F, EF B, E A, B D, DA B, EB C, AB C, G
B, C B}
Solution:
Step 1: Fmin = {D C, D A, D B, B D, E B, G B, A F, C B}
Dr. A. K. Panda
Step 3: D = {R1(D, C, A, B), R2(B, D),R3(E, B),R4(G, B),R5(A, F),R6(C, B)}
Step 4: Since none of the relation scheme in D contains key of R, a new relation R 7(E, G)
containing key of R is included in D.
D = { R1(D, C, A, B), R2(B, D),R3(E, B),R4(G, B),R5(A, F),R6(C, B), R7(E, G)}
Step 5: Eliminating the redundant relation schemes R2(B, D) and R6(C, B) we get the
following 3NF relation schemes:
D = { R1(D, C, A, B), R2(E, B),R3(G, B),R4(A, F), R5(E, G)}, where the key attributes are
underlined.
Example:
Project-id Supplier-id }
Solution:
a) The primary key consists of only one attribute i.e. Contract-id. Hence the relation
CONTRACTS is in 2NF. Since there is a FD between non-key attributes, the relation is
not in 3NF. Hence the highest normal form of the relation is 2NF.
b) Given relation scheme R(C, S, J, D, P, Q, V) with a set of FDs:
F = {C S J D P Q V, JP C, SD P, J S}
Fmin = {C J, C D, C Q, C V, JP C, SD P, J S}
D1 = {R1(C, J, D, Q, V), R2(J, P, C), R3(S, D, P), R4(J, S)}, where each Ri is in 3NF.
Dr. A. K. Panda
c) In the FD: SD P, SD is not a key. Hence R is decomposed into R1(S, D, P) and R2(C,
S, J, D, Q, V).
In R2, there is a FD: J S and J is not a key. Hence R2 is decomposed into R2(J, S) and
R3(C, J, D, Q, V).
D2 = {R1(S, D, P), R2(J, S), R3(C, J, D, Q, V)}, where each Ri is in BCNF.
d) We can verify that D1 is a loss-less join and dependency preserving decomposition
and D2 is loss-less but does not preserve dependency.
F = {A B, BC E, ED A}.
Ans:
Ans:
2NF decomposition
A D,E,I,J
R1(A, D, E, I, J) B F, G, H
R R2(B, F, G, H)
R2(A, B, C, F, G, H)
R3(A, B, C)
Hence D = {R1(A, D, E, I, J), R2(B, F, G, H), R3(A, B, C)}, where each Ri is in 2NF.
3NF decomposition
D I,J
R1(D, I, J)
R1(A, D, E, I, J)
R2(A, D, E)
Dr. A. K. Panda
F GH
R3(F, G, H)
R2(B, F, G, H)
R4(B, F)
Hence D = { R1(D, I, J), R2(A, D, E), R3(F, G, H), R4(B, F), R5(A, B, C)}, where each Ri is in 3NF.
Solution:
D = { R1(A, B, C), R2(A, D, E), R3(B, F), R4(F, G, H), R5(D, I, J)}
Example: Consider R (A, B, C, D) be a relation scheme. For each of the following sets of FDs,
assuming those are the only dependencies that hold for R, do the following:
1) C D, C A, B C
2) B C, D A
3) ABC D, D A
4) A B, BC D, A C
5) AB C, AB D, C A, D B.
Solution:
1) (a) Since B does not appear in the RHS of any FD and B + = {A, B, C, D}, Hence B is the
only candidate key.
(b) Since primary key contains a single attribute, R is in 2NF, but it is not in 3NF
because there exists FD between non-key attributes. Therefore, the best normal form of
R is 2NF.
(c) D = {R1(C, D), R2(A, C), R3(B, C)}
Dr. A. K. Panda
(d) D is both loss-less and dependency preserving.
2) (a) Since BD does not appear in the RHS of any FD and {B,D} + = {A, B, C, D}, Hence BD is
the only candidate key.
(b) Since partial dependency exists, R is not in 2NF. Therefore, the best normal
form of R is 1NF.
(c) D = {R1(B, C), R2(A, D), R3(B, D)}
(d) D is both loss-less and dependency preserving.
3) (a) Since BC does not appear in the RHS of any FD, and {B,C}+ {A, B, C, D}, Hence BC is
part of the key. ABC and BCD are the keys.
(b) Since there is no partial dependency, R is in 2NF. It is also in 3NF because
there exists only one non-key attribute. It is not in BCNF because for the FD D A, D is
not a key of R. Therefore, the best normal form of R is 3NF.
(c) D = {R1(A, D), R2(B, C, D)}, where each Ri is in BCNF.
(d) D is loss-less but does not preserve the dependency ABC D.
4) (a) Since A does not appear in the RHS of any FD and A + = {A, B, C, D}, Hence A is the
only candidate key.
(b) Since primary key contains a single attribute, R is in 2NF, but it is not in 3NF
because there exists a FD between non-key attributes i.e. BC D. Therefore, the best
normal form of R is 2NF.
(c) D = {R1(B, C, D), R2(A, B, C)}
(d) D is both loss-less and dependency preserving.
5) (a) AB, BC, CD, AD are the keys of R.
(b) If AB is considered as PK, there is no FD between non-key attributes. Hence, R is in
3NF. It is not in BCNF because for the FD: C A, C is not a key. Therefore, The best
normal form of R is 3NF.
(c) D = { R1(A, C), R2(B, D), R3(C, D)}
(d) D is loss-less but does not preserve dependency.
Let R be a relation scheme and X and Y be subsets of the attributes of R. The multivalued
dependency X Y (X multi-determines Y) is said to hold over R if in every legal instance r
of R, each X value is associated with a set of Y values and this set is independent of the
values in the other attributes.
In other words, X Y holds on R if for all pair of tuples t1 and t2 in r, if t1 and t2 have
same value for X then we must get two tuples t3 and t4 in r by interchanging Y value for t1
and t2.
Dr. A. K. Panda
Example:
a) Y is a subset of X, or
b) X Y = R.
Dr. A. K. Panda
Fourth Normal Form (4NF):
A relation R is said to be in fourth normal form (4NF) if it is in BCNF and for every non-
trivial MVD X Y that holds over R, X is a super key for R.
Example:
The relation STB is not in 4NF because Subject Teacher is a nontrivial MVD and
Subject is not a key. Hence the relation STB can be decomposed into two relations ST
(Subject, Teacher) and SB (Subject, Book). Each of these relations is in 4NF.
Input: A relation scheme R that is not in 4NF and a set functional and multivalued
dependencies F of R.
1. Initialize D = R.
2. repeat
Choose a relation scheme Ri in D that is not in 4NF
if X Y be a MVD of Ri that violates 4NF then
replace Ri in D by two relation schemes Ri – Y and X Y.
Note: This algorithm guarantees Lossless but does not guarantee dependency preserving.
Ques: Explain why 4NF is a normal form more desirable than BCNF.
Ans: 4NF is more desirable than BCNF because it reduces the repetition of information. If
we consider a BCNF schema not in 4NF, we observe that decomposition into 4NF does not
Dr. A. K. Panda
loose information provided that lossless join decomposition is used, yet redundancy is
reduced.
Join Dependency (JD): A Join dependency (JD) denoted by JD (R1, R2, …, Rn) is said to hold
over a relation schema R if R1, R2, …, Rn is a lossless-join decomposition of R.
Fifth Normal Form (5NF): It is also called Project Join Normal Form (PJNF). A relation R is
said to be in fifth normal form (5NF) if for every JD (R 1, R2, …, Rn) that holds over R, one of
the following conditions is satisfied.
Example:
S P P L L S
S1 P1 P1 L2 L2 S1
S1 P2 P2 L1 L1 S1
S2 P1 P1 L1 L2 S2
Join
EXERCISE
No.1: Consider the following collection of relations and dependencies. Assume that each
relation is obtained through decomposition from a relation with attributes ABCDEFGHI and
that all the known dependencies over relation ABCDEFGHI are listed for each question.
(The questions are independent of each other, obviously, since the given dependencies
over ABCDEFGHI are different.) For each (sub) relation:
(a) State the strongest normal form that the relation is in.
(b) If it is not in BCNF, decompose it into a collection of BCNF relations.
1. R1(A,C,B,D,E), A → B, C → D
2. R2(A,B,F), AC → E, B → F
3. R3(A,D), D → G, G → H
4. R4(D,C,H,G), A → I, I → A
5. R5(A,I,C,E)
Answer:
1. 1NF. BCNF decomposition: D = {R1(AB), R2(CD), R3(ACE)}.
2. 1NF. BCNF decomposition: D = { R1(AB), R2(BF)}
3. BCNF.
4. BCNF.
5. BCNF.
Ans: R is not in 3NF because there is only one non-key attribute. It is not in BCNF because
in the FD: C A, C is not a key of R.
No. 4: Give an example of a relation scheme, R and a set of dependencies such that R is in
BCNF but is not in 4NF.
Dr. A. K. Panda
A →→ BC,
B →→ CD
E →→ AD
No. 5: Prove that any relation scheme with two attributes is in BCNF.
Ans: Consider a relation scheme R (A, B). The only possible non-trivial FDs are A B and
B A. There are four possible cases:
1. No FD holds in R. In this case, the key is {A, B} and the relation satisfies BCNF.
2. Only A B holds. In this case, the key is {A} and the relation satisfies BCNF.
3. Only B A holds. In this case, the key is {B} and the relation satisfies BCNF.
4. Both A B and B A hold. In this case, there are two keys {A} and {B} and
the relation satisfies BCNF.
Dr. A. K. Panda
1
TRANSACTION PROCESSING
Example:
Read (A);
A = A + 1;
Write (A).
Properties of Transaction:
Read/ Write
Begin T End T Commit
Active Partially Committed
Committed
Abort Abort
Failed Terminated
Dr. A. K. Panda
2
Transaction States:
1. Active State: It is the initial state. The transaction stays in this state while it
is executing.
2. Partially committed State: When the final statement has been executed, we say the
transaction is in partially committed state.
3. Failed State: When the normal execution can no longer proceed, we say that
the transaction is in failed state.
4. Committed State: When a transaction is completed successfully, it comes to
committed state.
5. Terminated State: It is the final state. When transaction is leaving the system, we
say that it is in terminated state.
Schedule:
Transaction Transaction
T1 T2
Read A
Write A
Read B
Write B
Read C
Write C
Dr. A. K. Panda
3
Types of Schedule:
1. Complete Schedule
2. Serial Schedule
3. Non-serial schedule
4. Equivalent Schedule
5. Serializable Schedule
1. Complete Schedule: A schedule that contains either an abort or a commit for each
transaction, whose actions are listed in it, is called a complete schedule.
4. Equivalent Schedule: Two schedules are said to be equivalent schedules if they produce
the same result on any database state. Two equivalent schedules always produce identical
results.
Example:
Consider two transactions T1 and T2 in the following non-serial schedule S1; T1 transfers Rs.
1000 from A/C A to A/C B and T2 transfers Rs. 2000 from A/C B to A/C C:
Dr. A. K. Panda
4
The effect of schedule S1 is same as effect of two serial schedules S 2 and S3. Hence the
schedule S1 is Serializable.
Schedule S4
The effect of S4 is not same as any serial schedule (S2 or S3). Hence S4 is non-Serializable.
Dr. A. K. Panda
5
Conflicts:
Two actions in a schedule are said to conflict if they satisfy all three of the following
conditions:
In Serializability, the order of read and write operations are important and the following
serializability rules are given below:
If two transactions only read a data item, they do not conflict and the order is not
important.
If two transactions either read or write completely separate data items, they do not
conflict and the order is not important.
If one transaction writes a data item and another either reads or writes the same
data item, the order of execution is important.
Types of Serializability:
1. Conflict Serializability:
Conflict Equivalence: Two schedules S1 and S2 are said to be conflict equivalent if they can
be turned one into the other by a sequence of non-conflicting swaps of adjacent actions.
Transaction Transaction
T1 T2
Read A
Write A
Read A
Write A
Read B
Write B
Read B
Write B
Dr. A. K. Panda
6
The above schedule can be converted into a serial schedule by non-conflicting swaps of
adjacent actions as given below:
2. View Serializability:
View Equivalence: Two schedules S1 and S2 are said to be view equivalent if following
three conditions are satisfied:
1. For each data item X, if transaction Ti reads the initial value of X in schedule S 1, then
transaction Ti must in schedule S2, also read the initial value of X.
2. For each data item X, if transaction T i executes Read(X) in schedule S1 and if that
value was produced by a Write(X) operation executed by Transaction T j, then the
Read(X) operation of Transaction Ti must in schedule S2 also read the value of X that
was produced by the same Write(X) operation of transaction T j.
Dr. A. K. Panda
7
3. For each data item X, the transaction (if any) that performs the final Write(X)
operation in schedule S1 must perform the final Write(X) operation in schedule S 2.
Dr. A. K. Panda
8
T3
T1 T2
Precedence Graph of S7:
T3
Recoverability:
The process of restoring the database to a correct state in the event of a failure is called
database recovery. If a transaction fails we need to undo the effect of the transaction and
bring the database to the consistent state prior to the start of the transaction. So when a
Dr. A. K. Panda
9
transaction aborts, all the transactions dependent on the aborted transaction also should
be aborted and rolled back.
Example:
Non-recoverable Schedule S8
Transaction Transaction
T1 T2
Read A
Write A
Read A
Write A
Commit
Read B
…
…
In schedule S8, T2 has read the value written by T1. If T1 fails before it commits, we must
abort T2 to ensure atomicity. But this is not possible as transaction T 2 has already been
committed. This situation is an example of non-recoverable schedule.
Example:
Cascading Schedule S9
In Schedule S9, T1 writes a value that is read by T2. T2 writes a value that is read by T3.
Suppose at that point transaction T1 fails, so T1 is rolled back. Since T2 is dependent on T1, it
also should be rolled back. Since T 3 is dependent on T2 it too has to be rolled back. This
Dr. A. K. Panda
10
3. Strict Schedule: A schedule in which transactions can neither read nor write a data item
‘X’ until the last transaction that wrote the data item ‘X’ has committed or aborted.
Example:
Strict Schedule S10 Strict Schedule S11
Dr. A. K. Panda
11
CONCURRENCY CONTROL
1. Lost update Problem: A successfully completed update operation by one user can be
overwritten by another user. This is known as lost update problem.
Schedule S12
Dr. A. K. Panda
12
Since the transaction T2 has aborted, the database should be restored to the original state.
But before the roll back is performed, transaction T 1 reads the A/C balance and starts
executing. So instead of a balance of 4900 (since only T 1 was committed), it is ended with a
wrong result of 5900. This is happened only because T 1 was permitted to read the
intermediate result of transaction T2.
This read is known as Dirty Read and the problem is known as dirty read problem.
Example: Suppose that there are two concurrent transactions T 1 and T2, where T2 is
totaling the balances of A/C A (Rs. 4000), A/C B (Rs. 5000) and A/C C (Rs. 3000) and T 1 is
transferring Rs.500 from A/C A to A/C C.
Schedule S14
Dr. A. K. Panda
13
If Rs. 500 is transferred from A/C A to A/C C, Total Balance of three A/Cs should remain
same i.e. Rs. 12000. But effect of the above schedule is total balance is Rs. 12500.
A transaction T requests an access to an item A by issuing a Lock (A) operation. If Lock (A)
= 1, the transaction is forced to wait. If Lock A) = 0, then transaction T is allowed to access
item A. When T’s access is over, it issues an unlock (A) operation which sets Lock (A) to 0.
Schedule S15
Transaction T1 Transaction T2
Read A
Read A
A=A–1
A=A+1
Write A
Write A
Due to concurrent execution of transactions the update of T 1 is lost. The problem can be
solved by providing a lock on item A.
Dr. A. K. Panda
14
Transaction Transaction
T1 T2
Lock (A)
Read A
A=A–1
Write A
Unlock (A)
Lock (A)
Read A
A=A+1
Write A
Unlock (A)
Rule followed during Binary Locking: Each transaction (say, T) must follow the following
rules:
1. A transaction T must issue Lock (A) operation before any Read (A) or Write (A)
operations are performed in T.
2. T must issue the Unlock (A) operation after all Read (A) and Write (A) operations
are completed in T.
3. T will not issue a Lock (A) operation if it already holds the lock on item A.
4. T will not issue an Unlock (A) operation unless it already holds the lock on item A.
5. At most only one transaction can hold the lock on a particular item.
Dr. A. K. Panda
15
The above schedule follows Binary locking protocol, but the schedule is not Serializable
whose precedence graph is given below.
T1 T2
T3
Example: Consider the following Schedule S17. There are two concurrent transactions T1
and T2, where T2 is totaling the balances of A/C A (Rs. 4000) and A/C B (Rs. 3000) and T 1 is
transferring Rs.100 from A/C A to A/C B.
The above schedule S17 is non0serializable because total balance is not equal to 7000.
Dr. A. K. Panda
16
When several transactions try to access the same data item for reading purpose only, then
we should allow the access. But, if a transaction is to write an item A, it must have exclusive
access to A. For this purpose there are two modes of locking:
Shared Lock (Read Lock): The intention of this mode of locking is to ensure that the data
item does not undergo any modifications while it is locked in this mode. Any number of
transactions can concurrently lock and access a data item in the shared mode. But none of
them can modify it. A data item locked in the shared mode cannot be locked in the exclusive
mode until the shared lock is released.
Exclusive Lock (Write Lock): The intention of this mode of locking is to provide exclusive
use of the data item to one transaction. If a transaction has Write lock on a data item, it can
both read and update the data item and no other transaction issue a shared or exclusive
lock until write lock is released.
Rule followed during Shared/ exclusive Locking: Each transaction (say, T) must follow
the following rules:
1. Any transaction that needs to access a data item must first lock the item requesting
a read lock for read only access or a write Lock for both read access and write
access.
2. If the item is not already locked by other transaction, the lock will be granted.
3. If the item is currently locked, the Database system determines whether the request
is compatible with the existing lock. If a read lock is requested on an item that
already has a read lock on it, the request will be granted otherwise, the transaction
must wait until the existing write lock is released.
4. A transaction continues to hold a lock until it explicitly releases it either during
execution or, when it terminates (aborts or commits). It is only when the write lock
has been released that the effects of the write operation will be made visible to
other transactions.
Note: Shared/ exclusive (Read/ Write) Locking does not guarantee serializability.
Example: Consider the following Schedule S18 where T1 is a transaction that transfers Rs.
1000 from A/C A to A/C B and T2 is a transaction that increases A and B by 10%.
Dr. A. K. Panda
17
The above Schedule follows R/W Locking protocol but non-Serializable whose precedence
graph is given below:
T1 T2
Dr. A. K. Panda
18
4. For each case in S, where Tj issues a Wlock(X) after Ti issues a Wlock (X), create a
directed edge from Ti to Tj.
5. If the Precedence graph has no cycles, then the schedule S is Serializable,
else
Schedule S is Non-Serializable.
A transaction must acquire a lock on an item before operating on the item. The lock
may be Rlock or Wlock depending on the type of access needed.
Once a transaction releases a single lock, it can never acquire any new lock.
S is serializable (Proved).
Limitation of 2PL:
a) Cascading rollback
b) Deadlock
Dr. A. K. Panda
19
Deadlock:
A deadlock is a condition in which two or more transactions in a set are each waiting for
locks held by some other transaction in the set. Neither transaction can continue because
each transaction in the set is on the queue, waiting for one of the other transactions in the
set to release the lock on an item.
Schedule S19
Transaction Transaction
T1 T2
Wlock (A)
Wlock (B)
Read A
Read B
A = A – 100
B = B + 1000
Write A
Write B
Wlock (B)
WAIT Wlock (A)
WAIT WAIT
WAIT WAIT
Dr. A. K. Panda
20
… …
1. Deadlock prevention
2. Deadlock detection and recovery
1. Deadlock Prevention:
In deadlock prevention the DBMS looks ahead to determine if a transaction would cause a
deadlock and never allows a deadlock to occur. There are two approaches to prevent
deadlock:
a) Using Time Stamp: Time stamp is a unique identifier created by the DBMS that
indicates the relative starting time of each transaction. In this approach DBMS
decides whether to wait or abort and rollback a transaction by using any one of
following two techniques:
(i) Wait-Die:
If the requesting transaction Ti is older than the transaction Tj that
holds the lock on the requested data item (TS [Ti] TS [Tj]) then the
requesting transaction Ti is allowed to wait.
If the requesting transaction Ti is younger than the transaction Tj (TS
[Ti] TS [Tj]) then the requesting transaction Ti is aborted (Ti dies)
and restarted with the same time stamp.
(ii) Wound-Wait:
If the requesting transaction Ti is older than Tj (TS [Ti] TS [Tj]) then
Tj is aborted and restarted with the same time stamp (the younger
transaction is wounded or suspended by the older transaction).
If TS [Ti] TS [Tj] then Ti is allowed to wait.
Dr. A. K. Panda
21
If both are blocked, then find block times b(Ti) and b(Tj) of Ti and Tj
respectively then
if b[Ti] b[Tj] then Ti is blocked and allowed to wait Tj.
Recovery from deadlock: To recover from a deadlock, the cycles in the WFG must be
broken. The most common method of doing this is to rollback one or more transactions in
the cycles until the system exhibits no further deadlock situation. Choosing which
transaction to rollback is known as victim selection.
4. Timestamp Ordering:
In this method, a serial order is created among the concurrent transactions by assigning to
each transaction a unique non decreasing number called timestamp. Besides the timestamp
of each transaction, each data item has two timestamps: read timestamp and write
timestamp.
RTS(X): This is the largest time stamp among all transactions that have successfully
read item X.
WTS(X): This is the largest of all timestamps of transactions that have
successfully written item X.
Procedure:
Dr. A. K. Panda
22
Example: Consider the following schedule S20 that follows Time stamp ordering and the
schedule is serializable.
Schedule S20 A B
Transaction Transaction Transaction RTS = 0 RTS = 0
T1 T2 T3 WTS = 0 WTS = 0
(Time Stamp (Time stamp (Time Stamp
10) 11) 12)
Read A RTS =
A = A – 100 10
Write A
Read B Read A WTS = RTS = 10
B = B + 100 A = A – 500 10
Write B Write A RTS = WTS = 10
Read B Read A 11 RTS = 11
B = B + 500
Write B WTS = WTS = 11
Read B 11 RTS = 12
C=A+B RTS =
Print C 12
Note: Time stamp ordered schedulers does not create deadlock, they may lead to livelock.
Let {X1, X2, …, Xn} denote the versions of a data item X. Besides its value, each version Xi
contains following two timestamps.
Dr. A. K. Panda
23
1. RTS (Xi): The read time stamp of Xi is the largest of all the timestamps of
transactions that have successfully read the version X i.
2. WTS (Xi): The write timestamp of Xi is the timestamp of the transaction that
created the version Xi.
The read timestamp of version X i is updated whenever a transaction Tk with TS (Tk) RTS
(Xi) reads the version Xi and RTS (Xi) is changed to RTS (Xi) = TS (Tk)
1. If transaction T issues a Read(X) operation, find the version of X (say Xj) that has the
largest WTS (Xj) value that is also less than or equal to TS (T); then return the value
of Xj to T and update RTS (Xj) as follows:
RTS (Xj) = Max [ TS (T), RTS (Xj)
2. If transaction T issues a Write(X) operation, and the version of X (say Xj) that has
the largest WTS (Xj) value that is also less than or equal to TS (T); then abort and
rollback.
Otherwise,
Create a new version of X (say Xj + 1) with RTS (Xj + 1) = WTS (Xj + 1) =TS (T)
1. Read Phase: The transaction T reads data items from the database and stores these
values in local variables. All write operations are performed on the local variables
without modifying the actual database.
2. Validation Phase: In this phase, appropriate checks are performed to determine
whether the transaction updates can be carried out on the database without causing
violation of serializability.
3. Write Phase: This phase comes after successful completion of the validation phase.
If the validation phase is successful, the transaction updates are applied to the
database; otherwise, the transaction T is rolled back.
Dr. A. K. Panda
24
DATABASE RECOVERY
Database recovery is the process of restoring the database to a correct (consistent) state in
the event of a failure.
1. Shadow Paging:
This technique does not require the use of a log file in a single-user environment, though a
log is needed in a multiuser environment for concurrency control. Shadow paging
considers the database to be made up of a number of fixed size disk pages or disk blocks for
recovery purposes.
This technique maintains two directories during the life of a transaction- a current
directory and a shadow directory. When the transaction starts, the two directories are the
same. The shadow directory is saved to the disk and the current directory is used by the
transaction.
During the transaction execution, the shadow directory is never modified. When a write
operation is performed on a data item, a new copy of the modified database page is created,
but the old copy of that page not overwritten. The new copy is written somewhere else. The
current directory entry is modified to point to the disk block. The shadow directory will be
still pointing to the old unmodified disk block as it is not updated and the old disk block is
not overwritten.
2
1
1 3 2
2 3
3 4 4
4 5
5
5 6
6 6 7
7 8
8 7
Current 8 Shadow
Directory Directory
9
10
Dr. A. K. Panda
Pages on disk
25
To recover from a transaction failure, it is sufficient to free the modified database page and
discard the current directory. The state of the database before the start of the transaction is
available through the shadow directory and that state is recovered by reinstating the
shadow directory.
Committing a transaction is done by discarding the shadow directory. Thus the current
directory is used to record all updates to the database. When a transaction completes, the
current directory becomes the shadow directory. Since the recovery using the shadow
paging technique requires neither an undo nor a redo, it is classified as NO-UNDO/ NO-
REDO algorithm.
ARIES is a recovery algorithm that is designed to work with a steal, no-force approach.
ARIES recovers from a system crash in three phases:
1. Analysis: This phase identifies the dirty pages in the buffer (i.e. the changes that
have not been written to disk) and active transactions at the time of the crash.
2. Redo: This phase repeats all actions, starting from an appropriate point in the log,
and restores the database state to what it was at the time of the crash.
3. Undo: This phase undoes the actions of transactions that did not commit, so that
the database reflects only the actions of committed transactions.
Write-ahead logging: Any change to a database object is first recorded in the log;
the record in the log must be written to stable storage before the change to the
database object is written to disk.
Dr. A. K. Panda
26
Repeating history during Redo: Upon restart following crash, ARIES retraces all
actions of the DBMS before the crash and brings the system back to the exact state
that it was in at the time of the crash.
Logging changes during Undo: Changes made to the database while undoing a
transaction are logged in order to ensure that such an action is not repeated in the
event of repeated restarts.
Dr. A. K. Panda