0% found this document useful (0 votes)
27 views86 pages

Dbms Notes Unit1,2,6

The document provides an overview of Database Management Systems (DBMS), including definitions, architecture, data models, and the roles of database administrators. It compares DBMS with file systems, highlighting advantages such as reduced redundancy and improved data consistency. Additionally, it outlines the responsibilities of DBAs and the structure of DBMS, including types of architectures and data models used.

Uploaded by

akbhai000008
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views86 pages

Dbms Notes Unit1,2,6

The document provides an overview of Database Management Systems (DBMS), including definitions, architecture, data models, and the roles of database administrators. It compares DBMS with file systems, highlighting advantages such as reduced redundancy and improved data consistency. Additionally, it outlines the responsibilities of DBAs and the structure of DBMS, including types of architectures and data models used.

Uploaded by

akbhai000008
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

UNIT -I

Important questions in UNIT1


Q1. Define data Independence. 5M
Q.2 Define DBA and discuss roles and responsibilities of DBA. 10M
Q.3 Compare file system and Database system. 5M
Q.4 Draw and describe overall architecture of DBMS with its component. 10M
Q.5Discuss three level schema architecture of DBMS. 10M

INTRODUCTION TO DBMS:

What is data?
• Data is nothing but facts and statistics stored or free flowing over a network,
generally it's raw and unprocessed.
• Data becomes information when it is processed, turning it into something
meaningful.
• What is database: The database is a collection of inter-related data which is used to
retrieve, insert and delete the data efficiently.
• It is also used to organize the data in the form of a table, schema, views, and
reports, etc.
• Using the database, you can easily retrieve, insert, and delete the information.
• For example: The college Database organizes the data about the admin, staff,
students and faculty etc.

Difference between DBMS and Filesystem.

DBMS File System

DBMS is a collection of data. In DBMS, the user File system is a collection of data. In this system, the
is not required to write the procedures. user has to write the procedures for managing the
database.

DATABASE MANAGEMENT SYSTEMS Page 2


Searching data is easy in Dbms Searching is difficult in File System

Dbms is structured data Files are unstructured data

No data redundancy in Dbms Data redundancy is there in file system

Memory utilisation well in dbms Memory utilisation poor in file system

No data inconsistency in dbms Inconsistency in file system

DBMS gives an abstract view of data that hides File system provides the detail of the data
the details. representation and storage of data.

DBMS provides a crash recovery mechanism, File system doesn't have a crash mechanism, i.e., if
i.e., DBMS protects the user from the system the system crashes while entering some data, then the
failure. content of the file will lost.

DBMS provides a good protection mechanism. It is very difficult to protect a file under the file
system.

DBMS contains a wide variety of sophisticated File system can't efficiently store and retrieve the
techniques to store and retrieve the data. data.

DBMS takes care of Concurrent access of data In the File system, concurrent access has many
using some form of locking. problems like redirecting the file while other deleting
some information or updating some information.

• A DBMS is software that allows creation, definition and manipulation of database,


allowing users to store, process and analyse data easily.
• DBMS provides us with an interface or a tool, to perform various operations like
creating database, storing data in it, updating data, creating tables in the database
and a lot more.

DATABASE MANAGEMENT SYSTEMS Page 3


• DBMS also provides protection and security to the databases.
• It also maintains data consistency in case of multiple users.
Here are some examples of popular DBMS used these days:
• MySql
• Oracle
• SQL Server
• IBM DB2

PURPOSE OF DATABASE SYSTEMS

• The main purpose of database systems is to manage the data. Consider a university
that keeps the data of students, teachers, courses, books etc. To manage this data
we need to store this data somewhere where we can add new data, delete unused
data, update outdated data, retrieve data, to perform these operations on data we
need a Database management system that allows us to store the data in such a way
so that all these operations can be performed on the data efficiently.
Characteristics of DBMS
• Data stored into Tables: Data is never directly stored into the database. Data is
stored into tables, created inside the database.
• Reduced Redundancy: In the modern world hard drives are very cheap, but earlier
when hard drives were too expensive, unnecessary repetition of data in database
was a big problem. But DBMS follows Normalisation which divides the data in
such a way that repetition is minimum.
• Data Consistency: On Live data, i.e. data that is being continuosly updated and
added, maintaining the consistency of data can become a challenge. But DBMS
handles it all by itself.
• Support Multiple user and Concurrent Access: DBMS allows multiple users to
work on it(update, insert, delete data) at the same time and still manages to
maintain the data consistency.
• Query Language: DBMS provides users with a simple Query language, using
which data can be easily fetched, inserted, deleted and updated in a database.

DATABASE MANAGEMENT SYSTEMS Page 4


Advantages of DBMS

• Controls database redundancy: It can control data redundancy because it stores all
the data in one single database file and that recorded data is placed in the database.
• Data sharing: In DBMS, the authorized users of an organization can share the data
among multiple users.
• Easily Maintenance: It can be easily maintainable due to the centralized nature of
the database system.
• Reduce time: It reduces development time and maintenance need.
• Backup: It provides backup and recovery subsystems which create automatic
backup of data from hardware and software failures and restores the data if
required.
• multiple user interface: It provides different types of user interfaces like graphical
user interfaces, application program interfaces

Disadvantages of DBMS

• Cost of Hardware and Software: It requires a high speed of data processor and
large memory size to run DBMS software.
• Size: It occupies a large space of disks and large memory to run them efficiently.
• Complexity: Database system creates additional complexity and requirements.
• Higher impact of failure: Failure is highly impacted the database because in most
of the organization, all the data stored in a single database and if the database is
damaged due to electric failure or database corruption then the data may be lost
forever.

View of Data in DBMS


• Abstraction is one of the main features of database systems.
• Hiding irrelevant details from user and providing abstract view of data to users,
helps in easy and efficient user-database interaction.
• the three level of DBMS architecture, The top level of that architecture is “view
level”. The view level provides the “view of data” to the users and hides the
irrelevant

DATABASE MANAGEMENT SYSTEMS Page 5


details such as data relationship, database schema, constraints, security etc from the
user.

Data Abstraction in DBMS

Database systems are made-up of complex data structures. To ease the user interaction with
database, the developers hide internal irrelevant details from users. This process of hiding
irrelevant details from user is called data abstraction.

We have three levels of abstraction:


Physical level: This is the lowest level of data abstraction. It describes how data is actually
stored in database. You can get the complex data structure details at this level.

Logical level: This is the middle level of 3-level data abstraction architecture. It describes
what data is stored in database.

View level: Highest level of data abstraction. This level describes the user interaction
with database system.
Instance and schema in DBMS

• Definition of schema: Design of a database is called the schema. Schema is of three


types: Physical schema, logical schema and view schema.

DATABASE MANAGEMENT SYSTEMS Page 6


• The design of a database at physical level is called physical schema, how the data
stored in blocks of storage is described at this level.
• Design of database at logical level is called logical schema, programmers and
database administrators work at this level, at this level data can be described as certain
types of data records gets stored in data structures, however the internal details such
as implementation of data structure is hidden at this level (available at physical level).
• Design of database at view level is called view schema. This generally describes end
user interaction with database systems.

Definition of instance:
The data stored in database at a particular moment of time is called instance of database.
Database schema defines the variable declarations in tables that belong to a particular
database; the value of these variables at a moment of time is called the instance of that
database.

DBMS ARCHITECTURE:
• Database management systems architecture will help us understand the components of
database system and the relation among them.
• The architecture of DBMS depends on the computer system on which it runs.
• the basic client/server architecture is used to deal with a large number of PCs, web
servers, database servers and other components that are connected with networks.
• The client/server architecture consists of many PCs and a workstation which are
connected via the network.
• DBMS architecture depends upon how users are connected to the database to get their
request done.

TYPES OF DBMS ARCHITECTURE

There are three types of DBMS architecture:


1. Single tier architecture
2. Two tier architecture
3.Three tier architecture

DATABASE MANAGEMENT SYSTEMS Page 7


1-Tier Architecture /1 layer architecture

• In this type of architecture, the database is readily available on the client machine, any
request made by client doesn’t require a network connection to perform the action on
the database.
• Any changes done here will directly be done on the database itself. It doesn't provide
a handy tool for end users.
• The 1-Tier architecture is used for development of the local application, where
programmers can directly communicate with the database for the quick response.

2. Two tier architecture /2 layer architecture

• In two-tier architecture, the Database system is present at the server machine and
the DBMS application is present at the client machine, these two machines are
connected with each other through a reliable network.
• Whenever client machine makes a request to access the database present at server
using a query language like sql, the server perform the request on the database
and returns the result back to the client.
• The application connection interface such as JDBC, ODBC are used for the
interaction between server and client.

3-Tier Architecture /3 layer architecture


• In Three-tier architecture, the Database system is present at the server machine
and the DBMS application is present at the client machine, these two machines
are connected with each other through a reliable network.

DATABASE MANAGEMENT SYSTEMS Page 8


• Whenever client machine makes a request to access the database present at server
using a query language like sql, the server perform the request on the database
and returns the result back to the client.

• In three-tier architecture, another layer is present between the client machine and
server machine.

• In this architecture, the client application doesn’t communicate directly with the
database systems present at the server machine, rather the client application
communicates with server application and the server application internally
communicates with the database system present at the server.

DATA MODELS:
• Data Model is the modeling of the data description, data semantics, and
consistency constraints of the data.
• It provides the conceptual tools for describing the design of a database at each
level of data abstraction.
• Therefore, there are following four data models used for understanding the
structure of the database:

Four Types of DBMS systems are:

• Hierarchical database

DATABASE MANAGEMENT SYSTEMS Page 9


• Network database
• Relational database ER model database

Hierarchical DBMS
In a Hierarchical database, model data is organized in a tree-like structure. Data is Stored
Hierarchically (top down or bottom up) format. Data is represented using a parent-child
relationship. In Hierarchical DBMS parent may have many children, but children have
only one parent.

Network Model
The network database model allows each child to have multiple parents. It helps you to address
the need to model more complex relationships like as the orders/parts many-to-many
relationship. In this model, entities are organized in a graph which can be accessed through
several paths.

Relational model
Relational DBMS is the most widely used DBMS model because it is one of the easiest. This
model is based on normalizing data in the rows and columns of the tables. Relational model
stored in fixed structures and manipulated using SQL.

Entity-Relationship Model

DATABASE MANAGEMENT SYSTEMS Page 10


Entity-Relationship (ER) Model is based on the notion of real-world entities and relationships
among them. While formulating real-world scenario into the database model, the ER Model
creates entity set, relationship set, general attributes and constraints.

DATA BASE USERS AND ADMINISTRATORS:


Database users are the persons who interact with the database and take the benefits of
database.
They are differentiated into different types based on the way they expect to interact with the
system.
Naive users: They are the unsophisticated users who interact with the system by using
permanent applications that already exist. Example: Online Library Management System,
ATMs (Automated Teller Machine), etc.
Application programmers: They are the computer professionals who interact with system
through DML. They write application programs.
Sophisticated users: They interact with the system by writing SQL queries directly through the
query processor without writing application programs.
Specialized users: They are also sophisticated users who write specialized database
applications that do not fit into the traditional data processing framework. Example: Expert
System, Knowledge Based System, etc.

Database Administrators
A Database Administrator (DBA) is an individual or person responsible for
controlling, maintaining, coordinating, and operating a database
management system
The life cycle of database starts from designing, implementing to administration of it. A
database for any kind of requirement needs to be designed perfectly so that it should work
without any issues. Once all the design is complete, it needs to be installed. Once this step is
complete, users start using the database. The database grows as the data grows in the
database. When the database becomes huge, its performance comes down. Also accessing the
data from the database becomes challenge. There will be unused memory in database, making
the memory inevitably huge. These administration and maintenance of database is taken care
by database Administrator – DBA.

DATABASE MANAGEMENT SYSTEMS Page 11


A DBA has many responsibilities. A good performing database is in the hands of DBA.
Database Administrators coordinate all the activities of the database system. They have
all the permissions.

Tasks/roles and responsibilities of DBA

• Creating thes chema


• Specifying integrity constraints
• Storage structure and access method definition Granting permission to other
users.
• Monitoring performance
• Routine Maintenance
• Manages data integrity and security –
Data integrity needs to be checked and managed accurately as it
protects and restricts data from unauthorized use. DBA eyes on
relationships within data to maintain data integrity.
• Database Accessibility –
Database Administrator is solely responsible for giving permission to
access data available in the database. It also makes sure who has the
right to change the content.
• Database design –
DBA is held responsible and accountable for logical, physical design,
external model design, and integrity and security control.
• Database implementation –
DBA implements DBMS and checks database loading at the time of its
implementation.
• Query processing performance –
DBA enhances query processing by improving speed, performance,
and accuracy.
• Tuning Database Performance –
If the user is not able to get data speedily and accurately then it may
lose organization’s business. So by tuning SQL commands DBA can
enhance the performance of the database.

DATABASE MANAGEMENT SYSTEMS Page 12


DBMS STRUCTURE/Overall Architecture:

DML pre-compiler:

DATABASE MANAGEMENT SYSTEMS Page 13


It converts DML statement embedded in an application program to normal
procedure calls in the host language. The pre-complier must interact with the query
processor in order to generate the appropriate code.

DDL compiler:

The DDL compiler converts the data definition statements into a set of tables. These
tables contains information concerning the database and are in a form that can be
used by other components of the dbms.
File manager:

File manager manages the allocation of space on disk storage and the data structure
used to represent information stored on disk.

Database manager:

A database manager is a program module which provides the interface between the
low level data stored in the database and the application programs and queries
submitted to the system.
The responsibilities of database manager are:
1. Interaction with file manager: The data is stored on the disk using the
file system which is provided by operating system. The database manager
translate the the different DML statements into low-level file system
commands. so The database manager is responsible for the actual
storing,retrieving and updating of data in the database.
2. Integrity enforcement:The data values stored in the database must satisfy
certain constraints(eg: the age of a person can't be less then zero).These
constraints are specified by DBA. Data manager checks the constraints and
if it satisfies then it stores the data in the database.
3. Security enforcement:Data manager checks the security measures for
database from unauthorized users.
4. Backup and recovery:Database manager detects the failures occurs due
to different causes (like disk failure, power failure,deadlock,s/w error) and
restores the database to original state of the database.
5. Concurrency control:When several users access the same database file
simultaneously, there may be possibilities of data inconsistency. It is
responsible of database manager to control the problems occurs for
concurrent transactions.
6. query processor:
The query processor used to interpret to online user’s query and
convert it into an efficient series of operations in a form capable of
being sent to the data manager for execution. The query processor

DATABASE MANAGEMENT SYSTEMS Page 14


uses the data dictionary to find the details of data file and using this
information it create query plan/access plan to execute the query.
Data Dictionary:
Data dictionary is the table which contains the information about
database objects. It contains information like
1. external, conceptual and internal database description
2. description of entities , attributes as well as meaning of data elements
3. synonyms, authorization and security codes
4. database authorization
The data stored in the data dictionary is called meta data.

Transaction Management?

• A Database Transaction is a logical unit of processing in a DBMS which entails


one or more database access operation. In a nutshell, database transactions
represent realworld events of any enterprise.
• All types of database access operation which are held between the beginning and
end transaction statements are considered as a single logical transaction in DBMS.
During the transaction the database is inconsistent. Only once the database is
committed the state is changed from one consistent state to another.

Storage Manager In DBMS


• A storage manager is a program module that provides the interface between the
lowlevel data stored in the database and the application programs and queries
submitted to the system.
• The storage manager is responsible for the interaction with the file manager.
• The raw data are stored on the disk using the file system, which is usually
provided by a conventional operating system.
• The storage manager translates the various DML statements into low-level file-
system commands. Thus, the storage manager is responsible for storing,
retrieving, and updating data in the database.
The storage manager components include:
1. Authorization and integrity manager, which tests for the satisfaction of integrity
constraints and checks the authority of users to access data.

DATABASE MANAGEMENT SYSTEMS Page 15


2. Transaction manager, which ensures that the database remains in a consistent
(correct) state despite system failures, and that concurrent transaction executions proceed
without conflicting.
3. File manager, which manages the allocation of space on disk storage and the data
structures used to represent information stored on disk.
4. Buffer manager, which is responsible for fetching data from disk storage into main
memory, and deciding what data to cache in main memory. The buffer manager is a critical
part of the database system, since it enables the database to handle data sizes that are much
larger than the size of main memory.The storage manager implements several data
structures as part of the physical system implementation:

Query Processing in DBMS

A query processor is one of the major components of a relational database or an


electronic database in which data is stored in tables of rows and columns. It complements
the storage engine, which writes and reads data to and from storage media.

Parsing and Translation

As query processing includes certain activities for data retrieval. Initially, the given user
queries get translated in high-level database languages such as SQL. It gets translated into

DATABASE MANAGEMENT SYSTEMS Page 16


expressions that can be further used at the physical level of the file system. After this, the
actual evaluation of the queries and a variety of query -optimizing transformations and takes
place.

Query Evaluation Plan o In order to fully evaluate a query, the system needs to
construct a query evaluation plan.
o The annotations in the evaluation plan may refer to the algorithms to be used for the
particular index or the specific operations.
o Such relational algebra with annotations is referred to as Evaluation Primitives. The
evaluation primitives carry the instructions needed for the evaluation of the operation.

o Thus, a query evaluation plan defines a sequence of primitive operations used for
evaluating a query. The query evaluation plan is also referred to as the query
execution plan. o A query execution engine is responsible for generating the
output of the given query. It takes the query execution plan, executes it, and finally
makes the output for the user query.

Optimization o The cost of the query evaluation can vary for different types of
queries. Although the system is responsible for constructing the evaluation plan, the user
does need not to write their query efficiently. o Usually, a database system generates an
efficient query evaluation plan, which minimizes its cost. This type of task performed by
the database system and is known as Query Optimization. o For optimizing a query,
the query optimizer should have an estimated cost analysis of each operation. It is
because the overall operation cost depends on the memory allocations to several
operations, execution costs, and so on.

DATABASE MANAGEMENT SYSTEMS Page 17


Unit 2

Important Questions in UNIT2

1.What is an attribute explain different types of attributes 10 M

2.Draw ER diagram for following System.

1. a.Hospital management system


2. b.Library management system.
3. c.University management system
4. d Airlines management system.

3. Explain concept of strong entity and weak entity. 10M

4.Explain extended ER diagram features. 10M

5.Write notes on Generalization and Aggregation in EER diagram.

6.Define Integrity constraints.Explain types of Integrity constraints. 10M

What is Relational Model?

Relational Model (RM) represents the database as a collection of relations. A relation is


nothing but a table of values. Every row in the table represents a collection of related data
values. These rows in the table denote a real-world entity or relationship.

The table name and column names are helpful to interpret the meaning of values in each row.
The data are represented as a set of relations. In the relational model, data are stored as tables.
However, the physical storage of the data is independent of the way the data are logically
organized.

Relational Model Concepts

DATABASE MANAGEMENT SYSTEMS Page 18


1. Attribute: Each column in a Table. Attributes are the properties which define a
relation. e.g., Student_Rollno, NAME,etc.

2. Tables – In the Relational model the, relations are saved in the table format. It is
stored along with its entities. A table has two properties rows and columns. Rows
represent records and columns represent attributes.
3. Tuple – It is nothing but a single row of a table, which contains a single record.
4. Relation Schema: A relation schema represents the name of the relation with its
attributes.
5. Degree: The total number of attributes which in the relation is called the degree
of the relation.
6. Cardinality: Total number of rows present in the Table.
7. Column: The column represents the set of values for a specific attribute.
8. Relation instance – Relation instance is a finite set of tuples in the RDBMS
system.
Relation instances never have duplicate tuples.
9. Relation key - Every row has one, two or multiple attributes, which is called
relation key.
10. Attribute domain – Every attribute has some pre-defined value and scope which
is known as attribute domain

Keys in DBMS
KEYS in DBMS is an attribute or set of attributes which helps you to identify a row(tuple) in
a relation(table). They allow you to find the relation between two tables. Keys help you
uniquely identify a row in a table by a combination of one or more columns in that table. Key
is also helpful for finding unique record or row from the table. Database key is also helpful
for finding unique record or row from the table.

Why we need a Key?

Here are some reasons for using sql key in the DBMS system.

DATABASE MANAGEMENT SYSTEMS Page 19


• Keys help you to identify any row of data in a table. In a real-world application, a
table could contain thousands of records. Moreover, the records could be
duplicated.
Keys ensure that you can uniquely identify a table record despite these challenges.
• Allows you to establish a relationship between and identify the relation between
tables
• Help you to enforce identity and integrity in the relationship.
Types of Keys in Database Management System

There are mainly seven different types of Keys in DBMS and each key has its different
functionality:

• Super Key - A super key is a group of single or multiple keys which identifies
rows in a table.
• Primary Key - is a column or group of columns in a table that uniquely identify
every row in that table.
• Candidate Key - is a set of attributes that uniquely identify tuples in a table.
Candidate Key is a super key with no repeated attributes.
• Alternate Key - is a column or group of columns in a table that uniquely identify
every row in that table.
• Foreign Key - is a column that creates a relationship between two tables. The
purpose of Foreign keys is to maintain data integrity and allow navigation
between two different instances of an entity.
• Compound Key - has two or more attributes that allow you to uniquely
recognize a specific record. It is possible that each column may not be unique by
itself within the database.
• Composite Key - An artificial key which aims to uniquely identify each record is
called a surrogate key. These kind of key are unique because they are created
when you don't have any natural primary key.
• Surrogate Key - An artificial key which aims to uniquely identify each record is
called a surrogate key. These kind of key are unique because they are created
when you don't have any natural primary key.

ER model

DATABASE MANAGEMENT SYSTEMS Page 20


o ER model stands for an Entity-Relationship model. This model is used to define the
data elements and relationship for a specified system. o

o It develops a conceptual design for the database. It also develops a very simple and
easy to design view of data.
o In ER modeling, the database structure is portrayed as a diagram called an
entityrelationship diagram.

For example, Suppose we design a school database. In this database, the student will be an
entity with attributes like address, name, id, age, etc. The address can be another entity with
attributes like city, street name, pin code, etc and there will be a relationship between them.

Component of ER Diagram

DATABASE MANAGEMENT SYSTEMS Page 21


1. Entity:

An entity may be any object, class, person or place. In the ER diagram, an entity can be
represented as rectangles.

Consider an organization as an example- manager, product, employee, department etc. can be


taken as an entity.

2. Attribute

The attribute is used to describe the property of an entity. Eclipse is used to represent an
attribute.

For example, id, age, contact number, name, etc. can be attributes of a student.

DATABASE MANAGEMENT SYSTEMS Page 22


Types of attributes

1.Simple Attributes

Simple attributes in an ER model diagram are independent attributes that can't be


classified further and also, can't be subdivided into any other component. These attributes
are also known as atomic attributes.

As we can see in the above example, Student is an entity represented by a


rectangle, and it consists of attributes: Roll_no, class, and Age. Also, there is a
point to be noted that we can't further subdivide the Roll_no attribute and even
the other two attributes into sub-attributes. Hence, they are known as simple
attributes of the Student entity.

2.Key Attribute

The key attribute is used to represent the main characteristics of an entity. It represents a
primary key. The key attribute is represented by an ellipse with the text underlined.

DATABASE MANAGEMENT SYSTEMS Page 23


3.Composite Attribute

An attribute that composed of many other attributes is known as a composite attribute. The
composite attribute is represented by an ellipse, and those ellipses are connected with an
ellipse.

4.Multivalued Attribute

An attribute can have more than one value. These attributes are known as a multivalued
attribute. The double oval is used to represent multivalued attribute.

For example, a student can have more than one phone number.

DATABASE MANAGEMENT SYSTEMS Page 24


5.Derived Attribute

An attribute that can be derived from other attribute is known as a derived attribute. It can be
represented by a dashed ellipse.

For example, A person's age changes over time and can be derived from another attribute
like Date of birth.

3. Relationship

A relationship is used to describe the relation between entities. Diamond or rhombus is used
to represent the relationship

Types of relationship are as follows:

DATABASE MANAGEMENT SYSTEMS Page 25


a. One-to-One Relationship

When only one instance of an entity is associated with the relationship, then it is known
as one to one relationship.

For example, A female can marry to one male, and a male can marry to one female.

b. One-to-many relationship

When only one instance of the entity on the left, and more than one instance of an entity on
the right associates with the relationship then this is known as a one-to-many relationship.

For example, Scientist can invent many inventions, but the invention is done by the only
specific scientist.

c. Many-to-one relationship

When more than one instance of the entity on the left, and only one instance of an entity on
the right associates with the relationship then it is known as a many-to-one relationship.

For example, Student enrolls for only one course, but a course can have many students.

d. Many-to-many relationship

DATABASE MANAGEMENT SYSTEMS Page 26


When more than one instance of the entity on the left, and more than one instance of an entity
on the right associates with the relationship then it is known as a many-to-many relationship.

For example, Employee can assign by many projects and project can have many employees.

Notation of ER diagram

Database can be represented using the notations. In ER diagram, many notations are used to
express the cardinality. These notations are as follows:

DATABASE MANAGEMENT SYSTEMS Page 27


Strong entity

• Strong Entity is independent of any other entity in the schema

Example – A student entity can exist without needing any other entity in the schema
or a course entity can exist without needing any other entity in the schema

• A Strong entity is nothing but an entity set having a primary key attribute or a
table that consists of a primary key column

Representation

o The strong entity is represented by a single rectangle.


o The relationship between two strong entities is represented by a single
diamond.

Examples for the strong entity


o Consider the ER diagram which consists of two entities student and


course
o Student entity is a strong entity because it consists of a primary
key called student id which is enough for accessing each record
uniquely
o In the same way, the course entity contains of course ID attribute which
is capable of uniquely accessing each row.

DATABASE MANAGEMENT SYSTEMS Page 28


a. Weak Entity

An entity that depends on another entity called a weak entity. The weak entity doesn't contain
any key attribute of its own. The weak entity is represented by a double rectangle.

Example 1 – A loan entity can not be created for a customer if the customer doesn’t
exist

Example 2 – A dependents list entity can not be created if the employee doesn’t exist

• Simply a weak entity is nothing but an entity that does not have a primary key
attribute
• It contains a partial key called a discriminator which helps in identifying a
group of entities from the entity set
• A discriminator is represented by underlining with a dashed line

Representation

o A double rectangle is used for representing a weak entity set


o The double diamond symbol is used for representing the relationship
between a strong entity and a weak entity which is known as identifying
relationship

DATABASE MANAGEMENT SYSTEMS Page 29


Extended ER Model
These concepts are used when the comes in EER schema and the resulting
schema diagrams called as EER Diagrams.

Features of EER Model

• EER creates a design more accurate to database schemas.


• It reflects the data properties and constraints more precisely.
• It includes all modeling concepts of the ER model.
• Diagrammatic technique helps for displaying the EER schema.
• It includes the concept of specialization and generalization.
It is used to represent a collection of objects that is union of objects of
different of different entity types.
Specialization and Generalization

1. Generalization
• Generalization is the process of generalizing the entities which contain
the properties of all the generalized entities.
• It is a bottom approach, in which two lower level entities combine to
form a higher level entity.
• Generalization is the reverse process of Specialization.
• It defines a general entity type from a set of specialized entity type.
• It minimizes the difference between the entities by identifying the
common features.
For example:

In the above example, Tiger, Lion, Elephant can all be generalized as Animals.

DATABASE MANAGEMENT SYSTEMS Page 30


2. Specialization
• Specialization is a process that defines a group entities which is divided
into sub groups based on their characteristic.
• It is a top down approach, in which one higher entity can be broken
down into two lower level entity.
• It maximizes the difference between the members of an entity by
identifying the unique characteristic or attributes of each member.
• It defines one or more sub class for the super class and also forms the
superclass/subclass relationship.
For example


In the above example, Employee can be specialized as Developer or
Tester, based on what role they play in an Organization.

DATABASE MANAGEMENT SYSTEMS Page 31


Integrity Constraints o
Integrity constraints are a set of rules. It is used to maintain the quality of information.

o Integrity constraints ensure that the data insertion, updating, and other processes have to
be performed in such a way that data integrity is not affected.

o Thus, integrity constraint is used to guard against accidental damage to the database.

Types of Integrity Constraint

1. Domain constraints o Domain constraints can be defined as the definition of


a valid set of values for an attribute.
o The data type of domain includes string, character, integer, time, date, currency, etc.
The value of the attribute must be available in the corresponding domain.

Example:

DATABASE MANAGEMENT SYSTEMS Page 32


2. Entity integrity constraints o The entity integrity constraint states that
primary key value can't be null.

o This is because the primary key value is used to identify individual rows in relation
and if the primary key has a null value, then we can't identify those rows.
o A table can contain a null value other than the primary key field.

3. Referential

Integrity Constraints o A referential integrity constraint is specified


between two tables.

o In the Referential integrity constraints, if a foreign key in Table 1 refers to the Primary
Key of Table 2, then every value of the Foreign Key in Table 1 must be null or be
available in Table 2.

DATABASE MANAGEMENT SYSTEMS Page 33


4. Key constraints o Keys are the entity set that is used to identify an entity within its
entity set uniquely.

o An entity set can have multiple keys, but out of which one key will be the primary
key. A primary key can contain a unique and null value in the relational table.

Unit3
Important questions on UNIT3

1. 10M

DATABASE MANAGEMENT SYSTEMS Page 34


Relational Algebra
• Relational Algebra is procedural query language, which takes Relation as input and
generates relation as output. Relational algebra mainly provides theoretical
foundation for relational databases and SQL.
• Relational algebra is a procedural query language, it means that it tells what data to
be retrieved and how to be retrieved.
• Relational Algebra works on the whole table at once, so we do not have to use loops
etc to iterate over all the rows (tuples) of data one by one.
• All we have to do is specify the table name from which we need the data, and in a
single line of command, relational algebra will traverse the entire given table to
fetch data for you.

DATABASE MANAGEMENT SYSTEMS Page 35


Basic/Fundamental Operations:

1.Select (σ)
2. Project (∏)
3. Union ( )
4. Set Difference (-)
5. Cartesian product (X)
6. Rename (ρ)

1. Select Operation (σ) :This is used to fetch rows (tuples/records)

from table(relation) which satisfies a given condition. Syntax: σp(r)

➢ σ is the predicate
➢ r stands for relation which is the name of the table

➢ p is prepositional logic ex: σage > 17 (Student)


This will fetch the tuples(rows) from table Student, for which age will be greater than
17.

σage > 17 and gender = 'Male' (Student)


This will return tuples(rows) from table Student with information of male
students, of age more than 17.

DATABASE MANAGEMENT SYSTEMS Page 36


BRANCH_NAME LOAN_NO AMOUNT

Downtownn L-17 1000

Redwood L-23 2000

Perryride L-15 1500

Downtown L-14 1500

Mianus L-13 500

Roundhill L-11 900

Perryride L-16 1300

DATABASE MANAGEMENT SYSTEMS Page 41

Input:
σ BRANCH_NAME="perryride" (LOAN)

Output:

BRANCH_NAME LOAN_NO AMOUNT

DATABASE MANAGEMENT SYSTEMS Page 37


Perryride L-15 1500

Perryride L-16 1300

Project Operation (∏):


• Project operation is used to project only a certain set of attributes of a
relation. In simple words, If you want to see only the names all of the
students in the Student table, then you can use Project Operation.
• It will only project or show the columns or attributes asked for, and will also
remove duplicate data from the columns.
Syntax of Project Operator (∏)
∏ column_name1, column_name2, ...., column_nameN(table_name)

Example:
∏Name, Age(Student)
Above statement will show us only the Name and Age columns for all the
rows of data in Student table.

Example: CUSTOMER RELATION

NAME STREET CITY

Jones Main Harrison

Smith North Rye

Hays Main Harrison

DATABASE MANAGEMENT SYSTEMS Page 38


Curry North Rye

Johnson Alma Brooklyn

Brooks Senator Brooklyn

Input:
∏ NAME, CITY
(CUSTOMER) Output:

NAME CITY

Jones Harrison

Smith Rye

Hays Harrison

Curry Rye

Johnson Brooklyn

Brooks Brooklyn

Union Operation ( ):

• This operation is used to fetch data from two relations(tables) or temporary


relation(result of another operation).

DATABASE MANAGEMENT SYSTEMS Page 39


• For this operation to work, the relations(tables) specified should have same
number of attributes(columns) and same attribute domain. Also the duplicate
tuples are autamatically eliminated from the result.
Syntax: A B
∏Student(RegularClass) ∏Student(ExtraClass)
Example:

DEPOSITOR RELATION
CUSTOMER_NAME ACCOUNT_NO

Johnson A-101

Smith A-121

Mayes A-321

Turner A-176

Johnson A-273

Jones A-472

Lindsay A-284

BORROW RELATION

CUSTOMER_NAME LOAN_NO

DATABASE MANAGEMENT SYSTEMS Page 40


Jones L-17

Smith L-23

Hayes L-15

Jackson L-14

Curry L-93

Smith L-11

Williams L-17

Input:
∏ CUSTOMER_NAME (BORROW) ∏ CUSTOMER_NAME (DEPOSITOR)

Output:

CUSTOMER_NAME

Johnson

Smith

Hayes

DATABASE MANAGEMENT SYSTEMS Page 41


Turner

Jones

Lindsay

Jackson

Curry

Williams

Mayes

Set Difference (-):


This operation is used to find data present in one relation and not present in
the second relation. This operation is also applicable on two relations, just
like Union operation. Syntax: A - B where A and B are relations.
For example, if we want to find name of students who attend the regular class but
not the extra class, then, we can use the below operation:
∏Student(RegularClass) - ∏Student(ExtraClass)
Input: ∏ CUSTOMER_NAME (BORROW) ∩ ∏ CUSTOMER_NAME
(DEPOSITOR)

CUSTOMER_NAME

DATABASE MANAGEMENT SYSTEMS Page 42


Smith

Jones

Cartesian Product (X):

This is used to combine data from two different relations(tables) into one and
fetch data from the combined relation.
Syntax: A X B
For example, if we want to find the information for Regular Class and Extra Class
which are conducted during morning, then, we can use the following operation:
σtime = 'morning' (RegularClass X ExtraClass)
For the above query to work, both RegularClass and ExtraClass
should have the attribute time. Notation: E X D

EMPLOYEE
EMP_ID EMP_NAME EMP_DEPT

1 Smith A

2 Harry C

3 John B

DATABASE MANAGEMENT SYSTEMS Page 43


DEPARTMENT

DEPT_NO DEPT_NAME

A Marketing

B Sales

C Legal

Input:
EMPLOYEE X DEPARTMENT

Output:

EMP_ID EMP_NAME EMP_DEPT DEPT_NO DEPT_NAME

1 Smith A A Marketing

1 Smith A B Sales

1 Smith A C Legal

2 Harry C A Marketing

DATABASE MANAGEMENT SYSTEMS Page 44


2 Harry C B Sales

2 Harry C C Legal

3 John B A Marketing

3 John B B Sales

3 John B C Legal

Rename Operation (ρ):

This operation is used to rename the output relation for any query operation which
returns result like Select, Project etc. Or to simply rename a relation(table)
Syntax: ρ(RelationNew, RelationOld)

The rename operation is used to rename the output relation. It is denoted by rho
(ρ).

Example: We can use the rename operator to rename STUDENT relation to


STUDENT1.
ρ(STUDENT1, STUDENT)

Joins in Relational algebra:


Please refer PDF provided in classroom for relational algebra of JOIN .Even
though concept of join is same, symbol used in relational algebra for join is
different than SQL syntax for join

DATABASE MANAGEMENT SYSTEMS Page 45


SQL syntax for JOINS:

• A JOIN clause is used to combine rows from two or more tables, based on
a related column between them.
• Join in DBMS is a binary operation which allows you to combine join
product and selection in one single statement.
• The goal of creating a join condition is that it helps you to combine the
data from two or more DBMS tables.
• The tables in DBMS are associated using the primary key and foreign
keys.

Types of SQL JOIN


1. INNER JOIN /Natural Join
2. Outer Join
a LEFT Outer JOIN

b RIGHT Outer JOIN


c FULL Outer JOIN

Table name: EMPLOYEE

EMP_ID EMP_NAME CITY SALARY AGE

1 Angelina Chicago 200000 30

2 Robert Austin 300000 26

3 Christian Denver 100000 42

DATABASE MANAGEMENT SYSTEMS Page 46


4 Kristen Washington 500000 29

5 Russell Los angels 200000 36

6 Marry Canada 600000 48


PROJECT

PROJECT_NO DEPARTMENT
EMP_ID

101 1 Testing

102 2 Development

103 3 Designing

104 4 Development

1. INNER JOIN

In SQL, INNER JOIN selects records that have matching values in both tables as
long as the condition is satisfied.

It returns the combination of all rows from both the tables where the condition
satisfies.

Syntax
SELECT table1.column1, table1.column2

DATABASE MANAGEMENT SYSTEMS Page 47


FROM table1 INNER JOIN table2
ON table1.matching_column = table2.matching_column;

Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE INNER JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

2. LEFT JOIN

The SQL left join returns all the values from left table and the matching values
from the right table. If there is no matching join value, it will return NULL.

DATABASE MANAGEMENT SYSTEMS Page 48


Syntax
SELECT table1.column1, table1.column2 FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;

Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE LEFT JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

Russell NULL

DATABASE MANAGEMENT SYSTEMS Page 49


Marry NULL

3. RIGHT JOIN
In SQL, RIGHT JOIN returns all the values from the values from the rows of right
table and the matched values from the left table. If there is no matching in both
tables, it will return
NULL.

Syntax
SELECT table1.column1, table1.column2
FROM table1 RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;

Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE RIGHT JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

DATABASE MANAGEMENT SYSTEMS Page 50


Angelina Testing

Robert Development

Christian Designing

Kristen Development

4. FULL JOIN

In SQL, FULL JOIN is the result of a combination of both left and right outer
join. Join tables have all the records from both tables. It puts NULL on the place
of matches not found.

Syntax
SELECT table1.column1, table1.column2
FROM table1 FULL JOIN table2
ON table1.matching_column = table2.matching_column;

Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE

DATABASE MANAGEMENT SYSTEMS Page 51


FULL JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

Russell NULL

Marry NULL

Division Operator in SQL


Division Operator (÷): Division operator A÷B can be applied if and only if:
• Attributes of B is proper subset of Attributes of A.
• The relation returned by division operator will have attributes = (All attributes
of A – All Attributes of B)
• The relation returned by division operator will return those tuples from
relation A which are associated to every B’s tuple.

The division operator is used when we have to evaluate queries which contain
the keyword ALL.

DATABASE MANAGEMENT SYSTEMS Page 52


Table 1: Course_Taken → It consists of the names of Students against the
courses that they have taken.

Student_Name Course

Robert Databases

Robert Programming Languages

David Databases

David Operating Systems

DATABASE MANAGEMENT SYSTEMS Page 53


Hannah Programming Languages

Hannah Machine Learning

Tom Operating Systems

Table 2: Course_Required → It consists of the courses that one is required to


take in order to graduate.

Course

Databases

Programming Languages

1.Find all the students

Create a set of all students that have taken courses. This can be done easily using
the following command.

DATABASE MANAGEMENT SYSTEMS Page 54


CREATE TABLE AllStudents AS SELECT DISTINCT Student_Name
FROM Course_Taken
This command will return the table AllStudents, as the resultset:

Student_name

Robert

David

Hannah

Tom

DATABASE MANAGEMENT SYSTEMS Page 55


Student_Name Course

Robert Databases

Robert Programming Languages

David Databases

David Programming Languages

Hannah Databases

Hannah Programming Languages

Tom Databases

DATABASE MANAGEMENT SYSTEMS Page 56


T

DATABASE MANAGEMENT SYSTEMS Page 57


Unit-5
Important Questions
1.What is deadlock?Explain deadlock handling in DBMS 10 M
2.Describe ACID properties of transaction management.Draw state transition
diagram of transaction. 10M
3.Explain Log based recovery. 10M
4.Explain Timestamp ordering protocol. 10 M
5.What is transaction ?Discuss ACID properties of transaction. 10M

TRANSACTION MANAGEMENT IN DBMS:

• A transaction is a set of logically related operations.

• A transaction can be defined as a group of tasks. A single task is the minimum


processing unit which cannot be divided further.
• Let‟s take an example of a simple transaction. Suppose a bank employee transfers Rs
500 from A's account to B's account. This very simple and small transaction involves
several low-level tasks.
• A’s Account
• Open_Account(A)
• Old_Balance = A.balance
• New_Balance = Old_Balance - 500
• A.balance = New_Balance
Close_Account(A)
• B’s Account
• Open_Account(B)
• Old_Balance = B.balance
• New_Balance = Old_Balance + 500
• B.balance = New_Balance
Close_Account(B)

• The main problem that can happen during a transaction is that the transaction can fail
before finishing the all the operations in the set. This can happen due to power
failure, system crash etc.

DATABASE MANAGEMENT SYSTEMS Page 58


• This is a serious problem that can leave database in an inconsistent state. Assume that
transaction fail after third operation (see the example above) then the amount would
be deducted from your account but your friend will not receive it.

To solve this problem, we have the following two operations

Commit: If all the operations in a transaction are completed successfully then commit those
changes to the database permanently.

Rollback: If any of the operation fails then rollback all the changes done by previous
operations.

TRANSACTION PROPERTIES

The transaction has the four properties. These are used to maintain consistency in a database,
before and after the transaction.

Property of Transaction
1. Atomicity
2. Consistency
3. Isolation
4. Durability

Atomicity o It states that all operations of the transaction take place at once if not, the
transaction is aborted.
o There is no midway, i.e., the transaction cannot occur partially. Each transaction is
treated as one unit and either run to completion or is not executed at all.

Atomicity involves the following two operations:

Abort: If a transaction aborts then all the changes made are not visible.
Commit: If a transaction commits then all the changes made are visible.

Consistency o The integrity constraints are maintained so that the database is consistent
before and after the transaction.

DATABASE MANAGEMENT SYSTEMS Page 59


o The execution of a transaction will leave a database in either its prior stable state or a
new stable state.
o The consistent property of database states that every transaction sees a consistent
database instance.
o The transaction is used to transform the database from one consistent state to another
consistent state.

Isolation o It shows that the data which is used at the time of execution of a
transaction cannot be used by the second transaction until the first one is completed.
o In isolation, if the transaction T1 is being executed and using the data item X, then
that data item can't be accessed by any other transaction T2 until the transaction T1
ends.
o The concurrency control subsystem of the DBMS enforced the isolation property.

Durability o The durability property is used to indicate the performance of the database's
consistent state. It states that the transaction made the permanent changes.

• They cannot be lost by the erroneous operation of a faulty transaction or by the system
failure. When a transaction is completed, then the database reaches a state known as the
consistent state. That consistent state cannot be lost, even in the event of a system's
failure.
• o The recovery subsystem of the DBMS has the responsibility of Durability property.

STATES OF Transactions

Transactions can be implemented using SQL queries and Server. In the below-given diagram,
you can see how transaction states works.

DATABASE MANAGEMENT SYSTEMS Page 60


Fig:State transaction diagram

Active state

o The active state is the first state of every transaction. In this state, the transaction is
being executed.
o For example: Insertion or deletion or updating a record is done here. But all the
records are still not saved to the database.

Partially committed

o In the partially committed state, a transaction executes its final operation, but the data
is still not saved to the database.

o In the total mark calculation example, a final display of the total marks step is
executed in this state.

Committed

A transaction is said to be in a committed state if it executes all its operations successfully. In


this state, all the effects are now permanently saved on the database system.

Failed state

o If any of the checks made by the database recovery system fails, then the transaction
is said to be in the failed state.
o In the example of total mark calculation, if the database is not able to fire a query to
fetch the marks, then the transaction will fail to execute.

DATABASE MANAGEMENT SYSTEMS Page 61


Aborted

o If any of the checks fail and the transaction has reached a failed state then the
database recovery system will make sure that the database is in its previous consistent
state. If not then it will abort or roll back the transaction to bring the database into a
consistent state.

o If the transaction fails in the middle of the transaction then before executing the
transaction, all the executed transactions are rolled back to its consistent state. o
After aborting the transaction, the database recovery module will select one of the
two operations:
1. Re-start the transaction
2. Kill the transaction

IMPLEMENTATION OF ATOMICITY AND DURABILITY

The recovery-management component of a database system can support atomicity and durability
by a variety of schemes.
E.g. the shadow-database scheme:

Shadow copy:

• In the shadow-copy scheme, a transaction that wants to update the database first creates a
complete copy of the database.
• All updates are done on the new database copy, leaving the original copy, the shadow copy,
untouched. If at any point the transaction has to be aborted, the system merely deletes the
new copy. The old copy of the database has not been affected.
• This scheme is based on making copies of the database, called shadow copies, assumes that
only one transaction is active at a time.
• The scheme also assumes that the database is simply a file on disk. A pointer called
dbpointer is maintained on disk; it points to the current copy of the database.

If the transaction completes, it is committed as follows:

DATABASE MANAGEMENT SYSTEMS Page 62


• First, the operating system is asked to make sure that all pages of the new copy of the
database have been written out to disk. (Unix systems use the flush command for this
purpose.)
• After the operating system has written all the pages to disk, the database system updates the
pointer db-pointer to point to the new copy of the database;
• the new copy then becomes the current copy of the database. The old copy of the database is
then deleted.

Figure below depicts the scheme, showing the database state before and after the update.

SCHEDULE

A series of operation from one transaction to another transaction is known as schedule. It is


used to preserve the order of the operation in each of the individual transaction.

DATABASE MANAGEMENT SYSTEMS Page 63


1. SERIAL SCHEDULE

The serial schedule is a type of schedule where one transaction is executed completely before
starting another transaction. In the serial schedule, when the first transaction completes its
cycle, then the next transaction is executed.

For example: Suppose there are two transactions T1 and T2 which have some operations. If
it has no interleaving of operations, then there are the following two possible outcomes:

1. Execute all the operations of T1 which was followed by all the operations of T2.
2. Execute all the operations of T1 which was followed by all the operations of T2.

o In the given (a) figure, Schedule A shows the serial schedule where T1 followed by
T2.
o In the given (b) figure, Schedule B shows the serial schedule where T2 followed by
T1.

2. NON-SERIAL SCHEDULE
o If interleaving of operations is allowed, then there will be non-serial schedule.

o It contains many possible orders in which the system can execute the individual
operations of the transactions.
o In the given figure (c) and (d), Schedule C and Schedule D are the non-serial
schedules. It has interleaving of operations.

3. SERIALIZABLE SCHEDULE

DATABASE MANAGEMENT SYSTEMS Page 64


o The serializability of schedules is used to find non-serial schedules that allow the
transaction to execute concurrently without interfering with one another.

o It identifies which schedules are correct when executions of the transaction have
interleaving of their operations. o A non-serial schedule will be serializable if
its result is equal to the result of its transactions executed serially.

SERIALIZABILITY IN DBMS
Some non-serial schedules may lead to inconsistency of the database.

• Serializability is a concept that helps to identify which non-serial schedules are correct and
will maintain the consistency of the database.

Types of Serializability

Serializability is mainly of two types-

1. Conflict Serializability
2. View Serializability

Conflict Serializability

If a given non-serial schedule can be converted into a serial schedule by swapping its
nonconflicting operations, then it is called as a conflict serializable schedule.

Conflicting Operations
Two operations are called as conflicting operations if all the following conditions hold true for
them-

DATABASE MANAGEMENT SYSTEMS Page 65


• Both the operations belong to different transactions
• Both the operations are on the same data item
• At least one of the two operations is a write operation

Example-

Consider the following schedule-

In this schedule,

• W1 (A) and R2 (A) are called as conflicting operations.


• This is because all the above conditions hold true for them.
Checking Whether a Schedule is Conflict Serializable Or Not-

Follow the following steps to check whether a given non-serial schedule is conflict
serializable or not-

Follow the following steps to check whether a given non-serial schedule is conflict
serializable or not-

Step-01:

Find and list all the conflicting operations.

Step-02:

DATABASE MANAGEMENT SYSTEMS Page 66


Start creating a precedence graph by drawing one node for each transaction.

Step-03:

Draw an edge for each conflict pair such that if Xi (V) and Yj (V) forms a conflict pair then
draw an edge from Ti to Tj.

• This ensures that Ti gets executed before Tj.


Step-04:

Check if there is any cycle formed in the graph.

• If there is no cycle found, then the schedule is conflict serializable otherwise not.
VIEW SERIALIZABILITY?

View Serializability is a process to find out that a given schedule is view serializable or not.

To check whether a given schedule is view serializable, we need to check whether the given
schedule is View Equivalent to its serial schedule. Lets take an example to understand what
I mean by that.

View Serializability o A schedule will view serializable if it is view equivalent


to a serial schedule.

o If a schedule is conflict serializable, then it will be view serializable. o

The view serializable which does not conflict serializable contains blind

writes.

View Equivalent

Two schedules S1 and S2 are said to be view equivalent if they satisfy the following
conditions:

1. Initial Read:

An initial read of both schedules must be the same. Suppose two schedule S1 and S2. In
schedule S1, if a transaction T1 is reading the data item A, then in S2, transaction T1 should
also read A.

DATABASE MANAGEMENT SYSTEMS Page 67


Above two schedules are view equivalent because Initial read operation in S1 is done by T1
and in S2 it is also done by T1.

2. Updated Read

In schedule S1, if Ti is reading A which is updated by Tj then in S2 also, Ti should read A


which is updated by Tj.

3. Final Write

A final write must be the same between both the schedules. In schedule S1, if a transaction
T1 updates A at last then in S2, final writes operations should also be done by T1.

DATABASE MANAGEMENT SYSTEMS Page 68


Above two schedules is view equal because Final write operation in S1 is done by T3
and in S2, the final write operation is also done by T3.

Recoverability of Schedule

Sometimes a transaction may not execute completely due to a software issue, system crash or
hardware failure. In that case, the failed transaction has to be rollback. But

Serializable – This is the Highest isolation level. A serializable execution is guaranteed


to be serializable. Serializable execution is defined to be an execution of operations in
which concurrently executing transactions appears to be serially executing.

FAILURE CLASSIFICATION

To find that where the problem has occurred, we generalize a failure into the following
categories:

1. Transaction failure
2. System crash
3. Disk failure

1. Transaction failure

DATABASE MANAGEMENT SYSTEMS Page 69


The transaction failure occurs when it fails to execute or when it reaches a point from
where it can't go any further. If a few transaction or process is hurt, then this is called
as transaction failure.

Reasons for a transaction failure could be -

1. Logical errors: If a transaction cannot complete due to some code error or an


internal error condition, then the logical error occurs.
2. Syntax error: It occurs where the DBMS itself terminates an active
transaction because the database system is not able to execute it. For
example, The system aborts an active transaction, in case of deadlock or
resource unavailability.

2. System Crash o System failure can occur due to power failure or other hardware

or software failure. Example: Operating system error.

Fail-stop assumption: In the system crash, non-volatile storage is assumed


not to be corrupted.

3. Disk Failure

o It occurs where hard-disk drives or storage drives used to fail frequently. It


was a common problem in the early days of technology evolution.
o Disk failure occurs due to the formation of bad sectors, disk head crash, and
unreachability to the disk or any other failure, which destroy all or part of disk
storage.

CONCURRENT EXECUTION OF TRANSACTION

In the transaction process, a system usually allows executing more than one transaction
simultaneously. This process is called a concurrent execution.

Advantages of concurrent execution of a transaction

1. Decrease waiting time or turnaround time.

DATABASE MANAGEMENT SYSTEMS Page 70


2. Improve response time
3. Increased throughput or resource utilization.

Problems with Concurrent Execution

In a database transaction, the two main operations are READ and WRITE operations. So,
there is a need to manage these two operations in the concurrent execution of the
transactions as if these operations are not performed in an interleaved manner, and the data
may become inconsistent. So, the following problems occur with the Concurrent Execution
of the operations:

1: Lost Update Problems (W - W Conflict)

2. Dirty Read Problems (W-R Conflict)

3. Unrepeatable Read Problem (W-R Conflict)

1. Lost update problem (Write – Write conflict)


This type of problem occurs when two transactions in database access the same data item
and have their operations in an interleaved manner that makes the value of some database
item incorrect.
If there are two transactions T1 and T2 accessing the same data item value and then update
it, then the second record overwrites the first record.
Example: Let’s take the value of A is 100

DATABASE MANAGEMENT SYSTEMS Page 71


• At t1 time, T1 transaction reads the value of A i.e., 100. At t2 time, T1 transaction
deducts the value of A by 50. At t3 time, T2 transactions read the value of A i.e., 100.
• At t4 time, T2 transaction adds the value of A by 150.
• At t5 time, T1 transaction writes the value of A data item on the basis of value seen at
time t2 i.e.,

DATABASE MANAGEMENT SYSTEMS Page 72


DATABASE MANAGEMENT SYSTEMS Page 73
At t2 time, T1 transaction adds the value of A by 20.
At t3 time, T1transaction writes the value of A (120) in the database.
• At t4 time, T2 transactions read the value of A data item i.e., 120.
• At t5 time, T2 transaction adds the value of A data item by 30.
• At t6 time, T2transaction writes the value of A (150) in the database.
• At t7 time, a T1 transaction fails due to power failure then it is rollback according to
atomicity property of transaction (either all or none).
• So, transaction T2 at t4 time contains a value which has not been committed in the
database.
The value read by the transaction T2 is known as a dirty read.

Unrepeatable read (R-W Conflict)

It is also known as an inconsistent retrieval problem. If a transaction T1 reads a value of data


item twice and the data item is changed by another transaction T2 in between the two read
operation. Hence T1 access two different values for its two read operation of the same data
item.

DATABASE MANAGEMENT SYSTEMS Page 74


• At t1 time, T1 transaction reads the value of A i.e., 100.
At t2 time, T2transaction reads the value of A i.e., 100.
At t3 time, T2 transaction adds the value of A data item by 30.
• At t4 time, T2 transaction writes the value of A (130) in the database.
• Transaction T2 updates the value of A. Thus, when another read statement is performed
by transaction T1, it accesses the new value of A, which was updated by T2. Such type
of conflict is known as R-W conflict.

CONCURRENCY CONTROL

Concurrency Control is the working concept that is required for controlling and managing the
concurrent execution of database operations and thus avoiding the inconsistencies in the
database. Thus, for maintaining the concurrency of the database, we have the concurrency
control protocols.

Concurrency Control Protocols

The concurrency control protocols ensure the atomicity, consistency, isolation,


durability and serializability of the concurrent execution of the database transactions.
Therefore, these protocols are categorized as:

o Lock Based Concurrency Control Protocol

o Time Stamp Concurrency Control Protocol

Lock-Based Protocol

In this type of protocol, any transaction cannot read or write data until it acquires an
appropriate lock on it. There are two types of lock:

1. Shared lock:

DATABASE MANAGEMENT SYSTEMS Page 75


o It is also known as a Read-only lock. In a shared lock, the data item can only read by
the transaction.
o It can be shared between the transactions because when the transaction holds a lock,
then it can't update the data on the data item.

2.Exclusive lock

• Exclusive Lock allows the data item to be read as well as written. This is a one-time
use mode that can't be utilized on the exact data item twice. To obtain X-lock, the user
needs to make use of the lock-x instruction. After finishing the 'write' step,
transactions can unlock the data item
• At any given time, the exclusive locks can only be owned by one transaction.
• By imposing an X lock on a transaction that needs to update a person's account
balance, for example, you can allow it to proceed. As a result of the exclusive lock, the
second transaction is unable to read or write.
• The other name for an exclusive lock is write lock.

TWO-PHASE LOCKING (2PL)

o The two-phase locking protocol divides the execution phase of the transaction into
three parts.
o In the first part, when the execution of the transaction starts, it seeks permission for
the lock it requires.
o In the second part, the transaction acquires all the locks. The third phase is started as
soon as the transaction releases its first lock.
o In the third phase, the transaction cannot demand any new locks. It only releases the
acquired locks.

DATABASE MANAGEMENT SYSTEMS Page 76


There are two phases of 2PL:

Growing phase: In the growing phase, a new lock on the data item may be acquired by the
transaction, but none can be released.

Shrinking phase: In the shrinking phase, existing lock held by the transaction may be
released, but no new locks can be acquired.

In the below example, if lock conversion is allowed then the following phase can happen:

1. Upgrading of lock (from S(a) to X (a)) is allowed in growing phase.

2. Downgrading of lock (from X(a) to S(a)) must be done in shrinking phase.

Example:

DATABASE MANAGEMENT SYSTEMS Page 77


The following way shows how unlocking and locking work with 2-PL.

DATABASE MANAGEMENT SYSTEMS Page 78


TIMESTAMP ORDERING PROTOCOL
o The Timestamp Ordering Protocol is used to order the transactions based on their
Timestamps. The order of transaction is nothing but the ascending order of the
transaction creation.

o The priority of the older transaction is higher that's why it executes first. To
determine the timestamp of the transaction, this protocol uses system time or logical
counter.
o The lock-based protocol is used to manage the order between conflicting pairs among
transactions at the execution time. But Timestamp based protocols start working as
soon as a transaction is created.

Basic Timestamp ordering protocol works as follows:

1. Check the following condition whenever a transaction Ti issues a Read (X) operation:

o If W_TS(X) >TS(Ti) then the operation is rejected. o

o If W_TS(X) <= TS(Ti) then the operation is executed. o

o Timestamps of all the data items are updated.

2. Check the following condition whenever a transaction Ti issues a Write(X) operation:

o If TS(Ti) < R_TS(X) then the operation is rejected. o

o If TS(Ti) < W_TS(X) then the operation is rejected and Ti is rolled back otherwise
the operation is executed.

Where,

TS(TI) denotes the timestamp of the transaction Ti.

R_TS(X) denotes the Read time-stamp of data-item X.

W_TS(X) denotes the Write time-stamp of data-item X.

DATABASE MANAGEMENT SYSTEMS Page 79


Validation Based Protocol

Validation phase is also known as optimistic concurrency control technique. In the validation
based protocol, the transaction is executed in the following three phases:

1. Read phase: In this phase, the transaction T is read and executed. It is used to read
the value of various data items and stores them in temporary local variables. It can
perform all the write operations on temporary variables without an update to the
actual database.
2. Validation phase: In this phase, the temporary variable value will be validated
against the actual data to see if it violates the serializability.
3. Write phase: If the validation of the transaction is validated, then the temporary
results are written to the database or system otherwise the transaction is rolled back.

Here each phase has the following different timestamps:

Start(Ti): It contains the time when Ti started its execution.

Validation (Ti): It contains the time when Ti finishes its read phase and starts its validation
phase.

Finish(Ti): It contains the time when Ti finishes its write phase.

o This protocol is used to determine the time stamp for the transaction for serialization
using the time stamp of the validation phase, as it is the actual phase which
determines if the transaction will commit or rollback.
o Hence TS(T) = validation(T).

o The serializability is determined during the validation process. It can't be decided in


advance. o While executing the transaction, it ensures a greater degree of
concurrency and also less number of conflicts. o Thus it contains transactions
which have less number of rollbacks.

THOMAS WRITE RULE

DATABASE MANAGEMENT SYSTEMS Page 80


Thomas Write Rule provides the guarantee of serializability order for the protocol. It
improves the Basic Timestamp Ordering Algorithm.

The basic Thomas write rules are as follows:


o If TS(T) < R_TS(X) then transaction T is aborted and rolled back, and operation is
rejected. o If TS(T) < W_TS(X) then don't execute the W_item(X) operation of
the transaction and continue processing. o If neither condition 1 nor condition 2
occurs, then allowed to execute the WRITE operation by transaction Ti and set
W_TS(X) to TS(T).

DATABASE MANAGEMENT SYSTEMS Page 81


Database Recovery:

• When a system crashes, it may have several transactions being executed and various
files opened for them to modify the data items.
• Database recovery means recovering the data when it get deleted, hacked or
damaged accidentally.
• Atomicity is must whether is transaction is over or not it should reflect in the
database permanently or it should not effect the database at all.

When a DBMS recovers from a crash, it should maintain the following −

• It should check the states of all the transactions, which were being executed.

• A transaction may be in the middle of some operation; the DBMS must ensure the
atomicity of the transaction in this case.

• It should check whether the transaction can be completed now or it needs to be rolled
back.

• No transactions would be allowed to leave the DBMS in an inconsistent state.

There are two types of techniques, which can help a DBMS in recovering as well as
maintaining the atomicity of a transaction −

• Maintaining the logs of each transaction, and writing them onto some stable storage
before actually modifying the database.

• Maintaining shadow paging, where the changes are done on a volatile memory, and
later, the actual database is updated.

DATABASE MANAGEMENT SYSTEMS Page 82


Log-Based Recovery o

The log is a sequence of records. Log of each transaction is maintained in some stable

storage so that if any failure occurs, then it can be recovered from there.

• If any operation is performed on the database, then it will be recorded in the log.
o But the process of storing the logs should be done before the actual
transaction is applied in the database.
• When transaction Ti starts, it registers itself by writing a
<Ti start>log record
• Before Ti executes write(X), a log record
<Ti, X, V1, V2>
is written, where V1 is the value of X before the write (the old value), and V2 is
the value to be written to X (the new value).
• When Ti finishes it last statement, the log record <Ti commit> is written.

There are two approaches to modify the database:

1. Deferred database modification:

o The deferred modification technique occurs if the transaction does not modify the
database until it has committed.
o In this method, all the logs are created and stored in the stable storage, and the
database is updated when a transaction commits.

2. Immediate database modification:

o The Immediate modification technique occurs if database modification occurs while


the transaction is still active.
o In this technique, the database is modified immediately after every operation. It
follows an actual database modification.

Example of immediate database modification log is given below

DATABASE MANAGEMENT SYSTEMS Page 83


Undo and Redo Operations – Because all database modifications must be
preceded by creation of log record, the system has available both the old value
prior to the modification of the data item and new value that is to be written for
data item. This allows system to perform redo and undo operations as
appropriate:
1. Undo: using a log record sets the data item specified in log record to
old value.
2. Redo: using a log record sets the data item specified in log record to
new value.

Deadlocck Handling inDBMS


A deadlock situation,which may arise where two concurrent transactions are working on
a database, and they both are holding two different locks, and both are waiting for each
other to release the other locks.

Let us consider we have some organization’s database. In the database, we have one
employee table and one salary table.
Suppose two transactions T1 and T2, are working concurrently, the transaction T1 holds
the lock of some rows in the employee table and the transaction T2 holds the lock of
some rows in the salary table.
Now, consider a situation where T1 wants to make some changes in the salary table,
and at the same time, T2 also wants to make some changes in the employee table.

DATABASE MANAGEMENT SYSTEMS Page 84


Both the transactions are waiting for the other to release locks; they will have to wait for
an infinite amount of time to execute completely. The infinite wait means we have a
Deadlock situation here.

Deadlock Avoidance
• Deadlock avoidance algorithms are used to avoid the deadlock before it
occurs than to deal with it.

• It helps to save the resources by avoiding rebooting the database server.


Deadlock Detection
In a database management system, if a transaction gets blocked indefinitely to obtain a
lock, the system uses deadlock detection methods to detect if the transaction is in a
deadlock or not. One of the methods is Wait-for-graph.
In this method, we draw a graph for the transactions and their locks. If the graph contains
a cycle, then a deadlock has occurred.

Prevention is better than cure, So let’s see how we prevent deadlocks.

Deadlock Prevention
There are two methods for Deadlock Prevention:
1. Wait-Die Method

2. Wound-Wait Method

Wait-Die Method
Wait-Die is a non-preemptive type of deadlock prevention method. Since it is non-
preemptive, CPU time will be distributed unevenly among all transactions. One

DATABASE MANAGEMENT SYSTEMS Page 85


transaction cannot be preempted between executing (it executes until it’s complete Burst
Time).
In the Wait-Die Method, a transaction is made to wait if it has arrived before the other
transaction or is killed.
Let’s consider two transactions Ti and Tj. Consider a situation where Ti requests the data
member lock which Tj holds. Then Ti can wait only if the timestamp of Ti is lesser than
that of the Tj.

Wound-Wait Method
Wound-Wait is a preemptive type deadlock prevention method. It ensures that all
transactions get equal CPU time. The transactions are not executed to entire burst-time;
they can be preempted during their execution to get CPU time for other transactions.
The wound-wait schema is the opposite of the wait-die schema; here, the transaction
waits if it has arrived after the other transaction, or the other transaction is rolled back.
Again, let’s consider two transactions Ti and Tj, where Ti requests a data-lock held by Tj.

DATABASE MANAGEMENT SYSTEMS Page 86

You might also like