You are on page 1of 124

Fundamentals of Database Systems Department of ECE

UNIT – I
INTRODUCTION
Overview:
A Database is a collection of related data organised in a way that data can be easily accessed,
managed and updated. Any piece of information can be a data, for example name of your school.
Database is actually a place where related piece of information is stored and various operations
can be performed on it.

What is Data?

Data is a collection of a distinct small unit of information. It can be used in a variety of forms like
text, numbers, media, bytes, etc. it can be stored in pieces of paper or electronic memory, etc.

Word ‘Data’ is originated from the word 'datum' that means 'single piece of information.' It is
plural of the word datum.

In computing, Data is information that can be translated into a form for efficient movement and
processing. Data is interchangeable.

1. What is Database Management System?

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.

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
 PostgreSQL
 Amazon SimpleDB (cloud based) etc.

1.2 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, and 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.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 1
Fundamentals of Database Systems Department of ECE

1.3 DBMS allow users the following tasks:

 Data Definition: It is used for creation, modification, and removal of definition that
defines the organization of data in the database.
 Data Updation: It is used for the insertion, modification, and deletion of the actual data
in the database.
 Data Retrieval: It is used to retrieve the data from the database which can be used by
applications for various purposes.
 User Administration: It is used for registering and monitoring users, maintain data
integrity, enforcing data security, dealing with concurrency control, monitoring
performance and recovering information corrupted by unexpected failure.

1.4 Characteristics of DBMS:

 It uses a digital repository established on a server to store and manage the information.
 It can provide a clear and logical view of the process that manipulates data.
 DBMS contains automatic backup and recovery procedures.
 It contains ACID properties which maintain data in a healthy state in case of failure.
 It can reduce the complex relationship between data.
 It is used to support manipulation and processing of data.
 It is used to provide security of data.
 It can view the database from different viewpoints according to the requirements of the
user.

1.5 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

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 2
Fundamentals of Database Systems Department of ECE

1.6 Database Applications – DBMS:

 Telecom: There is a database to keeps track of the information regarding calls made,
network usage, customer details etc. Without the database systems it is hard to maintain
that huge amount of data that keeps updating every millisecond.
 Industry: Where it is a manufacturing unit, warehouse or distribution centre, each one
needs a database to keep the records of ins and outs. For example distribution centre
should keep a track of the product units that supplied into the centre as well as the
products that got delivered out from the distribution centre on each day; this is where
DBMS comes into picture.
 Banking System: For storing customer info, tracking day to day credit and debit
transactions, generating bank statements etc. All this work has been done with the help of
Database management systems.
 Sales: To store customer information, production information and invoice details.
 Airlines: To travel though airlines, we make early reservations; this reservation
information along with flight schedule is stored in database.
 Education sector: Database systems are frequently used in schools and colleges to store
and retrieve the data regarding student details, staff details, course details, exam details,
payroll data, attendance details, fees details etc. There is a hell lot amount of inter-related
data that needs to be stored and retrieved in an efficient manner.
 Online shopping: You must be aware of the online shopping websites such as Amazon,
Flipkart etc. These sites store the product information, your addresses and preferences,
credit details and provide you the relevant list of products based on your query. All this
involves a Database management system.

1.7 Drawbacks of File System:

 Data redundancy: Data redundancy refers to the duplication of data, lets say we are
managing the data of a college where a student is enrolled for two courses, the same
student details in such case will be stored twice, which will take more storage than
needed. Data redundancy often leads to higher storage costs and poor access time.
 Data inconsistency: Data redundancy leads to data inconsistency, let’s take the same
example that we have taken above, a student is enrolled for two courses and we have
student address stored twice, now let’s say student requests to change his address, if the
address is changed at one place and not on all the records then this can lead to data
inconsistency.
 Data Isolation: Because data are scattered in various files, and files may be in different
formats, writing new application programs to retrieve the appropriate data is difficult.
 Dependency on application programs: Changing files would lead to change in application
programs.
 Atomicity issues: Atomicity of a transaction refers to “All or nothing”, which means either
all the operations in a transaction executes or none.
 Data Security: Data should be secured from unauthorised access, for example a student
in a college should not be able to see the payroll details of the teachers, such kind of
security constraints are difficult to apply in file processing systems.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 3
Fundamentals of Database Systems Department of ECE

1.8 Advantage of DBMS over file system

 No redundant data: Redundancy removed by data normalization. No data duplication


saves storage and improves access time.
 Data Consistency and Integrity: As we discussed earlier the root cause of data
inconsistency is data redundancy, since data normalization takes care of the data
redundancy, data inconsistency also been taken care of as part of it
 Data Security: It is easier to apply access constraints in database systems so that only
authorized user is able to access the data. Each user has a different set of access thus data is
secured from the issues such as identity theft, data leaks and misuse of data.
 Privacy: Limited access means privacy of data.
 Easy access to data – Database systems manages data in such a way so that the data is
easily accessible with fast response times.
 Easy recovery: Since database systems keep the backup of data, it is easier to do a full
recovery of data in case of a failure.
 Flexible: Database systems are more flexible than file processing systems.

1.9 Types of Databases:

1.9.1) Centralized Database


It is the type of database that stores data at a centralized database system. It comforts the users
to access the stored data from different locations through several applications. These
applications contain the authentication process to let user’s access data securely. An example of
a Centralized database can be Central Library that carries a central database of each library in a
college/university.
Advantages of Centralized Database
o It has decreased the risk of data management, i.e., manipulation of data will not affect
the core data.
o Data consistency is maintained as it manages data in a central repository.
o It provides better data quality, which enables organizations to establish data standards.
o It is less costly because fewer vendors are required to handle the data sets.
Disadvantages of Centralized Database
o The size of the centralized database is large, which increases the response time for
fetching the data.
o It is not easy to update such an extensive database system.
o If any server failure occurs, entire data will be lost, which could be a huge loss.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 4
Fundamentals of Database Systems Department of ECE

1.9.2) Distributed Database


Unlike a centralized database system, in distributed systems, data is distributed among different
database systems of an organization. These database systems are connected via communication
links. Such links help the end-users to access the data easily. Examples of the Distributed
database are Apache Cassandra, HBase, Ignite, etc.
We can further divide a distributed database system into:
o Homogeneous DDB: Those database systems which execute on the same operating
system and use the same application process and carry the same hardware devices.
o Heterogeneous DDB: Those database systems which execute on different operating
systems under different application procedures, and carries different hardware devices.
Advantages of Distributed Database
o Modular development is possible in a distributed database, i.e., the system can be
expanded by including new computers and connecting them to the distributed system.
o One server failure will not affect the entire data set.

1.9.3) Relational Database


This database is based on the relational data model, which stores data in the form of rows(tuple)
and columns(attributes), and together forms a table(relation). A relational database uses SQL for
storing, manipulating, as well as maintaining the data. E.F. Codd invented the database in 1970.
Each table in the database carries a key that makes the data unique from others. Examples of
Relational databases are MySQL, Microsoft SQL Server, Oracle, etc.
Properties of Relational Database
There are following four commonly known properties of a relational model known as ACID
properties, where:
A means Atomicity: This ensures the data operation will complete either with success or with
failure. It follows the 'all or nothing' strategy. For example, a transaction will either be committed
or will abort.
C means Consistency: If we perform any operation over the data, its value before and after the
operation should be preserved. For example, the account balances before and after the
transaction should be correct, i.e., it should remain conserved.
I mean Isolation: There can be concurrent users for accessing data at the same time from the
database. Thus, isolation between the data should remain isolated. For example, when multiple
transactions occur at the same time, one transaction effects should not be visible to the other
transactions in the database.
D means Durability: It ensures that once it completes the operation and commits the data, data
changes should remain permanent.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 5
Fundamentals of Database Systems Department of ECE

1.9.4) NoSQL Database


Non-SQL/Not Only SQL is a type of database that is used for storing a wide range of data sets. It
is not a relational database as it stores data not only in tabular form but in several different ways.
It came into existence when the demand for building modern applications increased. Thus,
NoSQL presented a wide variety of database technologies in response to the demands. We can
further divide a NoSQL database into the following four types:

Key-value storage: It is the simplest type of database storage where it stores every single item as
a key (or attribute name) holding its value, together.
Document-oriented Database: A type of database used to store data as JSON-like document. It
helps developers in storing data by using the same document-model format as used in the
application code.
Graph Databases: It is used for storing vast amounts of data in a graph-like structure. Most
commonly, social networking websites use the graph database.
Wide-column stores: It is similar to the data represented in relational databases. Here, data is
stored in large columns together, instead of storing in rows.

Advantages of NoSQL Database


o It enables good productivity in the application development as it is not required to store
data in a structured format.
o It is a better option for managing and handling large data sets.
o It provides high scalability.
o Users can quickly access data from the database through key-value.

1.9.5) Cloud Database


A type of database where data is stored in a virtual environment and executes over the cloud
computing platform. It provides users with various cloud computing services (SaaS, PaaS, IaaS,
etc.) for accessing the database. There are numerous cloud platforms, but the best options are:
 Amazon Web Services(AWS)
 Microsoft Azure
 Kamatera
 PhonixNAP
 ScienceSoft
 Google Cloud SQL, etc.

1.9.6) Object-oriented Databases

The type of database that uses the object-based data model approach for storing data in the
database system. The data is represented and stored as objects which are similar to the objects
used in the object-oriented programming language.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 6
Fundamentals of Database Systems Department of ECE

1.9.7) Hierarchical Databases


It is the type of database that stores data in the form of parent-children relationship nodes. Here,
it organizes data in a tree-like structure.

Data get stored in the form of records that are connected via links. Each child record in the tree
will contain only one parent. On the other hand, each parent record can have multiple child
records.

1.9.8) Network Databases

It is the database that typically follows the network data model. Here, the representation of data
is in the form of nodes connected via links between them. Unlike the hierarchical database, it
allows each record to have multiple children and parent nodes to form a generalized graph
structure.
1.10 Structure of Database Management System:

The database system is divided into three components:


 Query Processor,
 Storage Manager, and
 Disk Storage.
These are explained as following below.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 7
Fundamentals of Database Systems Department of ECE

1.10.1. Query Processor:


It interprets the requests (queries) received from end user via an application program into
instructions. It also executes the user request which is received from the DML compiler.

Query Processor contains the following components:

 DML Compiler –
It processes the DML statements into low level instruction (machine language), so that
they can be executed.

 DDL Interpreter –
It processes the DDL statements into a set of table containing Meta data (data about
data).

 Embedded DML Pre-compiler –


It processes DML statements embedded in an application program into procedural calls.

 Query Optimizer – It executes the instruction generated by DML Compiler

1.10.2. Storage Manager –


Storage Manager is a program that provides an interface between the data stored in the
database and the queries received. It is also known as Database Control System. It maintains the
consistency and integrity of the database by applying the constraints and executes
the DCL statements. It is responsible for updating, storing, deleting, and retrieving data in the
database. It contains the following components

 Authorization Manager:
It ensures role-based access control, i.e,. checks whether the particular person is
privileged to perform the requested operation or not.

 Integrity Manager:
It checks the integrity constraints when the database is modified.

 Transaction Manager:
It controls concurrent access by performing the operations in a scheduled way that it
receives the transaction. Thus, it ensures that the database remains in the consistent
state before and after the execution of transaction.

 File Manager:
It manages the file space and the data structure used to represent information in the
database.

 Buffer Manager:
It is responsible for cache memory and the transfer of data between the secondary
storage and main memory.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 8
Fundamentals of Database Systems Department of ECE

1.10.3. Disk Storage: It contains the following components:

 Data Files –
It stores the data.

 Data Dictionary –
It contains the information about the structure of any database object. It is the repository
of information that governs the metadata.

 Indices –
It provides faster retrieval of data item.

1.11 Types of DBMS Architecture:

There are three types of DBMS architecture:

1. Single tier architecture


2. Two tier architecture
3. Three tier architecture

1.11.1 Single –Tier- 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.
For example, let’s say you want to fetch the records of employee from the database and the
database is available on your computer system, so the request to fetch employee details will be
done by your computer and the records will be fetched from the database by your computer as
well. This type of system is generally referred as local database system.

1.11.2. Two – Tier –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 as shown in the above diagram.

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.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 9
Fundamentals of Database Systems Department of ECE

1.11.3. Three – Tier –Architecture:

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.

1.12 Three schema Architecture


 The three schema architecture is also called ANSI/SPARC architecture or three-level
architecture.
 This framework is used to describe the structure of a specific database system.
 The three schema architecture is also used to separate the user applications and physical
database.
 The three schema architecture contains three-levels. It breaks the database down into
three different categories.

The three-schema architecture is as follows:

External Level

In the above diagram:

 It shows the architecture of DBMS.


 Mapping is the process of transforming request response between various database
levels of architecture.
 Mapping is not good for small database, because it takes more time.
 In External / Conceptual mapping, DBMS transforms a request on an external schema
against the conceptual schema.
 In Conceptual / Internal mapping, it is necessary to transform the request from the
conceptual to internal levels.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 10
Fundamentals of Database Systems Department of ECE

1.12.1. Physical Level

 Physical level describes the physical storage structure of data in database.


 It is also known as Internal Level.
 This level is very close to physical storage of data.
 At lowest level, it is stored in the form of bits with the physical addresses on the
secondary storage device.
 At highest level, it can be viewed in the form of files.
 The internal schema defines the various stored data types. It uses a physical data model.

1.12.2. Conceptual Level

 Conceptual level describes the structure of the whole database for a group of users.
 It is also called as the data model.
 Conceptual schema is a representation of the entire content of the database.
 This schema contains all the information to build relevant external records.
 It hides the internal details of physical storage.

1.12.3. External Level

 External level is related to the data which is viewed by individual end users.
 This level includes a no. of user views or external schemas.
 This level is closest to the user.
 External view describes the segment of the database that is required for a particular user
group and hides the rest of the database from that user group.

1.13 Data Models


Data Model is the modelling 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:

1) Relational Data Model: This type of model designs the data in the form of rows and columns
within a table. Thus, a relational model uses tables for representing data and in-between
relationships. Tables are also called relations. This model was initially described by Edgar F. Codd,
in 1969. The relational data model is the widely used model which is primarily used by
commercial data processing applications.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 11
Fundamentals of Database Systems Department of ECE

2) Entity-Relationship Data Model: An ER model is the logical representation of data as objects


and relationships among them. These objects are known as entities, and relationship is an
association among these entities. This model was designed by Peter Chen and published in 1976
papers. It was widely used in database designing. A set of attributes describe the entities. For
example, student_name, student_id describes the 'student' entity. A set of the same type of
entities is known as an 'Entity set', and the set of the same type of relationships is known as
'relationship set'.

3) Object-based Data Model: An extension of the ER model with notions of functions,


encapsulation, and object identity, as well. This model supports a rich type system that includes
structured and collection types. Thus, in 1980s, various database systems following the object-
oriented approach were developed. Here, the objects are nothing but the data carrying its
properties.

4) Semi structured Data Model: This type of data model is different from the other three data
models (explained above). The semi structured data model allows the data specifications at
places where the individual data items of the same type may have different attributes sets. The
Extensible Markup Language, also known as XML, is widely used for representing the semi
structured data. Although XML was initially designed for including the mark up information to
the text document, it gains importance because of its application in the exchange of data.

1.14 File System Vs DBMS

S No File System DBMS


1 File system is software that manages
and organizes the files in a storage DBMS is software for managing the database.
medium within a computer.
2 Redundant data can be present in a
In DBMS there is no redundant data
file system
3 It doesn’t provide backup and It provides backup and recovery of data even if it
recovery of data if it is lost. is lost.
4 There is no efficient query processing
Efficient query processing is there in DBMS.
in file system.
5 There is less data consistency in file There is more data consistency because of the
system. process of normalization.
6 It is less complex as compared to It has more complexity in handling as compared
DBMS. to file system.
7 File systems provide less security in DBMS has more security mechanisms as
comparison to DBMS. compared to file system
8 It has a comparatively higher cost than a file
It is less expensive than DBMS.
system.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 12
Fundamentals of Database Systems Department of ECE

1.15 Components of Database and Functions:

DBMS (Database Management System) acts as an interface between the user and the database.
The user requests the DBMS to perform various operations such as insert, delete, update and
retrieval on the database. The components of DBMS perform these requested operations on the
database and provide necessary data to the users.

The components of DBMS can be divided into two parts: Functions and Services

1.15.1 DDL Compiler:

 Data Description Language compiler processes schema definitions specified in the


DDL.
 It includes metadata information such as the name of the files, data items, storage
details of each file, mapping information and constraints etc.

1.15.2. DML Compiler and Query optimizer:

 The DML commands such as insert, update, delete, retrieve from the application
program are sent to the DML compiler for compilation into object code for
database access.
 The object code is then optimized in the best way to execute a query by the query
optimizer and then send to the data manager.

1.15.3 Data Manager:

 The Data Manager is the central software component of the DBMS also knows as
Database Control System.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 13
Fundamentals of Database Systems Department of ECE

1.15.3.1 The Main Functions Of Data Manager Are:

1. Convert operations in user's Queries coming from the application programs or


combination of DML Compiler and Query optimizer which is known as Query
Processor from user's logical view to physical file system.
2. Controls DBMS information access that is stored on disk.
3. It also controls handling buffers in main memory.
4. It also enforces constraints to maintain consistency and integrity of the data.
5. It also synchronizes the simultaneous operations performed by the concurrent
users.
6. It also controls the backup and recovery operations.

1 Data Dictionary:

 Data Dictionary, which stores metadata about the database, in particular the
schema of the database.
 Names of the tables, names of attributes of each table, length of attributes, and
number of rows in each table.
 Detailed information on physical database design such as storage structure, access
paths, files and record sizes.
 Usage statistics such as frequency of query and transactions.
 Data dictionary is used to actually control the data integrity, database operation
and accuracy. It may be used as a important part of the DBMS

2 Data Files: Which store the database itself


3 Compiled DML:

 The DML complier converts the high level Queries into low level file access
commands known as compiled DML.

4 End Users:

1. The second class of users then is end user, who interacts with system from online
workstation or terminals.
2. Use the interface provided as an integral part of the database system software.
3. User can request, in form of query, to access database either directly by using
particular language, such as SQL, or by using some pre-developed application
interface.
4. Such request are sent to query evaluation engine via DML pre-compiler and DML
compiler
5. The query evaluation engine accepts the query and analyses it.
6. It finds the suitable way to execute the compiled SQL statements of the query.
7. Finally, the compiled SQL statements are executed to perform the specified
operation

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 14
Fundamentals of Database Systems Department of ECE

8. Query Processor Units:


 Interprets DDL statements into a set of tables containing metadata.
 Translates DML statements into low level instructions that the query
evaluation engine understands.
 Converts DML statements embedded in an application program into
procedure calls in the host language.
Executes low level instructions generated by DML compiler.
 DDL Interpreter
 DML Compiler
 Embedded DML Pre-compiler
 Query Evaluation Engine

Storage Manager Units


 Checks the authority of users to access data.
 Checks for the satisfaction of the integrity constraints.
 Preserves atomicity and controls concurrency.
 Manages allocation of space on disk.
Fetches data from disk storage to memory for being used.

1. Authorization Manager
2. Integrity Manager
3. Transaction Manager
4. File manager
5. Buffer Manager

5. Functions of DBMS:

a. DBMS free the programmers from the need to worry about the organization and
location of the data i.e. it shields the users from complex hardware level details.
b. DBMS can organize process and present data elements from the database. This
capability enables decision makers to search and query database contents in order to
extract answers that are not available in regular Reports.
c. Programming is speeded up because programmer can concentrate on logic of the
application.
d. It includes special user friendly query languages which are easy to understand by non
programming users of the system.

6. The service provided by the DBMS includes:-


a) Authorization services like log on to the DBMS start the database stop the
Database etc.
b) Transaction supports like Recovery, Rollback etc,
c) Import and Export of Data.
d) Maintaining data dictionary
e) User's Monitoring

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 15
Fundamentals of Database Systems Department of ECE

1.16 Types of Database Languages:

1.16.1. DDL (Data Definition Language) : DDL or Data Definition Language actually consists of the
SQL commands that can be used to define the database schema. It simply deals with descriptions
of the database schema and is used to create and modify the structure of database objects in the
database.

Examples of DDL commands:

 CREATE – is used to create the database or its objects (like table, index, function, views,
store procedure and triggers).

Syntax: 1

CREATE DATABASE database_ name;

database name: name of the database.

Example 1: CREATE DATABASE my _database;

Syntax: 2

CREATE TABLE table_name


(
column1 data_type(size),
column2 data_type(size),
column3 data_type(size),
....
);

Example 2:
CREATE TABLE Students (ROLL_NO int(3), NAME varchar(20), SUBJECT varchar(20),);

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 16
Fundamentals of Database Systems Department of ECE

 DROP – is used to delete objects from the database.

DROP is used to delete a whole database or just a table. The DROP statement destroys
the objects like an existing database, table, index, or view.
A DROP statement in SQL removes a component from a relational database management
system (RDBMS).

Syntax :

DROP object object_name

Examples:
DROP TABLE table_name;
table_name: Name of the table to be deleted.

DROP DATABASE database_name;


database_name: Name of the database to be deleted.

 ALTER- is used to alter the structure of the database.

ALTER TABLE is used to add, delete/drop or modify columns in the existing table. It is also
used to add and drop various constraints on the existing table.

ADD is used to add columns into the existing table. Sometimes we may require to add
additional information, in that case we do not require to create the whole database
again, ADD comes to our rescue.

Syntax: ALTER TABLE table_name


ADD (Columnname_1 datatype,
Columnname_2 datatype,

Columnname_n datatype);

DROP COLUMN is used to drop column in a table. Deleting the unwanted columns from the
table.
Syntax: ALTER TABLE table_name
DROP COLUMN column_name;

Example :

ROLL_NO NAME
1 Ram
2 Abhi
3 Rahul
4 Tanu

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 17
Fundamentals of Database Systems Department of ECE

QUERY:
 To ADD 2 columns AGE and COURSE to table Student.

ALTER TABLE Student ADD (AGE number (3), COURSE varchar (40));

OUTPUT:
ROLL_NO NAME AGE COURSE
1 Ram
2 Abhi
3 Rahul
4 Tanu

 MODIFY column COURSE in table Student

ALTER TABLE Student MODIFY COURSE varchar (20);


After running the above query maximum size of Course Column is reduced to 20 from 40.
 DROP column COURSE in table Student.

ALTER TABLE Student DROP COLUMN COURSE;

OUTPUT:
ROLL_NO NAME AGE
1 Ram
2 Abhi
3 Rahul
4 Tanu

 TRUNCATE–is used to remove all records from a table, including all spaces allocated for
the records are removed.

TRUNCATE statement is a Data Definition Language (DDL) operation that is used to mark
the extents of a table for deallocation (empty for reuse). The result of this operation
quickly removes all data from a table, typically bypassing a number of integrity enforcing
mechanisms. The TRUNCATE TABLE mytable statement is logically (though not physically)
equivalent to the DELETE FROM mytable statement (without a WHERE clause).

Syntax :

TRUNCATE TABLE table_name;


table_name: Name of the table to be truncated.
DATABASE name - student_data

 Truncate is normally ultra-fast and its ideal for deleting data from a temporary table.
 Truncate preserves the structure of the table for future use, unlike drop table where the
table is deleted with its full structure.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 18
Fundamentals of Database Systems Department of ECE

 Table or Database deletion using DROP statement cannot be rolled back, so it must be
used wisely.

 To delete the whole database

DROP DATABASE student_data;

After running the above query whole database will be deleted.

 To truncate Student_details table from student_data database.

TRUNCATE TABLE Student_details;

After running the above query Student_details table will be truncated, i.e, the data will be
deleted but the structure will remain in the memory for further operations.

 COMMENT –is used to add comments to the data dictionary.

 RENAME –is used to rename an object existing in the database.


Sometimes we may want to rename our table to give it a more relevant name. For this
purpose we can use ALTER TABLE to rename the name of table.

Syntax: ALTER TABLE table_name


RENAME TO new_table_name;

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 19
Fundamentals of Database Systems Department of ECE

Columns can be also be given new name with the use of ALTER TABLE.

Syntax: ALTER TABLE table_name


RENAME COLUMN old_name TO new_name;

Syntax: ALTER TABLE table_name


CHANGE COLUMN old_name TO new_name;

SAMPLE TABLE: Student

ROLL_NO NAME AGE


1 Ram 20
2 Abhi 21
3 Rahul 22
4 Tanu 19

QUERY:

 Change the name of column NAME to FIRST_NAME in table Student.


ALTER TABLE Student RENAME COLUMN NAME TO FIRST_NAME;
OUTPUT:

ROLL_NO FIRST_NAME AGE


1 Ram 20
2 Abhi 21
3 Rahul 22
4 Tanu 19

Change the name of the table Student to Student_Details


ALTER TABLE Student RENAME TO Student_Details;
OUTPUT:
Student_Details

ROLL_NO FIRST_NAME AGE


1 Ram 20
2 Abhi 21
3 Rahul 22
4 Tanu 19

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 20
Fundamentals of Database Systems Department of ECE

1.16.2.DQL (Data Query Language) :

DQL statements are used for performing queries on the data within schema objects. The purpose
of the DQL Command is to get some schema relation based on the query passed to it.

Example of DQL:

 SELECT – is used to retrieve data from the database.

Sample Table:

Syntax : SELECT column1,column2 FROM table_name

column1 , column2: names of the fields of the table


table_name : from where we want to fetch

This query will return all the rows in the table with fields’ column1, column2.

To fetch the entire table or all the fields in the table:

SELECT * FROM table_name;

Query to fetch the fields ROLL_NO, NAME, AGE from the table Student:

SELECT ROLL_NO, NAME, AGE FROM Student;

Output:

ROLL_NO NAME Age


1 Ram 18
2 RAMESH 18
3 SUJIT 20
4 SURESH 18
To fetch all the fields from the table Student:

SELECT * FROM Student;

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 21
Fundamentals of Database Systems Department of ECE

Output:

ROLL_NO NAME ADDRESS PHONE Age


1 Ram Delhi XXXXXXXXXX 18
2 RAMESH GURGAON XXXXXXXXXX 18
3 SUJIT ROHTAK XXXXXXXXXX 20
4 SURESH Delhi XXXXXXXXXX 18

1.16.3 DML (Data Manipulation Language): The SQL commands that deals with the manipulation
of data present in the database belong to DML or Data Manipulation Language and this includes
most of the SQL statements.

Examples of DML:

 INSERT – is used to insert data into a table.

The INSERT INTO statement of SQL is used to insert a new row in a table. There are two
ways of using INSERT INTO statement for inserting rows:

1. Only values: First method is to specify only the value of data to be inserted without the
column names.

INSERT INTO table_name VALUES (value1, value2, value3,…);


table_name: name of the table.
value1, value2,.. : value of first column, second column,… for the new record

2. Column names and values both: In the second method we will specify both the columns
which we want to fill and their corresponding values as shown below:

INSERT INTO table_name (column1, column2, column3,..) VALUES (value1, value2,


value3,);
table_name: name of the table.
column1: name of first column, second column …
value1, value2, value3: value of first column, second column,… for the new record

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 22
Fundamentals of Database Systems Department of ECE

Method 1 (Inserting only values) :


INSERT INTO Student VALUES (‘5′,’HARSH’,’WEST BENGAL’,’9912204100’,’19’);

Output:
The table Student will now look like:
ROLL_NO NAME ADDRESS PHONE Age
1 Ram Delhi XXXXXXXXXX 18
2 RAMESH GURGAON XXXXXXXXXX 18
3 SUJIT ROHTAK XXXXXXXXXX 20
4 SURESH Delhi XXXXXXXXXX 18
3 SUJIT ROHTAK XXXXXXXXXX 20
2 RAMESH GURGAON XXXXXXXXXX 18
5 HARSH WEST BENGAL XXXXXXXXXX 19

Method 2 (Inserting values in only specified columns):

INSERT INTO Student (ROLL_NO, NAME, Age) VALUES (‘5′,’PRATIK’,’19’);

Output:
The table Student will now look like:

ROLL_NO NAME ADDRESS PHONE Age


1 Ram Delhi XXXXXXXXXX 18
2 RAMESH GURGAON XXXXXXXXXX 18
3 SUJIT ROHTAK XXXXXXXXXX 20
4 SURESH Delhi XXXXXXXXXX 18
3 SUJIT ROHTAK XXXXXXXXXX 20
2 RAMESH GURGAON XXXXXXXXXX 18
5 PRATIK null null 19

Notice that the columns for which the values are not provided are filled by null. Which is the
default values for those columns.

 Inserting all columns of a table: We can copy all the data of a table and insert into in a
different table.

INSERT INTO first_table SELECT * FROM second_table;

first_table: name of first table.


second_table: name of second table.

We have used the SELECT statement to copy the data from one table and INSERT INTO
statement to insert in a different table.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 23
Fundamentals of Database Systems Department of ECE

 Inserting specific columns of a table: We can copy only those columns of a table which
we want to insert into in a different table.
Syntax:

INSERT INTO first_table(names_of_columns1) SELECT names_of_columns2 FROM


second_table;

first_table: name of first table.


second_table: name of second table.
names of columns1: name of columns separated by comma(,) for table 1.
names of columns2: name of columns separated by comma(,) for table 2.

We have used the SELECT statement to copy the data of the selected columns only from
the second table and INSERT INTO statement to insert in first table.

 Copying specific rows from a table: We can copy specific rows from a table to insert into
another table by using WHERE clause with the SELECT statement. We have to provide
appropriate condition in the WHERE clause to select specific rows.

INSERT INTO table1 SELECT * FROM table2 WHERE condition;


first_table: name of first table.
second_table: name of second table.
condition: condition to select specific rows.

Table2: Lateral Student

ROLL_NO NAME ADDRESS PHONE Age


7 SOUVIK DUMDUM XXXXXXXXXX 18
8 NIRAJ NOIDA XXXXXXXXXX 19
9 SOMESH ROHTAK XXXXXXXXXX 20

Queries: Method 1(Inserting all rows and columns):

INSERT INTO Student SELECT * FROM LateralStudent;

Output:
This query will insert all the data of the table LateralStudent in the table Student.
The table Student will now look like,

ROLL_NO NAME ADDRESS PHONE Age


1 Ram Delhi XXXXXXXXXX 18
2 RAMESH GURGAON XXXXXXXXXX 18
3 SUJIT ROHTAK XXXXXXXXXX 20
4 SURESH Delhi XXXXXXXXXX 18

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 24
Fundamentals of Database Systems Department of ECE

ROLL_NO NAME ADDRESS PHONE Age


3 SUJIT ROHTAK XXXXXXXXXX 20
2 RAMESH GURGAON XXXXXXXXXX 18
7 SOUVIK DUMDUM XXXXXXXXXX 18
8 NIRAJ NOIDA XXXXXXXXXX 19
9 SOMESH ROHTAK XXXXXXXXXX 20

 Method 2(Inserting specific columns):

INSERT INTO Student(ROLL_NO,NAME,Age) SELECT ROLL_NO, NAME, Age FROM


LateralStudent;

Output:
This query will insert the data in the columns ROLL_NO, NAME and Age of the table
LateralStudent in the table Student and the remaining columns in the Student table will
be filled by null which is the default value of the remaining columns. The table Student
will now look like,

ROLL_NO NAME ADDRESS PHONE Age


1 Ram Delhi XXXXXXXXXX 18
2 RAMESH GURGAON XXXXXXXXXX 18
3 SUJIT ROHTAK XXXXXXXXXX 20
4 SURESH Delhi XXXXXXXXXX 18
3 SUJIT ROHTAK XXXXXXXXXX 20
2 RAMESH GURGAON XXXXXXXXXX 18
7 SOUVIK null null 18
8 NIRAJ null null 19
9 SOMESH null null 20

 Select specific rows to insert:

INSERT INTO Student SELECT * FROM Lateral Student WHERE Age = 18;

Output:
This query will select only the first row from table Lateral Student to insert into the table
Student. The table Student will now look like,

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 25
Fundamentals of Database Systems Department of ECE

ROLL_NO NAME ADDRESS PHONE Age


1 Ram Delhi XXXXXXXXXX 18
2 RAMESH GURGAON XXXXXXXXXX 18
3 SUJIT ROHTAK XXXXXXXXXX 20
4 SURESH Delhi XXXXXXXXXX 18
3 SUJIT ROHTAK XXXXXXXXXX 20
2 RAMESH GURGAON XXXXXXXXXX 18
7 SOUVIK DUMDUM XXXXXXXXXX 18

To insert multiple rows in a table using Single SQL Statement


INSERT INTO table_name(Column1,Column2,Column3,.......)
VALUES (Value1, Value2,Value3,.....), (Value1, Value2,Value3,.....),
(Value1, Value2,Value3,.....) , ;

table_name: name of the table


Column1: name of first column, second column …
Value1, Value2, Value3: value of first column, second column,… for each new row inserted

You need to provide multiple lists of values where each list is separated by ", ". Every list of value
corresponds to values to be inserted in each new row of the table.

Values in the next list tell values to be inserted in the next Row of the table.
Example:

The following SQL statement inserts multiple rows in Student Table.

Input :
INSERT INTO STUDENT (ID, NAME, AGE, GRADE, CITY) VALUES
(1,"AMIT KUMAR",15,10,"DELHI"),
(2,"GAURI RAO",18,12,"BANGALORE"),
(3,"MANAV BHATT",17,11,"NEW DELHI")
(4,"RIYA KAPOOR",10,5,"UDAIPUR");

Output: STUDENT TABLE


This query will insert all values in each successive row in the STUDENT TABLE. Thus STUDENT
Table will look like this:

ID NAME AGE GRADE CITY


1 AMIT KUMAR 15 10 DELHI
2 GAURI RAO 16 12 BANGALORE
3 MANAV BHATT 17 11 NEW DELHI
4 RIYA KAPOOR 10 5 UDAIPUR

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 26
Fundamentals of Database Systems Department of ECE

 UPDATE – is used to update existing data within a table.

The UPDATE statement in SQL is used to update the data of an existing table in database.
We can update single columns as well as multiple columns using UPDATE statement as
per our requirement.

Syntax : UPDATE table_name SET column1 = value1, column2 = value2,...

WHERE condition;

table_name: name of the table


column1: name of first, second, third column....
value1: new value for first, second, third column....
condition: condition to select the rows for which the

Values of columns needs to be updated.

Example Queries : Updating single column: Update the column NAME and set the value to
‘PRATIK’ in all the rows where Age is 20.

 UPDATE Student SET NAME = 'PRATIK' WHERE Age = 20;

Output:
This query will update two rows(third row and fifth row) and the table Student will now
look like,

ROLL_NO NAME ADDRESS PHONE Age


1 Ram Delhi XXXXXXXXXX 18
2 RAMESH GURGAON XXXXXXXXXX 18
3 PRATIK ROHTAK XXXXXXXXXX 20
4 SURESH Delhi XXXXXXXXXX 18
3 PRATIK ROHTAK XXXXXXXXXX 20
2 RAMESH GURGAON XXXXXXXXXX 18

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 27
Fundamentals of Database Systems Department of ECE

Updating multiple columns: Update the columns NAME to ‘PRATIK’ and ADDRESS to
‘SIKKIM’ where ROLL_NO is 1.

UPDATE Student SET NAME = 'PRATIK', ADDRESS = 'SIKKIM' WHERE ROLL_NO = 1

Output:
The above query will update two columns in the first row and the table Student will now
look like,

ROLL_NO NAME ADDRESS PHONE Age


1 PRATIK SIKKIM XXXXXXXXXX 18
2 RAMESH GURGAON XXXXXXXXXX 18
3 PRATIK ROHTAK XXXXXXXXXX 20
4 SURESH Delhi XXXXXXXXXX 18
3 PRATIK ROHTAK XXXXXXXXXX 20
2 RAMESH GURGAON XXXXXXXXXX 18

Note: For updating multiple columns we have used comma (,) to separate the names and
values of two columns.

Omitting WHERE clause: If we omit the WHERE clause from the update query then all of
the rows will get updated.

UPDATE Student SET NAME = 'PRATIK';

Output:
The table Student will now look like,

ROLL_NO NAME ADDRESS PHONE Age


1 PRATIK Delhi XXXXXXXXXX 18
2 PRATIK GURGAON XXXXXXXXXX 18
3 PRATIK ROHTAK XXXXXXXXXX 20
4 PRATIK Delhi XXXXXXXXXX 18
3 PRATIK ROHTAK XXXXXXXXXX 20
2 PRATIK GURGAON XXXXXXXXXX 18

 DELETE – is used to delete records from a database table.

The DELETE Statement in SQL is used to delete existing records from a table. We can
delete a single record or multiple records depending on the condition we specify in the
WHERE clause.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 28
Fundamentals of Database Systems Department of ECE

Syntax:
DELETE FROM table_name WHERE some_condition;

table_name: name of the table


some_condition: condition to choose particular record.

Note: We can delete single as well as multiple records depending on the condition we
provide in WHERE clause. If we omit the WHERE clause then all of the records will be
deleted and the table will be empty.

Sample Table:

Example Queries:

 Deleting single record: Delete the rows where NAME = ‘Ram’. This will delete only the
first row.
 DELETE FROM Student WHERE NAME = 'Ram';

Output:
The above query will delete only the first row and the table Student will now look like,

ROLL_NO NAME ADDRESS PHONE Age


2 RAMESH GURGAON XXXXXXXXXX 18
3 SUJIT ROHTAK XXXXXXXXXX 20
4 SURESH Delhi XXXXXXXXXX 18
3 SUJIT ROHTAK XXXXXXXXXX 20
2 RAMESH GURGAON XXXXXXXXXX 18

 Deleting multiple records: Delete the rows from the table Student where Age is 20. This
will delete 2 rows (third row and fifth row).

DELETE FROM Student WHERE Age = 20;

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 29
Fundamentals of Database Systems Department of ECE

Output:
The above query will delete two rows(third row and fifth row) and the table Student will
now look like,

ROLL_NO NAME ADDRESS PHONE Age


1 Ram Delhi XXXXXXXXXX 18
2 RAMESH GURGAON XXXXXXXXXX 18
4 SURESH Delhi XXXXXXXXXX 18
2 RAMESH GURGAON XXXXXXXXXX 18

Delete all of the records: There are two queries to do this as shown below,

query1: "DELETE FROM Student";

query2: "DELETE * FROM Student";

Output:

All of the records in the table will be deleted, there are no records left to display. The
table Student will become empty!

1.16.4. DCL (Data Control Language): DCL includes commands such as GRANT and REVOKE which
mainly deal with the rights, permissions and other controls of the database system.

Examples of DCL commands:

 GRANT-gives users’ access privileges to the database.


 REVOKE-withdraw user’s access privileges given by using the GRANT command.

TCL (transaction Control Language): TCL commands deal with the transaction within the
database.

Examples of TCL commands:

 COMMIT– commits a Transaction.


 ROLLBACK– rollbacks a transaction in case of any error occurs.
 SAVEPOINT–sets a save point within a transaction.
 SET TRANSACTION–specify characteristics for the transaction.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 30
Fundamentals of Database Systems Department of ECE

1.17 History of Database Management System:

 1960 – Charles Bachman designed first DBMS system


 1970 – Codd introduced IBM’S Information Management System (IMS)
 1976- Peter Chen coined and defined the Entity-relationship model also known as the ER
model
 1980 – Relational Model becomes a widely accepted database component
 1985- Object-oriented DBMS develops.
 1990s- Incorporation of object-orientation in relational DBMS.
 1991- Microsoft ships MS access, a personal DBMS and that displaces all other personal
DBMS products.
 1995: First Internet database applications
 1997: XML applied to database processing. Many vendors begin to integrate XML into
DBMS products.

1.18 Distributed Database System:

A distributed database is basically a database that is not limited to one system; it is spread over
different sites, i.e, on multiple computers or over a network of computers. A distributed
database system is located on various sites that don’t share physical components. This may be
required when a particular database needs to be accessed by various users globally. It needs to
be managed such that for the users it looks like one single database.

Types:
1. Homogeneous Database:
In a homogeneous database, all different sites store database identically. The operating system,
database management system and the data structures used – all are same at all sites. Hence,
they’re easy to manage.

2.HeterogeneousDatabase:
In a heterogeneous distributed database, different sites can use different schema and software
that can lead to problems in query processing and transactions. Also, a particular site might be
completely unaware of the other sites. Different computers may use a different operating
system, different database application. They may even use different data models for the
database. Hence, translations are required for different sites to communicate.

Distributed Data Storage:


There are 2 ways in which data can be stored on different sites. These are:

1.Replication :
In this approach, the entire relation is stored redundantly at 2 or more sites. If the entire
database is available at all sites, it is a fully redundant database. Hence, in replication, systems
maintain copies of data.

This is advantageous as it increases the availability of data at different sites. Also, now query
requests can be processed in parallel.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 31
Fundamentals of Database Systems Department of ECE

However, it has certain disadvantages as well. Data needs to be constantly updated. Any change
made at one site needs to be recorded at every site that relation is stored or else it may lead to
inconsistency. This is a lot of overhead. Also, concurrency control becomes way more complex as
concurrent access now needs to be checked over a number of sites.

2. Fragmentation:
In this approach, the relations are fragmented (i.e., they’re divided into smaller parts) and each
of the fragments is stored in different sites where they’re required. It must be made sure that
the fragments are such that they can be used to reconstruct the original relation (i.e, there isn’t
any loss of data). Fragmentation is advantageous as it doesn’t create copies of data, consistency
is not a problem.

Fragmentation of relations can be done in two ways:

 Horizontal fragmentation – Splitting by rows –


The relation is fragmented into groups of tuples so that each tuple is assigned to
at least one fragment.

 Vertical fragmentation – Splitting by columns –


The schema of the relation is divided into smaller schemas. Each fragment must
contain a common candidate key so as to ensure lossless join.

1.19 What is RDBMS

 RDBMS stands for Relational Database Management Systems..


 All modern database management systems like SQL, MS SQL Server, IBM DB2, ORACLE,
My-SQL and Microsoft Access are based on RDBMS.
 It is called Relational Data Base Management System (RDBMS) because it is based on
relational model introduced by E.F. Codd.

What is a Relational Database (RDBMS)?

A relational database is a type of database that stores and provides access to data points that are
related to one another. Relational databases are based on the relational model, an intuitive,
straightforward way of representing data in tables. In a relational database, each row in the table
is a record with a unique ID called the key. The columns of the table hold attributes of the data,
and each record usually has a value for each attribute, making it easy to establish the
relationships among data points.
How relational databases are structured
The relational model means that the logical data structures—the data tables, views, and
indexes—are separate from the physical storage structures. This separation means that database
administrators can manage physical data storage without affecting access to that data as a logical
structure. For example, renaming a database file does not rename the tables stored within it.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 32
Fundamentals of Database Systems Department of ECE

The distinction between logical and physical also applies to database operations, which are
clearly defined actions that enable applications to manipulate the data and structures of the
database. Logical operations allow an application to specify the content it needs, and physical
operations determine how that data should be accessed and then carries out the task.

To ensure that data is always accurate and accessible, relational databases follow certain
integrity rules. For example, an integrity rule can specify that duplicate rows are not allowed in a
table in order to eliminate the potential for erroneous information entering the database.

What is table
The RDBMS database uses tables to store data. A table is a collection of related data entries and
contains rows and columns to store data.
A table is the simplest example of data storage in RDBMS.
Let's see the example of student table.

ID Name Age Course


1 Anusha 24 B.Tech
2 Madhu 25 C.A
3 Samskruthi 24 BCA
4 Ashwini 25 M.Tech
5 Sragavi 24 BSc

What is field
Field is a smaller entity of the table which contains specific information about every record in the
table. In the above example, the field in the student table consist of id, name, age, course.

What is row or record?


A row of a table is also called record. It contains the specific information of each individual entry
in the table. It is a horizontal entity in the table. For example: The above table contains 5 records.

Let's see one record/row in the table.

ID Name Age Course


1 Anusha 24 B.Tech

What is column?
A column is a vertical entity in the table which contains all information associated with a specific
field in a table. For example: "name" is a column in the above table which contains all
information about student's name.

Name
Anusha
Madhu
Samskruthi
Ashwini
Sragavi

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 33
Fundamentals of Database Systems Department of ECE

NULL Values
The NULL value of the table specifies that the field has been left blank during record creation. It
is totally different from the value filled with zero or a field that contains space.

Data Integrity

There are the following categories of data integrity exist with each RDBMS:

Entity integrity: It specifies that there should be no duplicate rows in a table.

Domain integrity: It enforces valid entries for a given column by restricting the type, the format,
or the range of values.

Referential integrity: It specifies that rows cannot be deleted, which are used by other records.

DBMS Vs RDBMS

DBMS RDBMS
RDBMS applications store data in a tabular
DBMS applications store data as file.
form.
In RDBMS, the tables have an identifier called
In DBMS, data is generally stored in either a
primary key and the data values are stored in
hierarchical form or a navigational form.
the form of tables.
Normalization is not present in DBMS. Normalization is present in RDBMS.
RDBMS defines the integrity constraint for the
DBMS does not apply any security with
purpose of ACID (Atomocity, Consistency,
regards to data manipulation.
Isolation and Durability) property.
in RDBMS, data values are stored in the form of
DBMS uses file system to store data, so there tables, so a relationship between these data
will be no relation between the tables. values will be stored in the form of a table as
well.
RDBMS system supports a tabular structure of
DBMS has to provide some uniform methods
the data and a relationship between them to
to access the stored information.
access the stored information.
DBMS does not support distributed database. RDBMS supports distributed database.
DBMS is meant to be for small organization RDBMS is designed to handle large amount of
and deal with small data. it supports single data. it supports multiple users.
user.
Examples of DBMS are file systems xml etc.Example of RDBMS are mysql

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 34
Fundamentals of Database Systems Department of ECE

UNIT –II
DATABASE DESIGN ER MODEL

2 .1 What is ER Diagram?
ER Diagram stands for Entity Relationship Diagram,
also known as ERD is a diagram that displays the
relationship of entity sets stored in a database.

In other words, ER diagrams help to explain the logical


structure of databases. ER diagrams are created based on
three basic concepts: entities, attributes and relationships.

ER Diagrams contain different symbols that use


rectangles to represent entities, ovals to define attributes
and diamond shapes to represent relationships.

At first look, an ER diagram looks very similar to the


flowchart. However, ER Diagram includes many
specialized symbols, and its meanings make this model
unique. The purpose of ER Diagram is to represent the
entity framework infrastructure.

2.2 Why we use ER Diagrams?

Here, are prime reasons for using the ER Diagram

 Helps you to define terms related to entity relationship modelling


 Provide a preview of how all your tables should connect, what fields are going to be on
each table
 Helps to describe entities, attributes, relationships
 ER diagrams are translatable into relational tables which allows you to build databases
quickly
 ER diagrams can be used by database designers as a blueprint for implementing data in
specific software applications
 The database designer gains a better understanding of the information to be contained in
the database with the help of ERP diagram
 ERD Diagram allows you to communicate with the logical structure of the database to
users

2.3 Following are the main components and its symbols in ER Diagrams:

 Rectangles: This Entity Relationship Diagram symbol represents entity types


 Ellipses : Symbol represent attributes
 Diamonds: This symbol represents relationship types
 Lines: It links attributes to entity types and entity types with other relationship types
 Primary key: attributes are underlined
 Double Ellipses: Represent multi-valued attributes

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 35
Fundamentals of Database Systems Department of ECE

As shown in the above diagram, an ER diagram has three main components:


1. Entity
2. Attribute
3. Relationship

2.3.1. Entity
An entity is an object or component of data. An entity is represented as rectangle in an ER
diagram.
For example: In the following ER diagram we have two entities Student and College and these
two entities have many to one relationship as many students study in a single college. We will
read more about relationships later, for now focus on entities.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 36
Fundamentals of Database Systems Department of ECE

1.1 Weak Entity


An entity that cannot be uniquely identified by its own attributes and relies on the relationship
with other entity is called weak entity. The weak entity is represented by a double rectangle. For
example – a bank account cannot be uniquely identified without knowing the bank to which the
account belongs, so bank account is a weak entity.

2.3.2. Attribute
An attribute describes the property of an entity. An attribute is represented as Oval in an ER
diagram. There are four types of attributes:

2.3.2.1. Key attribute


2.3.2.2 Composite attribute
2.3.2.3. Multivalued attribute
2.3.2.4. Derived attribute

1. Key Attribute:
A key attribute can uniquely identify an entity
from an entity set. For example, student roll
number can uniquely identify a student from
a set of students. Key attribute is represented
by oval same as other attributes however the
text of key attribute is underlined.

2. Composite Attribute:

An attribute that is a combination of other


attributes is known as composite attribute. For
example, In student entity, the student address is
a composite attribute as an address is composed
of other attributes such as pin code, state,
country.

3. Multivalued attribute:
An attribute that can hold multiple values is known as Multivalued attribute. It is represented
with double ovals in an ER Diagram. For example – A person can have more than one phone
numbers so the phone number attribute is Multivalued.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 37
Fundamentals of Database Systems Department of ECE

4. Derived attribute:
A derived attribute is one whose value is dynamic and derived from another attribute. It is
represented by dashed oval in an ER Diagram. For example – Person age is a derived attribute as
it changes over time and can be derived from another attribute (Date of birth).

2.3.3. Relationship
A relationship is represented by diamond shape in ER diagram; it shows the relationship among
entities. There are four types of relationships:
1. One to One
2. One to Many
3. Many to One
4. Many too Many

1. One to One Relationship


When a single instance of an entity is associated with a single instance of another entity then it is called
one to one relationship. For example, a person has only one passport and a passport is given to one
person.

2. One too Many Relationship

When a single instance of an entity is associated with more than one instances of another entity
then it is called one to many relationship. For example – a customer can place many orders but a
order cannot be placed by many customers.

3.Many to One Relationship

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 38
Fundamentals of Database Systems Department of ECE

When more than one instances of an entity is associated with a single instance of another entity then
it is called many to one relationship. For example – many students can study in a single college but a
student cannot study in many colleges at the same time.

4. Many to Many Relationship

When more than one instances of an entity is associated with more than one instances of another
entity then it is called many to many relationship. For example, a can be assigned to many projects
and a project can be assigned to many students.

2.4 Database Objects in DBMS

Any defined object in the database which can be used to reference or store data is known as a
database object. Database objects can be made using the create command. These database
objects are used for holding and manipulating the data in the database.

The examples of database objects include:

1. View: Subsets of data from more than one table are logically represented.
2. Table: Composed of rows and columns, the table is the primary form of data representation.
3. Sequence: Sequence generates the primary key values.
4. Synonym: It is an alternative name for a specific object.
5. Index: It improves the performance of some particular queries.

2.5 Different Database Objects:

1. Table : A table is a database object used as a unit of storage.

Syntax: CREATE TABLE [ schema ] table (Column datatype [default expr] ;

Example: CREATE TABLE dept (deptno Number (2) , dname VARCHAR2(14) , loc VARCHAR2 (14) );

Output: Describe Dept ;


Name Null Type
Deptno Number (2)
Dname Varchar(14)
Loc Varchar(14)

2.View :

This object is used in the database to create a type of view of the database. It is a logical view
based on one or more tables or even another view. A view does not contain any data of its own
but is used to view data in other tables. The view is based on a table, and that table is known as
the base table. The data dictionary stores the view as a SELECT statement.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 39
Fundamentals of Database Systems Department of ECE

Syntax:

CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view


[(alias[, alias]...)] AS subquery
[WITH CHECK OPTION [CONSTRAINT constraint]]
[WITH READ ONLY [CONSTRAINT constraint]];

Example:

CREATE VIEW salvu50


AS SELECT employee_id ID_NUMBER, last_name NAME, salary*12 ANN_SALARY FROM
employees WHERE department_id = 50;

Output: Select * from salvu50

ID _NUMBER NAME ANN _SALARY


124 MANISH 69600
125 SAMSKRUTHI 50000
142 RITIKA 65522
127 ASHWINI 75000

3. Sequence:
This object in the database is used to create a sequence in the database. It is a user created
database object which can be shared by more than two users to create a unique integer in the
database. The most often use of sequence is to create a primary value in the database. This
primary value is unique for each row. Once the sequence is generated, it is decremented or
incremented using an Oracle routine.

Syntax: CREATE SEQUENCE sequence


[INCREMENT BY n]
[START WITH n]
[{MAXVALUE n | NOMAXVALUE}]
[{MINVALUE n | NOMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n | NOCACHE}];
Example: CREATE SEQUENCE dept_deptid_seq
INCREMENT BY 10
START WITH 120
MAXVALUE 9999
NOCACHE
NOCYCLE;

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 40
Fundamentals of Database Systems Department of ECE

4. Index – This database object is used to create a indexes in database. An Oracle server index
is a schema object that can speed up the retrieval of rows by using a pointer. Indexes can be
created explicitly or automatically. If you do not have an index on the column, then a full table
scan occurs.

An index provides direct and fast access to rows in a table. Its purpose is to reduce the
necessity of disk I/O by using an indexed path to locate data quickly. The index is used and
maintained automatically by the Oracle server. Once an index is created, no direct activity is
required by the user. Indexes are logically and physically independent of the table they index.
This means that they can be created or dropped at any time and have no effect on the base
tables or other indexes.
Syntax: CREATE INDEX index
ON table (column [, column]...);
Example: CREATE INDEX emp_last_name_idx
ON employees(last_name);
5.Synonym – This database object is used to create a indexes in database.It simplify access to
objects by creating a synonym(another name for an object). With synonyms, you can Ease
referring to a table owned by another user and shorten lengthy object names.To refer to a
table owned by another user, you need to prefix the table name with the name of the user
who created it followed by a period. Creating a synonym eliminates the need to qualify the
object name with the schema and provides you with an alternative name for a table, view,
sequence, procedure, or other objects. This method can be especially useful with lengthy
object names, such as views.

Syntax : CREATE [PUBLIC] SYNONYM synonym FOR object;

Example: CREATE SYNONYM d_sum FOR dept_sum_vu;

2.6 Attributes in DBMS:


An attribute is a property or characteristic of an entity. An entity may contain any number of
attributes. One of the attributes is considered as the primary key. In an Entity-Relation model,
attributes are represented in an elliptical shape.
Example: Student has attributes like name, age, roll number and many more. To uniquely
identify the student, we use the primary key as roll number as it is not repeated. Attributes can
also be subdivided into another set of attributes.

There are five such types of attributes: Simple, Composite, Single-valued, Multi-valued, and
Derived attribute.
These are explained as following below.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 41
Fundamentals of Database Systems Department of ECE

1. Simple attribute: An attribute which cannot be further subdivided into components is a


simple attribute.
Example: The roll number of a student, the id number of an employee .

2. Composite Attribute
An attribute which can be splitted into components is a composite attribute.
Example: The address can be further splitted into house number, street number, city, state,
country and pincode, the name can also be splitted into first name middle name and last name.

3.Single –valued Attribute :


The attribute which takes up only a single value for each entity instance is single-valued
attribute.
Example: The age of a student.

4.Multi-Valued Attribute :
The attribute which takes up more than a single value for each entity instance is multi-valued
attribute.
Example: Phone number of a student: Landline and mobile.

5.Dervied Attribute :
An attribute that can be derived from other attributes is derived attribute.
Example: Total and average marks of a student .

2.7 Entity-Set and Keys


Key is an attribute or collection of attributes that uniquely identifies an entity among entity set.
For example, the roll_number of a student makes him/her identifiable among students.
 Super Key − A set of attributes (one or more) that collectively identifies an entity in an
entity set.
 Candidate Key − A minimal super key is called a candidate key. An entity set may have
more than one candidate key.
 Primary Key − A primary key is one of the candidate keys chosen by the database
designer to uniquely identify the entity set.
2.8 E R Model
 Let us now learn how the ER Model is represented by means of an ER diagram. Any
object, for example, entities, attributes of an entity, relationship sets, and attributes of
relationship sets, can be represented with the help of an ER diagram.
 Relationships are represented by diamond-shaped box. Name of the relationship is
written inside the diamond-box. All the entities (rectangles) participating in a
relationship, are connected to it by a line.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 42
Fundamentals of Database Systems Department of ECE

2.8.1 Entity

Entities are represented by means of rectangles. Rectangles are named with the entity set they
represent.

2.8.2 Attributes

Attributes are the properties of entities. Attributes are represented by means of ellipses. Every
ellipse represents one attribute and is directly connected to its entity (rectangle).

2.8.3 Composite: they are further divided in a tree like structure. Every node is then connected
to its attribute. That is, composite attributes are represented by ellipses that are connected with
an ellipse.

2.8.4 Multivalued attributes are depicted by double ellipse.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 43
Fundamentals of Database Systems Department of ECE

2.8.5 Derived attributes are depicted by dashed ellipse.

2.9 Relationship
The association among entities is called a relationship. For example, an employee works_at a
department, a student enrolls in a course. Here, Works_at and Enrolls are called relationships.
Relationship Set
A set of relationships of similar type is called a relationship set. Like entities, a relationship too
can have attributes. These attributes are called descriptive attributes.
Degree of Relationship
The number of participating entities in a relationship defines the degree of the relationship.
 Binary = degree 2
 Ternary = degree 3
 n-ary = degree
2.10 Mapping Cardinalities
Cardinality defines the number of entities in one entity set, which can be associated with the
number of entities of other set via relationship set.
 One-to-one − One entity from entity set A can be associated with at most one entity of
entity set B and vice versa.

 One-to-many − One entity from entity set A can be associated with more than one
entities of entity set B however an entity from entity set B, can be associated with at
most one entity.

 Many-to-one − More than one entities from entity set A can be associated with at most
one entity of entity set B, however an entity from entity set B can be associated with
more than one entity from entity set A.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 44
Fundamentals of Database Systems Department of ECE

 Many-to-many − One entity from A can be associated with more than one entity from B
and vice versa.

2.11 Binary Relationship and Cardinality


A relationship where two entities are participating is called a binary relationship. Cardinality is
the number of instance of an entity from a relation that can be associated with the relation.
 One-to-one − When only one instance of an entity is associated with the relationship, it is
marked as '1:1'. The following image reflects that only one instance of each entity should
be associated with the relationship. It depicts one-to-one relationship.

 One-to-many − When more than one instance of an entity is associated with a


relationship, it is marked as '1:N'. The following image reflects that only one instance of
entity on the left and more than one instance of an entity on the right can be associated
with the relationship. It depicts one-to-many relationship.

 Many-to-one − When more than one instance of entity is associated with the
relationship, it is marked as 'N:1'. The following image reflects that more than one
instance of an entity on the left and only one instance of an entity on the right can be
associated with the relationship. It depicts many-to-one relationship.

 Many-to-many − The following image reflects that more than one instance of an entity
on the left and more than one instance of an entity on the right can be associated with
the relationship. It depicts many-to-many relationship.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 45
Fundamentals of Database Systems Department of ECE

Participation Constraints
 Total Participation − Each entity is involved in the relationship. Total participation is
represented by double lines.
 Partial participation − Not all entities are involved in the relationship. Partial
participation is represented by single lines.

2.12 Key
A key is an attribute or set of attributes which helps us in uniquely identifying the rows of a
table. It also helps in establishing relationship among tables. We will now see how this is done
with the help of examples.

Example: If we have the details of students of a classroom stored in Student table as follows:

Now, from this classroom, if we want to call a student whose name is ‘Andrew’ we don't know
which ‘Andrew’ to call as there are two students with the same name. Also, we if know the age
of student ‘Andrew’ we can’t distinguish between both the students because both are having
the same age. So, there must some value through which we can distinguish and uniquely
identify the students. The ‘Roll_no’ attribute will help us in uniquely identifying the rows in a
table. We can say that ‘Roll_no’ is the key here. Now, if we know the ‘Roll_no’ of the student
then there will be no confusion and we can easily select the student from here.

Key can be of the following types:

 Super Key
 Candidate Key
 Primary Key
 Alternate Key
 Foreign Key

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 46
Fundamentals of Database Systems Department of ECE

2.12.1 Super Key


A super key or simply key is a combination of all possible attribute which can uniquely identify
the rows(tuples) in a table. This means that a superkey may have some extra attribute which
isn't necessary for uniquely identifying the rows in the table.

Example: In the given Student Table we can have the following keys as the super key.

1. {Roll_no}
2. {Registration_no}
3. {Roll_no, Registration_no},
4. {Roll_no, Name}
5. {Name, Registration_no}
6. {Roll_no, Name, Registration_no}

All the above keys are able to uniquely identify each row. So, each of these keys is super key.
Here you can see that by using Roll_no only, we can uniquely identify the rows but if you are
making a super key, then you will try to find all the possible cases of keys that can be used to
identify data uniquely.

2.12.2 Candidate Key


A candidate key is a minimal super key or a super key with no redundant attribute. It is called a
minimal superkey because we select a candidate key from a set of super key such that selected
candidate key is the minimum attribute required to uniquely identify the table. It is selected
from the set of the super key which means that all candidate keys are super key. Candidate
Keys are not allowed to have NULL values.

If the subset of the candidate key is a super key, then that candidate key is not a valid
candidate key.
Example: In the above example, we had 6 super keys but all of them cannot become a
candidate key. Only those super keys would become a candidate key which have no redundant
attributes.

1. {Roll_no}: This key doesn't have any redundant or repeating attribute. So, it can be
considered as a candidate key.
2. {Registration_no}: This key also doesn't have any repeating attribute. So, it can be
considered as a candidate key.
3. {Roll_no, Registration_no}: This key cannot be considered as a candidate key because
when we take the subset of this key we get two attributes i.e Roll_no or
Registration_no. Each of these attributes is the candidate key. So, it is not a minimal
super key. Hence, this key is not a candidate key.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 47
Fundamentals of Database Systems Department of ECE

4. {Roll_no, Name}: This key cannot be considered as a candidate key because when we
take the subset of this key we get two attributes i.e. Roll_no or Name. Roll_no is a
candidate key. So, it is not a minimal super key. Hence, this key is not a candidate key.
5. {Name, Registration_no}: This key cannot be considered as a candidate key because
when we take the subset of this key we get two attributes i.e Registration_no or Name.
Registration_no is a candidate key. So, it is not a minimal super key. Hence, this key is
not a candidate key.
6. {Roll_no, Name, Registration_no}: This key cannot be considered as a candidate key
because when we take the subset of this key we get three attributes i.e Roll_no,
Registration_no and Name. Two of these attributes i.e Roll_no and Registration_no are
the candidate key. So, it is not a minimal superkey. Hence, this key is not a candidate
key.
So, from the above discussion, we conclude that we can have only 2 out of above 6
super keys as the candidate key. i.e. (Roll_no) and(Registration_no).

2.12.3 Primary Key


The primary key is the minimal set of attributes which uniquely identifies any row of a table. It
is selected from a set of candidate keys. Any candidate key can become a primary key. It
depends upon the requirements and is done by the Database Administrator (DBA). The primary
key cannot have a NULL value. It cannot have a duplicate value.
Example: In the above example, we saw that we have two candidate keys i.e (Roll_no) and
(Registration_no). From this set, we can select any key as the primary key for our table. It
depends upon our requirement. Here, if we are talking about class then selecting ‘Roll_no’ as
the primary key is more logical instead of ‘Registrartion_no’.

2.12.4 Alternate Key


All the candidate key which are not a primary key are called an alternate key.

Example: In the above example, since we have made ‘Roll_no’ as the Primary Key our Alternate
Key would be ‘Registration_no’.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 48
Fundamentals of Database Systems Department of ECE

2.12.5 Foreign Key:


The foreign key of a table is the attribute which establishes the relationship among tables. The
foreign key is the attribute which points to the primary key of another table.

Example: If we have two tables of Student and Course then we can establish a relationship
between these two tables using a foreign key. The ‘Course_id’ in the Student table is the
foreign key as it establishes the link between the Student and Course Table. So, if we need to
find the information about any course opted by any student then we can go the Course table
using the foreign key.

2.13 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.

2.14 Relational Model Concepts

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.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 49
Fundamentals of Database Systems Department of ECE

10. Attribute domain – Every attribute has some pre-defined value and scope which is known
as attribute domain

2.14 Relational Integrity Constraints


Relational Integrity constraints in DBMS are referred to conditions which must be present for a
valid relation. These Relational constraints in DBMS are derived from the rules in the mini-world
that the database represents.

There are many types of Integrity Constraints in DBMS. Constraints on the Relational database
management system is mostly divided into three main categories are:

1. Domain Constraints
2. Key Constraints
3. Referential Integrity Constraints

2.14.1Domain Constraints
Domain constraints can be violated if an attribute value is not appearing in the corresponding
domain or it is not of the appropriate data type.

Domain constraints specify that within each tuple, and the value of each attribute must be
unique. This is specified as data types which include standard data types integers, real numbers,
characters, Booleans, variable length strings, etc.

2.14.2 Key Constraints


An attribute that can uniquely identify a tuple in a relation is called the key of the table. The value
of the attribute for different tuples in the relation has to be unique.

Example:

In the given table, CustomerID is a key attribute of Customer Table. It is most likely to have a
single key for one customer, CustomerID =1 is only for the CustomerName =” Google”.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 50
Fundamentals of Database Systems Department of ECE

Customer ID Customer Name Status


1 Google Active
2 Amazon Active
3 Apple In Active
2.14.3 Referential Integrity Constraints
Referential Integrity constraints in DBMS are based on the concept of Foreign Keys. A foreign key
is an important attribute of a relation which should be referred to in other relationships.
Referential integrity constraint state happens where relation refers to a key attribute of a
different or same relation. However, that key element must exist in the table.

Example:

In the above example, we have 2 relations, Customer and Billing.


Tuple for CustomerID =1 is referenced twice in the relation Billing. So we know
CustomerName=Google has billing amount $300

2.15 Operations in Relational Model


Four basic update operations performed on relational database model are
Insert, update, delete and select.
 Insert is used to insert data into the relation
 Delete is used to delete tuples from the table.
 Modify allows you to change the values of some attributes in existing tuples.
 Select allows you to choose a specific range of data.
 Whenever one of these operations are applied, integrity constraints specified on the
relational database schema must never be violated.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 51
Fundamentals of Database Systems Department of ECE

 Insert Operation
 The insert operation gives values of the attribute for a new tuple which should be
inserted into a relation.

Update Operation
 You can see that in the below-given relation table CustomerName= ‘Apple’ is updated
from Inactive to Active.


 Delete Operation
 To specify deletion, a condition on the attributes of the relation selects the tuple to be
deleted.

 In the above-given example, CustomerName= “Apple” is deleted from the table.


 The Delete operation could violate referential integrity if the tuple which is deleted is
referenced by foreign keys from other tuples in the same database.
 Select Operation

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 52
Fundamentals of Database Systems Department of ECE

2.16 Weak Entity and Strong Entity in DBMS


The entity defines the type of data stored; simply it is nothing but a database table. We have the
following two types of entities based on Unique Identification –

1. Strong entity
2. Weak entity

2.16.1. Strong entity


 A strong entity set is an entity that contains sufficient attributes to uniquely identify all its
entities
 Simply strong entity is nothing but an entity set having a primary key attribute or a table
which consists of a primary key column
 The primary key of the strong entity is represented by underlining it

Representation
 The strong entity is represented by a single rectangle.
 Relationship between two strong entities is represented by a single diamond.

Examples for the strong entity

 Consider the ER diagram which consists


of two entities student and course
 Student entity is a strong entity because it
consists of a primary key called student id
which is enough for accessing each record
uniquely
 The same way, course entity contains of
course ID attribute which is capable of
uniquely accessing each row it is each course
details

2.16.2 Weak Entity Set:

 weak entity is an entity set that does not have sufficient attributes for Unique
Identification of its records
 Simply a weak entity is nothing but an entity which does not have a primary key
attribute
 It contains a partial key called as discriminator which helps in identifying a group of
entities from the entity set
 Discriminator is represented by underlining with a dashed line

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 53
Fundamentals of Database Systems Department of ECE

Representation

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


 The double diamond symbol is used for representing the relationship between a strong
entity and weak entity which is known as identifying relationship
 Double lines are used for presenting the connection with a weak entity set with
relationship

Example for weak entity

 In the ER diagram, we have two entities


building and apartment
 Building is a strong entity because it has
a primary key attribute called building
number which is capable of uniquely
identifying all the flats present in the
apartment
 Unlike building, apartment is weak
entity because it does not have any
primary key and door number here acts
only as a discriminator because door
number cannot be used as a primary key,
there might be multiple flats in the building
with the same door number or on different
floors.

2.17 Strong Entity Vs Weak Entity

Strong Entity Weak Entity


Strong entity always has a primary key Will not have a primary key but it has partial
discriminator key
It is not dependent on any other entity Which entity is dependent on the strong entity
Represented by double rectangle relationship
Represented by a single rectangle between a strong entity and the weak entity is
represented by double Diamond
Relationship between two strong entities is
represented by a single diamond
A strong entity has may or may not have total It has always total participation
participation

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 54
Fundamentals of Database Systems Department of ECE

2.18 Examples on Relational Database:

Relational database means the data is stored as well as retrieved in the form of relations
(tables). Table 1 shows the relational database with only one relation called STUDENT which
stores ROLL_NO, NAME, ADDRESS, PHONE and AGE of students.

Student Database:
Roll _No NAME ADDRESS PHONE AGE
401 AKHILA VISHAKAPATNAM 9912204100 24
402 SAMSKRUTHI DUBAI 9704216317 25
403 ASHWINI REDDY LONDON 9346261029 28
404 SANDHYA BANGALORE 9951063698 26
405 SHRAGVI GOKARANA 9755858898 27

These are some important terminologies that are used in terms of relation.
Attribute: Attributes are the properties that define a relation. e.g.; ROLL_NO, NAME etc.
Tuple: Each row in the relation is known as tuple. The above relation contains 4 tuples, one of
which is shown as:

401 AKHILA VISHAKAPATNAM 9912204100 24

Degree: The number of attributes in the relation is known as degree of the relation.
The STUDENT relation defined above has degree 5.
Cardinality: The number of tuples in a relation is known as cardinality. The STUDENT relation
defined above has cardinality 4.
Column: Column represents the set of values for a particular attribute. The column ROLL_NO is
extracted from relation STUDENT.

Roll _No
401
402
403
404
405

The queries to deal with relational database can be categories as:


Data Definition Language: It is used to define the structure of the database. e.g; CREATE
TABLE, ADD COLUMN, DROP COLUMN and so on.

Data Manipulation Language: It is used to manipulate data in the relations. e.g.; INSERT,
DELETE, UPDATE and so on.
Data Query Language: It is used to extract the data from the relations. e.g.; SELECT

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 55
Fundamentals of Database Systems Department of ECE

So first we will consider the Data Query Language. A generic query to retrieve from a relational
database is:
1. SELECT [DISTINCT] Attribute_List FROM R1,R2….RM
2. [WHERE condition]
3. [GROUP BY (Attributes)[HAVING condition]]
4. [ORDER BY(Attributes)[DESC]];

Part of the query represented by statement 1 is compulsory if you want to retrieve from a
relational database. The statements written inside [] are optional. We will look at the possible
query combination on relation shown in Table 1.
Case 1: If we want to retrieve attributes ROLL_NO and NAME of all students, the query will be:

SELECT ROLL_NO, NAME FROM STUDENT;

Roll _No NAME


401 AKHILA
402 SAMSKRUTHI
403 ASHWINI REDDY
404 SANDHYA
405 SHRAGVI

Case 2: If we want to retrieve ROLL_NO and NAME of the students whose ROLL_NO is greater
than 2, the query will be:

SELECT ROLL_NO, NAME FROM STUDENT WHERE ROLL_NO> 402;

Roll_No Name
403 ASHWINI REDDY
404 SANDHYA
405 SHRAGVI

CASE 3: If we want to retrieve all attributes of students, we can write * in place of writing all
attributes as:
SELECT * FROM STUDENT WHERE ROLL_NO>2;

Roll _No NAME ADDRESS PHONE AGE


403 ASHWINI REDDY LONDON 9346261029 28
404 SANDHYA BANGALORE 9951063698 26
405 SHRAGVI GOKARANA 9755858898 27

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 56
Fundamentals of Database Systems Department of ECE

CASE 4: If we want to represent the relation in ascending order by AGE, we can use ORDER BY
clause as:

SELECT * FROM STUDENT ORDER BY AGE;

Roll _No NAME ADDRESS PHONE AGE


401 AKHILA VISHAKAPATNAM 9912204100 24
402 SAMSKRUTHI DUBAI 9704216317 25
403 ASHWINI REDDY LONDON 9346261029 28
404 SANDHYA BANGALORE 9951063698 26
405 SHRAGVI GOKARANA 9755858898 27

Note: ORDER BY AGE is equivalent to ORDER BY AGE ASC. If we want to retrieve the results in
descending order of AGE, we can use ORDER BY AGE DESC.

CASE 5: If we want to retrieve distinct values of an attribute or group of attribute, DISTINCT is


used as in:

SELECT DISTINCT ADDRESS FROM STUDENT;


ADDRESS
VISHAKAPATNAM
DUBAI
LONDON
BANGALORE
GOKARANA
If DISTINCT is not used, DELHI will be repeated twice in result set. Before understanding
GROUP BY and HAVING, we need to understand aggregations functions in SQL.
AGGRATION FUNCTIONS: Aggregation functions are used to perform mathematical operations
on data values of a relation. Some of the common aggregation functions used in SQL are:

COUNT: Count Function is used to count the number of rows in a relation.

SELECT COUNT (PHONE) FROM STUDENT;

COUNT (PHONE)
5

SUM: SUM function is used to add the values of an attribute in a relation.

SELECT SUM (AGE) FROM STUDENT;

SUM (AGE) = 74

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 57
Fundamentals of Database Systems Department of ECE

In the same way, MIN, MAX and AVG can be used. As we have seen above, all aggregation
functions return only 1 row.
AVERAGE: It gives the average values of the tupples. It is also defined as sum divided by count
values.
Syntax:AVG(attributename)
OR
Syntax:SUM(attributename)/COUNT(attributename)
The above mentioned syntax also retrieves the average value of tupples.
MAXIMUM:It extracts the maximum value among the set of tupples.
Syntax:MAX(attributename)
MINIMUM:It extracts the minimum value amongst the set of all the tupples.
Syntax:MIN(attributename)
GROUP BY: Group by is used to group the tuples of a relation based on an attribute or group of
attribute. It is always combined with aggregation function which is computed on group
SELECT ADDRESS, SUM(AGE) FROM STUDENT GROUP BY (ADDRESS);

ADDRESS AGE
VISHAKAPATNAM 24
DUBAI 25
LONDON 28
BANGALORE 26
GOKARANA 27

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 58
Fundamentals of Database Systems Department of ECE

UNIT –III
STRUCTURED QUERY LANGUAGE (SQL)

Structured Query Language is a standard Database language which is used to create, maintain
and retrieve the relational database. Following are some interesting facts about SQL.

 SQL is case insensitive. But it is a recommended practice to use keywords (like SELECT,
UPDATE, CREATE, etc) in capital letters and use user defined things (liked table name,
column name, etc) in small letters.
 We can write comments in SQL using “–” (double hyphen) at the beginning of any line.
 SQL is the programming language for relational databases (explained below) like
MySQL, Oracle, Sybase, SQL Server, Postgre, etc. Other non-relational databases (also
called NoSQL) databases like MongoDB, DynamoDB, etc do not use SQL
 Although there is an ISO standard for SQL, most of the implementations slightly vary in
syntax. So we may encounter queries that work in SQL Server but do not work in MySQL.

3.1 SQL Process


When you are executing an SQL command for any RDBMS, the system determines the best way
to carry out your request and SQL engine figures out how to interpret the task.
There are various components included in this process.

These components are −


 Query Dispatcher
 Optimization Engines
 Classic Query Engine
 SQL Query Engine, etc.

A classic query engine handles all the non-


SQL queries, but a SQL query engine won't
handle logical files.

Following is a simple diagram showing the


SQL Architecture −

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 59
Fundamentals of Database Systems Department of ECE

3.2 SQL Commands


The standard SQL commands to interact with relational databases are CREATE, SELECT, INSERT,
UPDATE, DELETE and DROP. These commands can be classified into the following groups based
on their nature −

DDL - Data Definition Language


CREATE - Creates a new table, a view of a table, or other object in the database.
ALTER -Modifies an existing database object, such as a table.
DROP-Deletes an entire table, a view of a table or other objects in the database.

DML - Data Manipulation Language


SELECT-Retrieves certain records from one or more tables.
INSERT - Creates a record.
UPDATE -Modifies records.
DELETE -Deletes records.

DCL - Data Control Language


GRANT - Gives a privilege to user.
REVOKE - Takes back privileges granted from user.

3.3 Characteristics of SQL


 SQL is easy to learn.
 SQL is used to access data from relational database management systems.
 SQL can execute queries against the database.
 SQL is used to describe the data.
 SQL is used to define the data in the database and manipulate it when needed.
 SQL is used to create and drop the database and table.
 SQL is used to create a view, stored procedure, function in a database.
 SQL allows users to set permissions on tables, procedures, and views.

3.4 What is SQL Operator: A set operator in SQL is a keyword that lets you combine the results
of two queries into a single query.

Sometimes when working with SQL, you’ll have a need to query data from two more tables. But
instead of joining these two tables, you’ll need to list the results from both tables in a single
result, or in different rows. That’s what set operators do.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 60
Fundamentals of Database Systems Department of ECE

3.5 Different types of SET operators:


There are a few different set operators that can be used, depending on your needs, and
which database vendor you’re using.
The different set operators are:
 UNION
 UNION ALL
 MINUS
 INTERSECT
 EXCEPT

Using Set Operators:

Set operators are used like this:

SELECT your _select _query Set operator SELECT another _select_query;

 It uses two (or more) SELECT queries, with a set operator in the middle.
There are a few things to keep in mind though.
 When selecting your columns, the number of columns needs to match between queries,
and the data type of each column needs to be compatible.
 So, if you select three columns in the first query, you need to select three columns in the
second query. The data types also need to be compatible, so if you select a number and
two character types in the first query, you need to do the same in the second query.
 Also, if you want to order your results, the ORDER BY must go at the end of the last query.
You can’t add ORDER BY inside each SELECT query before the set operator.

3.6 Our Example Data

 Before we get started, let’s look at some sample data.


 To help explain joins, it helps to see how the SQL queries would work and what the
results would look like.
 So, let’s use an employee and department example. It’s a common example that you
might be used to.

This is the department table:

DEPARTMENT_ID DEPARTMENT_NAME
1 Executive
2 HR
3 Sales
4 Development
5 Support
6 Research

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 61
Fundamentals of Database Systems Department of ECE

And this is the employee table.

EMPLOYEE_ FULL_NAME DEPARTMENT_ ROLE MANAGER_


ID
1 John Smith ID
1 CEO ID
(null)
2 Sarah Goodes 1 CFO 1
3 Wayne Ablett 1 CIO 1
4 Michelle Carey 2 HR Manager 1
5 Chris Matthews 3 Sales Manager 2
6 Andrew Judd 4 Development Manager 3
7 Danielle McLeod 5 Support Manager 3
8 Matthew Swan 2 HR Representative 4
9 Stephanie Richardson 2 Salesperson 5
10 Tony Grant 3 Salesperson 5
11 Jenna Lockett 4 Front-End Developer 6
12 Michael Dunstall 4 Back-End Developer 6
13 Jane Voss 4 Back-End Developer 6
14 Anthony Hird (null) Support 7
15 Natalie Rocca 5 Support 7

This shows a list of 6 departments and 16 employees. The manager_id column in the employee table
refers to the employee_id column in the same table. I’ll show you how to use this later in this guide.

If you want to follow along and create the database yourself, here is the SQL:

CREATE TABLE department_id NUMBER(5) PRIMARY KEY , department _name VARCHAR2(100));

CREATE TABLE employee (employee _id NUMBER(5) PRIMARY KEY , full_name VARCHAR2(100),
department _id NUMBER (5) REFERENCES department (department_id), job_roleVARCHAR2(100),
manager_id NUMBER(5) );

INSERT INTO department (department _id ,department _name ) VALUES (1, ‘Executive’);

INSERT INTO department (department _id ,department _name ) VALUES (2, ‘HR’);

INSERT INTO department (department _id ,department _name ) VALUES (3, ‘Sales’);

INSERT INTO department (department _id ,department _name ) VALUES (4, ‘Development’);

INSERT INTO department (department _id ,department _name ) VALUES (5, ‘Support’);

INSERT INTO department (department _id ,department _name ) VALUES (6, ‘Research’);

INSERT INTO employee (employee _id, full_name , department_id , job_role , manager_id)


VALUES (1 ,’John Smith ‘ , 1, ‘CEO’, NULL) ;

INSERT INTO employee (employee _id, full_name , department_id , job_role , manager_id)


VALUES (2 , 'Sarah Goodes', 1, 'CFO', 1) ;

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 62
Fundamentals of Database Systems Department of ECE

INSERT INTO employee (employee _id, full_name , department_id , job_role , manager_id)


VALUES (3, 'Wayne Ablett', 1, 'CIO', 1) ;

INSERT INTO employee (employee _id, full_name , department_id , job_role , manager_id)


VALUES (4, 'Michelle Carey', 2, 'HR Manager', 1) ;

INSERT INTO employee (employee _id, full_name , department_id , job_role , manager_id)


VALUES (5, 'Chris Matthews', 3, 'Sales Manager ', 2) ;

INSERT INTO employee (employee _id, full_name , department_id , job_role , manager_id)


VALUES (6, 'Andrew Judd', 4, 'Development Manager', 3) ;

INSERT INTO employee (employee _id, full_name , department_id , job_role , manager_id)


VALUES (7, 'Danielle McLeod', 5, 'Support Manager', 3) ;

INSERT INTO employee (employee _id, full_name , department_id , job_role , manager_id)


VALUES (8, 'Matthew Swan', 2, 'HR Representative', 4) ;

INSERT INTO employee (employee _id, full_name , department_id , job_role , manager_id)


VALUES (9, 'Stephanie Richardson', 2, 'Salesperson', 5) ;

INSERT INTO employee (employee _id, full_name , department_id , job_role , manager_id)


VALUES (10, 'Tony Grant', 3, 'Salesperson', 5) ;

INSERT INTO employee (employee _id, full_name , department_id , job_role , manager_id)


VALUES (11, 'Jenna Lockett', 4, 'Front-End Developer', 6) ;

INSERT INTO employee (employee _id, full_name , department_id , job_role , manager_id)


VALUES (12, 'Michael Dunstall', 4, 'Back-End Developer', 6) ;

INSERT INTO employee (employee _id, full_name , department_id , job_role , manager_id)


VALUES (13, 'Jane Voss', 4, 'Back-End Developer', 6) ;

INSERT INTO employee (employee _id, full_name , department_id , job_role , manager_id)


VALUES (14, 'Anthony Hird', null, 'Support', 7) ;

INSERT INTO employee (employee _id, full_name , department_id , job_role , manager_id)


VALUES (15, 'Natalie Rocca', 5, 'Support', 7) ;

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 63
Fundamentals of Database Systems Department of ECE

Our sample data for this article uses a customer and employee table.
Customer Employee

First_Name Last _Name First_Name Last _Name


Stephen Jones Christina Jones
ark Smith Michael McDonald
Denise King Paula Johnson
Paula Johnson Stephen Jones
Richard Archer Richard Smith

Union: Combining Results


The UNION keyword or set operator will allow you to combine the results of two queries. It
removes any duplicate results and shows you the combination of both.
SELECT first_name, last_name FROM Customer UNION SELECT first_name, last_name FROM
employee;
Result :

First_Name Last _Name


Stephen Jones
Mark Smith
Denise King
Paula Johnson
Richard Archer
Christina Jones
Michael McDonald
Richard Smith

This shows us all customer and employee records.

But looking at this, we can’t tell which record comes from each table. Often we don’t need to
know, but sometimes we do.

How can we do that? We can add a static value to each query to indicate which table it came
from, or what type of record it is. As long as the number and type of columns match, the query
will work.
SELECT ‘ Customer ‘ AS record_type , First_name , last_name FROM Customer UNION SELECT
‘Employee’ , First _name , Last_name FROM employee ;

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 64
Fundamentals of Database Systems Department of ECE

Result :

Record –Type First_Name Last _Name


Customer Stephen Jones
Customer Mark Smith
Customer Denise King
Customer Paula Johnson
Customer Richard Archer
Employee Christina Jones
Employee Michael McDonald
Employee Richard Smith

In this query, I added in a value of ‘Customer’ to display for all records from the Customer
table. It has a column alias of record_type. The same column is labelled as ‘Employee’ from
the employee table. Looking at the results you can see which records came from which table.

You don’t need to specify the column aliases on the second table. Oracle will know that the
first columns match and use the alias already provided in the first query.

To order the results, the ORDER BY needs to go at the end.

SELECT ‘ Customer ‘ AS record_type , first _name , last_name FROM customer UNION


SELECT ‘ Employee ‘ , first_name , last_name FROM employee ORDER BY record_type
,first_name , last_name ;
Results :

Record –Type First_Name Last _Name


Customer Denise King
Customer Mark Smith
Customer Paula Johnson
Customer Richard Archer
Customer Stephen Jones
Employee Christina Jones
Employee Michael McDonald
Employee Richard Smith

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 65
Fundamentals of Database Systems Department of ECE

All of the set operators support standard keywords inside the SELECT statement. The set
operator is just a way of combining results.
So, you can add WHERE clauses like this if you need to:
SELECT ‘ Customer ‘ AS record_type , first _name , last_name FROM customer WHERE
status = “ Active” UNION SELECT ‘ Employee ‘ , first_name , last_name FROM
employee WHERE emp_status = ‘ Current ‘ ORDER BY record_type ,first_name ,
last_name ;

What’s the Difference Between a UNION and a JOIN?

The UNION and JOIN keywords both combine results from two different tables or queries.

The difference is how they are combined.

UNION combines data into separate rows, and JOIN combines data into separate columns.

When performing a JOIN, there is a column that matches between the two tables, and
additional data may be displayed.

If we wanted to JOIN our employee and customer tables, our query might look like this:

SELECT e.emp_id , e.first_name , e.last_name , c.customer _id, c.first_name, c.last_name


FROM employee e INNER JOIN customer c ON e.first _name = C.first_name AND
e.last_name =c.last_name ;
Result:

cust_id first_name last_name emp_id first_name last_name


15 Stephen Jones 3 Stephen Jones
81 Paula Johnson 9 Paula Johnson

When we use UNION to combine our tables, it looks like this:


SELECT first_name ,last_name FROM customer UNION SELECT first_name , last_name FROM
employee ;

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 66
Fundamentals of Database Systems Department of ECE

Result :

First_name last_name

Stephen Jones

Mark Smith

Denise King

Paula Johnson

Richard Archer

Christina Jones

Michael McDonald

Richard Smith

We can use different JOIN types to display different records based on matches being found,
but in general, that’s how a join is different to a UNION.

MINUS:
Another set operator we can use is the MINUS keyword.
The MINUS set operator will return results that are found in the first query specified that
don’t exist in the second query.

Using our example data, we could use the MINUS set operator to find all names in the
customer table that don’t exist in the employee table.

Our query would look like this:


SELECT first_name, last_name FROM Customer MINUS SELECT first_name, last_name FROM
employee;
Result :

First_name last_name
Mark Smith
Denise King
Richard Archer

If a result exists in the employee table as well as the customer table, it is not shown. Only the
results from the customer table that are not in the employee table are shown.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 67
Fundamentals of Database Systems Department of ECE

What About the EXCEPT Set Operator?

The EXCEPT keyword is another set operator you might see in your code or in online
examples.

EXCEPT is the same as MINUS – they both show results from one query that don’t exist in
another query.

However, MINUS is an Oracle-specific keyword, and EXCEPT is in other databases such as SQL
Server.

So, if you see EXCEPT anywhere, just know it’s the same as MINUS but for a different
database.

INTERSECT:

The INTERSECT keyword allows you to find results that exist in both queries. Two SELECT
statements are needed, and any results that are found in both of them are returned if
INTERSECT is used.

Using our example data, we could use the INTERSECT set operator to find all names in the
customer table that don’t exist in the employee table.

Our query would look like this:

SELECT first_name, last_name FROM Customer INTERSECT SELECT first_name, last_name


FROM employee;

Result :

first_name last_name

Stephen Jones

Paula Johnson

This shows all names that are in both the customer and employee table.
If we want to order these, we add an ORDER BY at the end.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 68
Fundamentals of Database Systems Department of ECE

SELECT First_name , last_name FROM Customer INTERSECT SELECT first_name ,last_name


FROM employee ORDER BY First _name , Last_name ;
Result :
First_name last_name

Paula Johnson

Stephen Jones

What’s the Difference between UNION and INTERSECT?

The difference between UNION and INTERSECT is that UNION gets results from both queries
and combines them, while INTERSECT gets results that only exist in both queries.

So, if Query 1 returns records A and B, and Query 2 returns records B and C, UNION would
return A, B and C. INTERSECT would only return B.

Sub queries:
FROM
The SQL FROM clause is where you specify where your data is to be retrieved from. This will
often be a table in your database, but it can also be a view or a subquery.

The syntax of the FROM clause looks the same regardless of what you’re selecting from:

SELECT first_name , last_name FROM employee ;

This example selects data from one table: the employee table. We can’t actually tell if it’s a
table or a view by looking at the name, but it doesn’t matter for the purpose of this query.

You can also use joins to SELECT data from multiple tables. I’ve written an entire post on
joins, as they are a pretty big feature of SQL, but a basic query with a join looks like this:

SELECT first_name, last_name, department _name FROM employee INNER JOIN


department ON employee .dept_id = department .id ;

This query will show the employee’s first name and last name, as well as their department
name. It uses an INNER JOIN to match records based on each table’s department ID.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 69
Fundamentals of Database Systems Department of ECE

WHERE:
The WHERE clause of the SQL SELECT statement is where you determine which rows to return
from your table or view. It’s an optional clause, so if you don’t specify a WHERE clause in your
query, you’ll get all the records:

SELECT first _name, last_name FROM employee WHERE <criteria>;

The criteria is a rule that is checked against each row. If the criteria is true for a row, the row is
included in the results. If it is false, the row is not included.

For example, this query shows all employees with a first_name of John.

SELECT first _name , last_name FROM employee WHERE first_name =’John’ ;

The WHERE clause can get quite complicated. You can have multiple criteria using the AND
or OR keywords, you can use brackets to group criteria, you can have greater than and less
than, partial matches, and much more.;

GROUP BY :
The SQL GROUP BY clause is used when you are using aggregate functions and want to
specify what values you want to have those aggregate functions calculated by.
For example, this query will count all employees:

SELECT COUNT ( *) FROM Employee


This query will count employees in each department, using the GROUP BY clause:
SELECT dept_id , COUNT ( * ) FROM employee GROUP BY dept_id ;
It’s an optional clause, but if you’re using an aggregate function like COUNT along with other
columns, you’ll need to use it.

HAVING:
The HAVING clause lets you filter a SELECT query that uses a GROUP BY clause based on the
results after a GROUP BY.

It uses the same concept as a WHERE clause, except the WHERE clause filters data before the
grouping, and HAVING filters data after the grouping.

For example, this query shows the count of employees in each department where there is
more than 1 employee in the department.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 70
Fundamentals of Database Systems Department of ECE

SELECT dept _id , COUNT (*) FROM employee GROUP BY dept_id HAVING COUNT ( *)
>1;

ORDER BY

The ORDER BY clause lets you specify the order you want the query results to be displayed in.

The database does not guarantee the order that the results are returned in. Even if it looks
like there is an order (e.g. ordered by ID), if you run the same query at a later date, the order
could change.

So, if you want your data in a specific order, you can use the ORDER BY clause:

SELECT first_name, last_name FROM employee ORDER BY last_name ASC ;

https://www.databasestar.com/sql-joins/

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 71
Fundamentals of Database Systems Department of ECE

CHAPTER – IV
DEPENDENCIES AND NORMAL FORMS
4.1 What is Normalization?
Normalization is a database design technique that reduces data redundancy and eliminates
undesirable characteristics like Insertion, Update and Deletion Anomalies. A normalization rule
divides larger tables into smaller tables and links them using relationships. The purpose of
Normalisation in SQL is to eliminate redundant (repetitive) data and ensure data is stored
logically.
The inventor of the relational model Edgar Codd proposed the theory of normalization of data
with the introduction of the First Normal Form, and he continued to extend theory with Second
and Third Normal Form. Later he joined Raymond F. Boyce to develop the theory of Boyce-Codd
Normal Form.

4.2 Database Normal Forms


Here is a list of Normal Forms in SQL:

 1NF (First Normal Form)


 2NF (Second Normal Form)
 3NF (Third Normal Form)
 BCNF (Boyce-Codd Normal Form)
 4NF (Fourth Normal Form)
 5NF (Fifth Normal Form)
 6NF (Sixth Normal Form)

4.3 Database Normalization with Examples


Database Normalization Example can be easily understood with the help of a case study.
Assume, a video library maintains a database of movies rented out. Without any normalization in
database, all information is stored in one table as shown below. Let’s understand Normalization
database with normalization example with solution:

Names Address Movies data Salutation


First Street – Pirates of the Caribbean , Clash Ms.
Janet Jones
Plot no-4 of Titans
Forgetting Sarah Marshal , Daddy Mr.
Robert Phill 3rd street -34
‘s little Girl
Robert Phill 5th Avenue Clash of Titans Mr.

Here you see Movies Rented column has multiple values.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 72
Fundamentals of Database Systems Department of ECE

4.4: 1NF (First Normal Form) Rules:

As per the rule of first normal form, an attribute (column) of a table cannot hold multiple values.
It should hold only atomic values.

 Each table cell should contain a single value.


 Each record needs to be unique.

From the Above table, we make in 1 NF


Names Address Movies data Salutation
Janet Jones First Street –Plot no-4 Pirates of the Caribbean Ms
Janet Jones First Street –Plot no-4 Clash of Titans Ms.
Robert Phill 3rd street -34 Forgetting Sarah Marshal Mr.
Robert Phill 3rd street -34 Daddy ‘s little Girl Mr.
Robert Phill 5th Avenue Clash of Titans Mr.

4.4.1.1 What is a KEY in SQL?


A KEY in SQL is a value used to identify records in a table uniquely. An SQL KEY is a single column
or combination of multiple columns used to uniquely identify rows or tuples in the table. SQL Key
is used to identify duplicate information, and it also helps establish a relationship between
multiple tables in the database.
Note: Columns in a table that are NOT used to identify a record uniquely are called non-key
columns.

4.4.1.2 What is a Primary Key?


A primary is a single column value used to identify a database record uniquely.

It has following attributes

 A primary key cannot be NULL


 A primary key value must be unique
 The primary key values should rarely be changed
 The primary key must be given a value when a new record is inserted.

4.4.1.3 What is Composite Key?


A composite key is a primary key composed of multiple columns used to identify a record
uniquely

In our database, we have two people with the same name Robert Phil, but they live in different
places.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 73
Fundamentals of Database Systems Department of ECE

Fig: Composite key in Database

Hence, we require both Full Name and Address to identify a record uniquely. That is a composite
key.

4.5: 2NF (Second Normal Form) Rules

 Rule 1- It should be in 1NF


 Rule 2- Single Column Primary Key that does not functionally dependant on any subset of
candidate key relation

It is clear that we can’t move forward to make our simple database in 2 nd Normalization form
unless we partition the table above.

Membership Names Address Movies data


1 Janet Jones First Street –Plot Pirates of the Caribbean , Clash of Titans
2 Robert Phill 3rd street
no-4 -34 Forgetting Sarah Marshal , Daddy ‘s little
th
3 Robert Phill 5 Avenue Clash Girl
of Titans

Membership Movies data


1 Pirates of the Caribbean
1 Clash of Titans
2 Forgetting Sarah Marshal
2 Daddy ‘s little Girl
3 Clash of Titans

We have divided our 1NF table into two tables viz. Table 1 and Table2. Table 1 contains member
information. Table 2 contains information on movies rented.

We have introduced a new column called Membership_id which is the primary key for table 1.
Records can be uniquely identified in Table 1 using membership id

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 74
Fundamentals of Database Systems Department of ECE

4.5.1: Database – Foreign Key: From the above table, Membership_ID is the Foreign Key
Membership Movies data
1 Pirates of the Caribbean
1 Clash of Titans
2 Forgetting Sarah Marshal
2 Daddy ‘s little Girl
3 Clash of Titans

Foreign Key references the primary key of another Table! It helps connect your Tables

 A foreign key can have a different name from its primary key
 It ensures rows in one table have corresponding rows in another
 Unlike the Primary key, they do not have to be unique. Most often they aren’t
 Foreign keys can be null even though primary keys can not

Foreign Key

Membership Movies data


1 Pirates of the Caribbean
1 Clash of Titans
2 Forgetting Sarah Marshal
2 Daddy ‘s little Girl
3 Clash of Titans

 Foreign key references primary key


 Foreign key can only have values present in primary key
 It could have a name other than that of primary key
Primary Key

MemberShip Names Address Salutation


First Street –Plot
1 Janet Jones Ms
no-4
rd
2 Robert Phill 3 street -34 Mr.
3 Robert Phill 5th Avenue Mr.

4.5.2 Why do you need a foreign key?

Suppose, a novice inserts a record in Table below such as


Insert a record in Table below where Member ID =101
Membership Movies data
101 Pirates of the Caribbean , Clash of Titans

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 75
Fundamentals of Database Systems Department of ECE

But Membership ID 101 is not present in table above


Membership Names Address Salutation
1 Janet Jones First Street –Plot no-4 Ms.
2 Robert Phill 3rd street -34 Mr
3 Robert Phill 5th Avenue Mr

But Database will throw an ERROR this helps in referential integrity


 You will only be able to insert values into your foreign key that exist in the unique key in
the parent table. This helps in referential integrity.
 The above problem can be overcome by declaring membership id from above Table 2 as
foreign key of membership id from Table1
 Now, if somebody tries to insert a value in the membership id field that does not exist in
the parent table, an error will be shown!

4.5.3 What are transitive functional dependencies?


A transitive functional dependency is when changing a non-key column, might cause any of the
other non-key columns to change

Consider the table 1. Changing the non-key column Full Name may change Salutation.

4.6: 3NF (Third Normal Form) Rules


 Rule 1- Be in 2NF
 Rule 2- Has no transitive functional dependencies

To move our 2NF table into 3NF, we again need to again divide our table.

Below is a 3NF example in SQL database:

 We have again divided our tables and created a new table which stores salutation
 There are no transitive functional dependencies, and hence our table is in 3NF

In Table 3 Salutation ID is primary key, and in Table 1 Salutation ID is foreign to primary key in
Table 3

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 76
Fundamentals of Database Systems Department of ECE

4.7 Boyce Codd normal form (BCNF)

It is an advance version of 3NF that’s why it is also referred as 3.5NF. BCNF is stricter than 3NF. A
table complies with BCNF if it is in 3NF and for every functional dependency X->Y, X should be the
super key of the table.

Example: Suppose there is a company wherein employees work in more than one department.
They store the data like this:

emp_id emp_nationality emp_dept dept_type dept_no_of_emp


1001 Austrian Production and planning D001 200
1001 Austrian stores D001 250
1002 American design and technical support D134 100
1002 American Purchasing department D134 600

unctional dependencies in the table above:


emp_id -> emp_nationality
emp_dept -> {dept_type, dept_no_of_emp}

Candidate key: {emp_id, emp_dept}

The table is not in BCNF as neither emp_id nor emp_dept alone are keys.
To make the table comply with BCNF we can break the table in three tables like this:

emp_nationality table:
emp_id emp_nationality
1001 Austrian
1002 American

emp_dept table:

emp_dept dept_type dept_no_of_emp


Production and planning D001 200
stores D001 250
design and technical support D134 100
Purchasing department D134 600

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 77
Fundamentals of Database Systems Department of ECE

emp_dept_mapping table:

emp_id emp_dept
1001 Production and planning
1001 stores
1002 design and technical support
1002 Purchasing department

Functional dependencies:
emp_id -> emp_nationality
emp_dept -> {dept_type, dept_no_of_emp}

Candidate keys:
For first table: emp_id
For second table: emp_dept
For third table: {emp_id, emp_dept}

This is now in BCNF as in both the functional dependencies left side part is a key.

4.8 A good database design has many benefits and is a goal to achieve for every DBA −
Easy Retrieval of Information
If the design is developed properly, then it would be easier to retrieve information. Correct
design means the tables, constraints, and relationships created are flawless.
Easier Modification
Changes that you make to the value of a given field will not adversely affect the values of other
fields within the table.
Easy to Maintain
The database structure should be easy to maintain. The design is perfect if changes in one field is
not affecting changes in another field.
Information
With a good design, you can enhance the quality and consistency of information.
Well-designed Database
If the database is well defined, then the flaws and issues of a poorly designed database will not
need to be addressed.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 78
Fundamentals of Database Systems Department of ECE

4.9 A badly designed database has the following problems:

 Related data is scattered over various tables. A change must be updated at many places.
It's possible that the information is only half present; it's there in one table, but missing in
another one.
 Data is inconsistent or ambiguous (poly interpretable).
 The database is unnecessary complex, hacked with lots of tricks. The database designer
done unnecessary complex things, where it could have been done so much easier.
 The database has 'hidden' information, for example by the sequence of rows in a table.
 The database is slow, inflexible, hard to extend and cannot handle all real life situations.

4.10 What is Functional Dependency?


Functional Dependency (FD) is a constraint that determines the relation of one attribute to
another attribute in a Database Management System (DBMS). Functional Dependency helps to
maintain the quality of data in the database. It plays a vital role to find the difference between
good and bad database design.

A functional dependency is denoted by an arrow “→”. The functional dependency of X on Y is


represented by X → Y. Let’s understand Functional Dependency in DBMS with example.

4.11 Key Terms :

Key Terms Description

Axioms is a set of inference rules used to infer all the functional dependencies on a
Axiom
relational database.
It is a rule that suggests if you have a table that appears to contain two entities which are
Decomposition
determined by the same primary key then you should consider breaking them up into two
different tables.
Dependent It is displayed on the right side of the functional dependency diagram.

Determinant It is displayed on the left side of the functional dependency Diagram.

It suggests that if two tables are separate, and the PK is the same, you should consider
Union
putting them together

4.12 Rules of Functional Dependencies


Below are the three most important rules for Functional Dependency in Database:

 Reflexive rule –. If X is a set of attributes and Y is_subset_of X, then X holds a value of Y.


 Augmentation rule: When x -> y holds, and c is attribute set, then ac -> bc also holds. That
is adding attributes which do not change the basic dependencies.
 Transitivity rule: This rule is very much similar to the transitive rule in algebra if x -> y
holds and y -> z holds, then x -> z also holds. X -> y is called as functionally that
determines y.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 79
Fundamentals of Database Systems Department of ECE

4.13 Types of Functional Dependencies in DBMS


There are mainly four types of Functional Dependency in DBMS. Following are the types of
Functional Dependencies in DBMS:

 Multivalued Dependency
 Trivial Functional Dependency
 Non-Trivial Functional Dependency
 Transitive Dependency

4.13.1 Multivalued Dependency in DBMS


Multivalued dependency occurs in the situation where there are multiple independent
multivalued attributes in a single table. A multivalued dependency is a complete constraint
between two sets of attributes in a relation. It requires that certain tuples be present in a
relation. Consider the following Multivalued Dependency Example to understand.

Example:
Car_model Maf_year Color
H001 2017 Metallic
H001 2017 Green
H005 2018 Metallic
H005 2018 Blue
H010 2015 Metallic
H033 2012 Gray

In this example, maf_year and color are independent of each other but dependent on
car_model. In this example, these two columns are said to be multivalue dependent on
car_model.
This dependence can be represented like this:
car_model -> maf_year
car_model-> colour
4.13.2 Trivial Functional Dependency in DBMS
The Trivial dependency is a set of attributes which are called a trivial if the set of attributes are
included in that attribute.

So, X -> Y is a trivial functional dependency if Y is a subset of X. Let’s understand with a Trivial
Functional Dependency Example.

For example:
Emp_id Emp_name
AS555 Harry
AS811 George
AS999 Kevin

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 80
Fundamentals of Database Systems Department of ECE

Consider this table of with two columns Emp_id and Emp_name.

{Emp_id, Emp_name} -> Emp_id is a trivial functional dependency as Emp_id is a subset of


{Emp_id,Emp_name}.

4.13.3 Non Trivial Functional Dependency in DBMS


Functional dependency which also known as a nontrivial dependency occurs when A->B holds
true where B is not a subset of A. In a relationship, if attribute B is not a subset of attribute A,
then it is considered as a non-trivial dependency.

Company CEO Age


Microsoft Satya Nadella 51
Google Sundar Pichai 46
Apple Tim Cook 57

Example:

(Company} -> {CEO} (if we know the Company, we knows the CEO name)

But CEO is not a subset of Company, and hence it’s non-trivial functional dependency.

4.13.4 Transitive Dependency in DBMS


A Transitive Dependency is a type of functional dependency which happens when t is indirectly
formed by two functional dependencies. Let’s understand with the following Transitive
Dependency Example.

Example:

Company CEO Age


Microsoft Satya Nadella 51
Google Sundar Pichai 46
Alibaba Jack Ma 54

{Company} -> {CEO} (if we know the compay, we know its CEO’s name)

{CEO } -> {Age} If we know the CEO, we know the Age

Therefore according to the rule of rule of transitive dependency:

{ Company} -> {Age} should hold, that makes sense because if we know the company name, we
can know his age.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 81
Fundamentals of Database Systems Department of ECE

4.15 Armstrong’s Axioms in Functional Dependency


The term Armstrong axioms refer to the sound and complete set of inference rules or axioms,
introduced by William W. Armstrong, that is used to test the logical implication of functional
dependencies. If F is a set of functional dependencies then the closure of F, denoted as ,
is the set of all functional dependencies logically implied by F. Armstrong’s Axioms are a set of
rules, that when applied repeatedly, generates a closure of functional dependencies.

Axioms –

Secondary Rules : These rules can be derived from the above axioms.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 82
Fundamentals of Database Systems Department of ECE

UNIT-V
TRANSACTIONS

5.1 Transactions:

 The transaction is a set of logically related operation. It contains a group of tasks.


 A transaction is an action or series of actions. It is performed by a single user to perform
operations for accessing the contents of the database.

OR

A transaction is an action or series of actions that are being performed by a single user or
application program, which reads or updates the contents of the database.

A transaction can be defined as a logical unit of work on the database. This may be an entire
program, a piece of a program, or a single command (like the SQL commands such as INSERT or
UPDATE), and it may engage in any number of operations on the database. In the database
context, the execution of an application program can be thought of as one or more transactions
with non-database processing taking place in between.

Example: Suppose an employee of bank transfers Rs 800 from X's account to Y's account. This
small transaction contains several low-level tasks:

X – ACCOUNT Y-ACCOUNT

 Open_Account(X) Open_Account(y)
 Old_Balance = X.balance Old _Balance = Y.Balance
 New_Balance = Old_Balance - 800 New_Balance = Old_Balance + 800
 X.balance = New_Balance Y.balance = New_Balance
 Close_Account(X) Close_Account(Y)

5.2 Operations of Transaction:

 Read(X): Read operation is used to read the value of X from the database and stores it
in a buffer in main memory.
 Write(X): Write operation is used to write the value back to the database from the
buffer.
 Let's take an example to debit transaction from an account which consists of following
operations:
 1. R(X);
 2. X = X - 500;
 3. W(X);

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 83
Fundamentals of Database Systems Department of ECE

Let's assume the value of X before starting of the transaction is 4000.


 The first operation reads X's value from database and stores it in a buffer.
 The second operation will decrease the value of X by 500. So buffer will contain 3500.
 The third operation will write the buffer's value to the database. So X's final value will be
3500.
But it may be possible that because of the failure of hardware, software or power, etc. that
transaction may fail before finished all the operations in the set.

For example: If in the above transaction, the debit transaction fails after executing operation 2
then X's value will remain 4000 in the database which is not acceptable by the bank.

To solve this problem, we have two important operations:

To solve this problem, we have two important operations:


Commit: It is used to save the work done permanently.
Rollback: It is used to undo the work done.

5.3 Transaction property


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

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 84
Fundamentals of Database Systems Department of ECE

Atomicity
 It states that all operations of the transaction take place at once if not, the transaction is
aborted.
 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.

Example: Let's assume that following transaction T consisting of T1 and T2. A consists of Rs 600
and B consists of Rs 300. Transfer Rs 100 from account A to account B.

T1 T2

Read(A) Read(B)
A:=A-100 Y:=Y+100
Write(A) Write(B)

After completion of the transaction, A consists of Rs 500 and B consists of Rs 400.


If the transaction T fails after the completion of transaction T1 but before completion of transaction T2,
then the amount will be deducted from A but not added to B. This shows the inconsistent database state.
In order to ensure correctness of database state, the transaction must be executed in entirety.
Consistency
 The integrity constraints are maintained so that the database is consistent before and
after the transaction.
 The execution of a transaction will leave a database in either its prior stable state or a
new stable state.
 The consistent property of database states that every transaction sees a consistent
database instance.
 The transaction is used to transform the database from one consistent state to another
consistent state.
For example: The total amount must be maintained before or after the transaction.
1. Total before T occurs = 600+300=900
2. Total after T occurs= 500+400=900
Therefore, the database is consistent. In the case when T1 is completed but T2 fails, then
inconsistency will occur.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 85
Fundamentals of Database Systems Department of ECE

Isolation
 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.
 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.
 The concurrency control subsystem of the DBMS enforced the isolation property.
Durability
 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.
 The recovery subsystem of the DBMS has the responsibility of Durability property.

5.4 States of Transaction:


In a database, the transaction can be in one of the following states -

Active state
 The active state is the first state of every transaction. In this state, the transaction is being
executed.
 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
 In the partially committed state, a transaction executes its final operation, but the data is
still not saved to the database.
 In the total mark calculation example, a final display of the total marks step is executed in
this state.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 86
Fundamentals of Database Systems Department of ECE

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
 If any of the checks made by the database recovery system fails, then the transaction is said
to be in the failed state.
 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.

Aborted
 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.
 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.
 After aborting the transaction, the database recovery module will select one of the two
operations:

 Re-start the transaction


 Kill the transaction

5.5 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.

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.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 87
Fundamentals of Database Systems Department of ECE

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.

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

2. Non-serial Schedule
 If interleaving of operations is allowed, then there will be non-serial schedule.
 It contains many possible orders in which the system can execute the individual
operations of the transactions.
 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

 The serializability of schedules is used to find non-serial schedules that allow the
transaction to execute concurrently without interfering with one another.
 It identifies which schedules are correct when executions of the transaction have
interleaving of their operations.
 A non-serial schedule will be serializable if its result is equal to the result of its
transactions executed serially.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 88
Fundamentals of Database Systems Department of ECE

Here :
Schedule A and Schedule B are serial schedule.
Schedule C and Schedule D are Non-serial schedule.

5.6 Testing of Serializability

Serialization Graph is used to test the Serializability of a schedule.

Assume a schedule S. For S, we construct a graph known as precedence graph. This graph
has a pair G = (V, E), where V consists a set of vertices, and E consists a set of edges. The
set of vertices is used to contain all the transactions participating in the schedule. The set
of edges is used to contain all edges Ti ->Tj for which one of the three conditions holds:

1. Create a node Ti → Tj if Ti executes write (Q) before Tj executes read (Q).


2. Create a node Ti → Tj if Ti executes read (Q) before Tj executes write (Q).
3. Create a node Ti → Tj if Ti executes write (Q) before Tj executes write (Q).

Precedence of Graph S :

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 89
Fundamentals of Database Systems Department of ECE

 If a precedence graph contains a single edge Ti → Tj, then all the instructions of Ti are
executed before the first instruction of Tj is executed.
 If a precedence graph for schedule S contains a cycle, then S is non-serializable. If the
precedence graph has no cycle, then S is known as serializable.

Read(A): In T1, no subsequent writes to A, so no new edges


Read(B): In T2, no subsequent writes to B, so no new edges
Read(C): In T3, no subsequent writes to C, so no new edges
Write(B): B is subsequently read by T3, so add edge T2 → T3
Write(C): C is subsequently read by T1, so add edge T3 → T1
Write(A): A is subsequently read by T2, so add edge T1 → T2
Write(A): In T2, no subsequent reads to A, so no new edges
Write(C): In T1, no subsequent reads to C, so no new edges
Write(B): In T3, no subsequent reads to B, so no new edges

Precedence graph for schedule S1:

The precedence graph for schedule S1 contains a cycle that's why Schedule S1 is non-serializable.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 90
Fundamentals of Database Systems Department of ECE

.
Explanation:
Read(A): In T4,no subsequent writes to A, so no new edges
Read(C): In T4, no subsequent writes to C, so no new edges
Write(A): A is subsequently read by T5, so add edge T4 → T5
Read(B): In T5,no subsequent writes to B, so no new edges
Write(C): C is subsequently read by T6, so add edge T4 → T6
Write(B): A is subsequently read by T6, so add edge T5 → T6
Write(C): In T6, no subsequent reads to C, so no new edges
Write(A): In T5, no subsequent reads to A, so no new edges
Write(B): In T6, no subsequent reads to B, so no new edges

Precedence graph for schedule S2:

The precedence graph for schedule S2 contains no cycle that's why ScheduleS2 is serializable.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 91
Fundamentals of Database Systems Department of ECE

5.7 Conflict Serializable Schedule


 A schedule is called conflict serializability if after swapping of non-conflicting operations, it
can transform into a serial schedule.
 The schedule will be a conflict serializable if it is conflict equivalent to a serial schedule.

Conflicting Operations

The two operations become conflicting if all conditions satisfy:


1. Both belong to separate transactions.
2. They have the same data item.
3. They contain at least one write operation.
Example:
Swapping is possible only if S1 and S2 are logically equal.

Here, S1 = S2. That means it is non-conflict.

Here, S1 ≠ S2. That means it is conflict.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 92
Fundamentals of Database Systems Department of ECE

4.8 Conflict Equivalent

In the conflict equivalent, one can be transformed to another by swapping non-conflicting


operations. In the given example, S2 is conflict equivalent to S1 (S1 can be converted to S2 by
swapping non-conflicting operations).

Two schedules are said to be conflict equivalent if and only if:

1. They contain the same set of the transaction.


2. If each pair of conflict operations are ordered in the same way.

Schedule S2 is a serial schedule because, in this, all operations of T1 are performed before
starting any operation of T2. Schedule S1 can be transformed into a serial schedule by swapping
non-conflicting operations of S1.

After swapping of non-conflict operations, the schedule S1 becomes:

T1 T2

Read(A)
Write(A)
Read(B)
Write(B)
Read(A)
Write(A)
Read(B)
Write(B)

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 93
Fundamentals of Database Systems Department of ECE

5.9 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.

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

Above two schedules are not view equal because, in S1, T3 is reading A updated by T2 and in S2,
T3 is reading A updated by T1.

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.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 94
Fundamentals of Database Systems Department of ECE

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.

Example:

Schedule S

With 3 transactions, the total number of possible schedule

= 3! = 6

 S1 = <T1 T2 T3>
 S2 = <T1 T3 T2>
 S3 = <T2 T3 T1>
 S4 = <T2 T1 T3>
 S5 = <T3 T1 T2>
 S6 = <T3 T2 T1>

Taking first schedule S1:

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 95
Fundamentals of Database Systems Department of ECE

Schedule S1
Step 1: final Updation on data items
In both schedules S and S1, there is no read except the initial read that's why we don't need to
check that condition.
Step 2: Initial Read
The initial read operation in S is done by T1 and in S1, it is also done by T1.
Step 3: Final Write
The final write operation in S is done by T3 and in S1, it is also done by T3. So, S and S1 are view
Equivalent.
The first schedule S1 satisfies all three conditions, so we don't need to check another schedule.
Hence, view equivalent serial schedule is:
T1 → T2 → T3

5.10 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 some other
transaction may also have used value produced by the failed transaction. So we also have to
rollback those transactions.

The above table 1 shows a schedule which has two transactions. T1 reads and writes the value of
A and that value is read and written by T2. T2 commits but later on, T1 fails. Due to the failure,
we have to rollback T1. T2 should also be rollback because it reads the value written by T1, but
T2 can't be rollback because it already committed. So this type of schedule is known as
irrecoverable schedule.

Irrecoverable schedule: The schedule will be irrecoverable if Tj reads the updated value of Ti and
Tj committed before Ti commit.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 96
Fundamentals of Database Systems Department of ECE

The above table 2 shows a schedule with two transactions. Transaction T1 reads and writes A,
and that value is read and written by transaction T2. But later on, T1 fails. Due to this, we have to
rollback T1. T2 should be rollback because T2 has read the value written by T1. As it has not
committed before T1 commits so we can rollback transaction T2 as well. So it is recoverable with
cascade rollback.

Recoverable with cascading rollback: The schedule will be recoverable with cascading rollback
if Tj reads the updated value of Ti. Commit of Tj is delayed till commit of Ti.

The above Table 3 shows a schedule with two transactions. Transaction T1 reads and write A and
commits, and that value is read and written by T2. So this is a cascade less recoverable schedule.

5.11 Transaction Isolation Levels in DBMS:


As we know that, in order to maintain consistency in a database, it follows ACID properties.
Among these four properties (Atomicity, Consistency, Isolation and Durability) Isolation
determines how transaction integrity is visible to other users and systems. It means that a
transaction should take place in a system in such a way that it is the only transaction that is
accessing the resources in a database system.

Isolation levels define the degree to which a transaction must be isolated from the data
modifications made by any other transaction in the database system. A transaction isolation
level is defined by the following phenomena –
 Dirty Read – A Dirty read is the situation when a transaction reads a data that has not
yet been committed. For example, let’s say transaction 1 updates a row and leaves it
uncommitted, meanwhile, Transaction 2 reads the updated row. If transaction 1 rolls back
the change, transaction 2 will have read data that is considered never to have existed.
 Non Repeatable read – Non Repeatable read occurs when a transaction reads same
row twice, and get a different value each time. For example, suppose transaction T1 reads
data. Due to concurrency, another transaction T2 updates the same data and commit, Now
if transaction T1 rereads the same data, it will retrieve a different value.
 Phantom Read – Phantom Read occurs when two same queries are executed, but the
rows retrieved by the two, are different. For example, suppose transaction T1 retrieves a
set of rows that satisfy some search criteria. Now, Transaction T2 generates some new rows
that match the search criteria for transaction T1. If transaction T1 re-executes the
statement that reads the rows, it gets a different set of rows this time.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 97
Fundamentals of Database Systems Department of ECE

Based on these phenomena, The SQL standard defines four isolation levels:
1. Read Uncommitted – Read Uncommitted is the lowest isolation level. In this level, one
transaction may read not yet committed changes made by other transaction, thereby
allowing dirty reads. In this level, transactions are not isolated from each other.
2. Read Committed – This isolation level guarantees that any data read is committed at
the moment it is read. Thus it does not allow dirty read. The transaction holds a read or
write lock on the current row, and thus prevent other transactions from reading, updating
or deleting it.
3. Repeatable Read – This is the most restrictive isolation level. The transaction holds read
locks on all rows it references and writes locks on all rows it inserts, updates, or deletes.
Since other transaction cannot read, update or delete these rows, consequently it avoids
non-repeatable read.
4. 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.

5.12 Transaction definition in SQL:

A transaction is a unit of work that is performed against a database. Transactions are units or
sequences of work accomplished in a logical order, whether in a manual fashion by a user or
automatically by some sort of a database program. A transaction is the propagation of one or
more changes to the database.

How to implement Transactions using SQL?


Following commands are used to control transactions. It is important to note that these
statements cannot be used while creating tables and are only used with the DML Commands
such as – INSERT, UPDATE and DELETE.

1. BEGIN TRANSACTION: It indicates the start point of an explicit or local transaction.


Syntax: BEGIN TRANSACTION transaction_name ;
2. SET TRANSACTION: Places a name on a transaction.
Syntax: SET TRANSACTION [READ WRITE | READ ONLY];
3. COMMIT: If everything is in order with all statements within a single transaction, all changes
are recorded together in the database is called committed. The COMMIT command saves all
the transactions to the database since the last COMMIT or ROLLBACK command.
Syntax: COMMIT;
Example 1 :

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 98
Fundamentals of Database Systems Department of ECE

Following is an example which would delete those records from the table which have age = 20
and then COMMIT the changes in the database.
Queries:
DELETE FROM Student WHERE AGE = 20;
COMMIT;
Output:
Thus, two rows from the table would be deleted and the SELECT statement would look like,

4. ROLLBACK: If any error occurs with any of the SQL grouped statements, all changes need to
be aborted. The process of reversing changes is called rollback. This command can only be
used to undo transactions since the last COMMIT or ROLLBACK command was issued.
Syntax: ROLLBACK;
Example:
From the above example 1
Delete those records from the table which have age =20 and then ROLLBACK changes in the
database.
Queries:
DELETE FROM student WHERE AGE =20;
ROLLBACK;
OUTPUT:

5. SAVEPOINT: creates points within the groups of transactions in which to ROLLBACK.


A SAVEPOINT is a point in a transaction in which you can roll the transaction back to a certain
point without rolling back the entire transaction.

Syntax for Savepoint command:


SAVEPOINT SAVEPOINT_NAME;

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 99
Fundamentals of Database Systems Department of ECE

This command is used only in the creation of SAVEPOINT among all the transactions.
In general ROLLBACK is used to undo a group of transactions.
Syntax for rolling back to Savepoint command:

ROLLBACK TO SAVEPOINT_NAME;
you can ROLLBACK to any SAVEPOINT at any time to return the appropriate data to its original
state.
Example:
From the above example Sample table1,
Delete those records from the table which have age = 20 and then ROLLBACK the changes in
the database by keeping Savepoints.
Queries:
SAVEPOINT SP1; //Savepoint created.
DELETE FROM Student WHERE AGE = 20; //deleted
SAVEPOINT SP2; //Savepoint created.
Here SP1 is first SAVEPOINT created before deletion.
In this example one deletion have taken place.
After deletion again SAVEPOINT SP2 is created.

Deletion have been taken place, let us assume that you have changed your mind and decided
to ROLLBACK to the SAVEPOINT that you identified as SP1 which is before deletion.
deletion is undone by this statement ,

ROLLBACK TO SP1;
//Rollback completed.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 100
Fundamentals of Database Systems Department of ECE

6. RELEASE SAVEPOINT:- This command is used to remove a SAVEPOINT that you have
created.
Syntax: RELEASE SAVEPOINT SAVEPOINT_NAME
Once a SAVEPOINT has been released, you can no longer use the ROLLBACK command to undo
transactions performed since the last SAVEPOINT.
It is used to initiate a database transaction and used to specify characteristics of the
transaction that follows.
5.13 Serializability by Locks-Locking: 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:
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:
o In the exclusive lock, the data item can be both reads as well as written by the
transaction.
o This lock is exclusive, and in this lock, multiple transactions do not modify the same data
simultaneously.

There are four types of lock protocols available:

1. Simplistic lock protocol

It is the simplest way of locking the data while transaction. Simplistic lock-based protocols allow
all the transactions to get the lock on the data before insert or delete or update on it. It will
unlock the data item after completing the transaction.

2. Pre-claiming Lock Protocol


o Pre-claiming Lock Protocols evaluate the transaction to list all the data items on which
they need locks.
o Before initiating an execution of the transaction, it requests DBMS for all the lock on all
those data items.
o If all the locks are granted then this protocol allows the transaction to begin. When the
transaction is completed then it releases all the lock.
o If all the locks are not granted then this protocol allows the transaction to rolls back and
waits until all the locks are granted.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 101
Fundamentals of Database Systems Department of ECE

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.

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.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 102
Fundamentals of Database Systems Department of ECE

Example :

The following way shows how unlocking and locking work with 2-PL.
Transaction T1:
o Growing phase: from step 1-3
o Shrinking phase: from step 5-7
o Lock point: at 3
Transaction T2:
o Growing phase: from step 2-6
o Shrinking phase: from step 8-9
o Lock point: at 6
Strict Two-phase locking (Strict-2PL)
o The first phase of Strict-2PL is similar to 2PL. In the first phase, after acquiring all the
locks, the transaction continues to execute normally.
o The only difference between 2PL and strict 2PL is that Strict-2PL does not release a lock
after using it.
o Strict-2PL waits until the whole transaction to commit, and then it releases all the locks at
a time.
o Strict-2PL protocol does not have shrinking phase of lock release.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 103
Fundamentals of Database Systems Department of ECE

5.14 Timestamp Ordering Protocol


 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.
 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.
 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.
 Let's assume there are two transactions T1 and T2. Suppose the transaction T1 has
entered the system at 007 times and transaction T2 has entered the system at 009 times.
T1 has the higher priority, so it executes first as it is entered the system first.
 The timestamp ordering protocol also maintains the timestamp of last 'read' and 'write'
operation on a data.

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 If W_TS(X) <= TS(Ti) then the operation is executed.
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 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.

Advantages and Disadvantages of TO protocol:


o TO protocol ensures serializability since the precedence graph is as follows:

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 104
Fundamentals of Database Systems Department of ECE

o TS protocol ensures freedom from deadlock that means no transaction ever waits.
o But the schedule may not be recoverable and may not even be cascade- free.

4.15 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.

 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.
 Hence TS(T) = validation(T).
 The serializability is determined during the validation process. It can't be decided in
advance.
 While executing the transaction, it ensures a greater degree of concurrency and also less
number of conflicts.
 Thus it contains transactions which have less number of rollbacks.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 105
Fundamentals of Database Systems Department of ECE

Assignment Questions
UNIT –I
1. Explain the Types of Languages in DBMS?
2. Explain about Distributed Databases?
3. Explain the DBMS Structure?
4. Differnce between File Processing System VS DBMS

UNIT –II
1. Explain about E R Model?
2. Explain about Primary key, Super Key, Candidate Key with Examples?
3. What are the operations in Relational Databases?
4. What are the Different database Objects

UNIT –III
1. What are the Different types of SET Operations with Examples?
2. What are the Relational Database Operations with Examples?
3. Write 10 Examples for SQL database operations?
4. Write 15 SQL Commands with Syntax?

UNIT –IV
1. What is Normalization and what are the types of Normalization?
2. Explain the difference between Good Schema and Bad Schema?
3. Define Normal Forms with examples?
4. What are the types of Functional Dependencies in DBMS

UNIT –V
1. What are the States of Transaction available?
2. What is Serializability –lock based protocol?
3. What is Time based Protocol and Validation based Protocol?
4. Tell about Testing of Serializability and Precedence graph of Schedule

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 106
Fundamentals of Database Systems Department of ECE

TUTORIAL QUESTIONS
UNIT – I

1. Characteristics of DBMS, Advantages and Disadvantages?


2. Explain the difference between File Processing System Vs DBMS?
3. Tell about 3 –Schema Architecture?
4. Explain about DBMS Structure?
5. Who are Database Users and DBA?
6. What is Distributed Database?
7. What are the types of Languages in DBMS? Explain the Languages in Detail?
8. History of DBMS and Founders of DBMS?
UNIT – II
1. Construct an ER diagram? Specify the notations used to indicate
various components of ER diagram?
2. Identify the different types of relationships in ER modelling?
3. Representations of Various ER - Schemas?
4. Develop an E-R Diagram for a Hospital with a set of patients and
set of medical doctors. Associated with each patient a log of
various tests and examinations conducted?
5. Examples on Keys – Primary, Candidate and Super key?
6. Explain about the Entity Keys in DBMS?
7. What are the Operations in Relational Model?
8. What are the examples on Relational Model?

UNIT –III

1. Write 15 SQL Commands with Syntax?


2. Create a Student or Candidate Database Table
3. Write 10 Examples for SQL database operations?
4. What are the Different types of SET Operations with Examples?
5. What are the Relational Database Operations with Examples?
6. What are the SQL Joins with examples?
7. What are the Different Kinds of Keywords with Examples?
8. What are the Sub-Query Operations in DBMS

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 107
Fundamentals of Database Systems Department of ECE

UNIT –IV

1. What is Normalization and what are the types of Normalization?


2. Explain the difference between Good Schema and Bad Schema?
3. Define Normal Forms with examples?
4. What are the types of Functional Dependencies in DBMS
5. What is Foreign Key and explain with example?
6. What is Armstrong’s Axioms in Functional Dependency
7. What is a Key in SQL and tell what types we have in this?
8. What are key Terms in SQL?

UNIT –V

5. What are Transaction Properties?


6. What are the States of Transaction available?
7. What is Serializability Schedule?
8. Tell about Testing of Serializability and Precedence graph of Schedule
9. Explain about Conflict Serial Schedule?
10. Explain Transactions implementations in SQL?
11. What is Serializability –lock based protocol?
12. What is Time based Protocol and Validation based Protocol?

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 108
Fundamentals of Database Systems Department of ECE

Important Questions
UNIT – I
1. Explain DBMS? Explain Database system Applications.
2. Make a comparison between Database system and File system. ?
3. Explain storage manager component of Database System structure.?
4. Explain the Database users and user interfaces.
5. Explain levels of data abstraction.
6. List and explain the functions of data base administrator?
7. What are the types of languages a database?
8. Types of Databases?
9. Charactersitcs of DBMS and Advantages and Disadvantages?
10.Types of DBMS Architecture ?
11. Schema Level Architecture?
12. Functional Components of DBMS?

UNIT _II

1. What is an ER diagram? Specify the notations used to indicate various components of E R


2.How to specify different constraints in ER diagram with examples.
3. List the six design goals for relational database and explain why they are desirable.
4. A company database needs to store data about employees, departments andchildren of
employees. Draw an ER diagram that captures the above data.
5. Explain how to differentiate attributes in Entity set?
6. What is the composite Attribute? How to model it in the ER diagram? Explain
with anexample.
7. Compare candidate key, primary key and super key.
8. What are the E-R Diagram Notations?
9. Explain About Weak Entity and Strong Entity?
10. Tell about Various of Types of E R Schema Representation?

UNIT-III

1. Explain about SQL Commands with Syntax?


2. Create a Student or Candidate Database Table
3. Write Examples for SQL database operations?
4. What are the Different types of SET Operations with Examples?
5. What are the Relational Database Operations with Examples?
6. What are the SQL Joins with examples?
7. What are the Different Kinds of Keywords with Examples?
8. What are the Sub-Query Operations in DBMS

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 109
Fundamentals of Database Systems Department of ECE

UNIT –IV

1. What is Normalization and what are the types of Normalization?


2. What are the Problems Encountered in Good Schema
3. What are the Problems encountered in Bad Schema?
4. Define Normal Forms with examples?
5. What are the types of Functional Dependencies in DBMS
6. What is Foreign Key and explain with example?
7. What is Armstrong’s Axioms in Functional Dependency
8. What is a Key in SQL and tell what types we have in this?
9. What are key Terms in SQL?
10. What are Rules of Functional Dependences?

UNIT-V

1. What are Transaction Properties?


2. What are the States of Transaction available?
3. What is Serializability Schedule?
4. Tell about Testing of Serializability and Precedence graph of Schedule
5. Explain about Conflict Serial Schedule?
6. Explain Transactions implementations in SQL?
7. What is Serializability –lock based protocol
8. What is Time based Protocol?
9. What is Validation based Protocol
10. What is Two –Phase Protocol?
11. What are the Operations in Transactions?
12. What are Transaction Isolation levels in DBMS?

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 110
Fundamentals of Database Systems Department of ECE

Multiple Choice Questions


UNIT – I
1. Which of the following is generally used for performing tasks like creating the structure of
the relations, deleting relation?
a. DML(Data Manipulation Language)
b. Query
c. Relational Schema
d. DDL(Data Definition Language)

2. which of the following provides the ability to query information from the database and
insert tuples into, delete tuples from, and modify tuples in the database?
a. DML(Data Manipulation Language)
b. DDL(Data Definition Language)
c. Query
d. Relational Schema

3. The given Query can also be replaced with_______:


SELECT name, course_id
FROM instructor, teaches
WHERE instructor_ID= teaches_ID;
a. Select name,course_id from teaches,instructor where instructor_id=course_id;
b. Select name, course_id from instructor natural join teaches;
c. Select name, course_id from instructor;
d. Select course_id from instructor join teaches;

4. What do you mean by one to many relationships?


a. One class may have many teachers
b. One teacher can have many classes
c. Many classes may have many teachers
d. Many teachers may have many classes

5. A Database Management System is a type of _________software.


a. It is a type of system software
b. It is a kind of application software
c. It is a kind of general software
d. Both A and C

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 111
Fundamentals of Database Systems Department of ECE

6. A huge collection of the information or data accumulated form several different sources is
known as ________:
a. Data Management
b. Data Mining
c. Data Warehouse
d. Both B and C
7. Which one of the following refers to the "data about data"?
a. Directory
b. Sub Data
c. Warehouse
d. Meta Data
8. Which of the following refers to the level of data abstraction that describes exactly how the
data actually stored?
a. Conceptual Level
b. Physical Level
c. File Level
d. Logical Level

9. To which of the following the term "DBA" referred?

a. Data Bank Administrator


b. Database Administrator
c. Data Administrator
d. None of the above

10. In general, a file is basically a collection of all related______.

a. Rows & Columns


b. Fields
c. Database
d. Records

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 112
Fundamentals of Database Systems Department of ECE

UNIT –II

1. Rows of a relation are known as the _______.


a. Degree
b. Tuples
c. Entity
d. All of the above

2. In a relation database, every tuples divided into the fields are known as the______.
a. Queries
b. Domains
c. Relations
d. All of the above

3. In the relational table, which of the following can also be represented by the term
"attribute"?
a. Entity
b. Row
c. Column
d. Both B &C

4. Which of the following refers to the number of attributes in a relation?


a. Degree
b. Row
c. Column
d. All of the above

5. The term "DFD" stands for?


a. Data file diagram
b. Data flow document
c. Data flow diagram
d. None of the above

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 113
Fundamentals of Database Systems Department of ECE

6. Which of the following keys is generally used to represents the relationships between the
tables?
a. Primary key
b. Foreign key
c. Secondary key
d. None of the above

7. Which one of the following keyword is used to find out the number of values in a column?

a. TOTAL
b. COUNT
c. SUM
d. ADD

8. Which one of the following commands is used to modify a column inside a table?

a. Drop
b. Update
c. Alter
d. Set

9.E R Model uses which symbol to represent weak entity set :

a. Dotted rectangle
b.Diamond
C.Doubly Outlined rectangle
d.None

10.E –R Modeling technique is a:


a. Top-Down approach
b.Bottom –Up approach
C.Left-right Approach
d.None

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 114
Fundamentals of Database Systems Department of ECE

UNIT _III

1. Which one of the following commands is used for removing (or deleting) a relation forms the
SQL database?
a. Delete
b. Drop
c. Remove
d. All of the above
2.What is the Language used by most of the DBMS for helping their users to access data ?
a.High level Language
b.Query Language
C.SQL
D.None
3.A Command that lets you change one or more fields in a record ?
a.Insert
b.Modify
c.Look-up
d.None
4.This is the Authorization command of SQL :
a.Access
b.Grant
C.Allow
d.None
5.Grant is a Command from SQL type :
a.DDL
b.DCL
c.DML
d.None
6.Which of the following is an aggregate function is SQL ?
a.Union
b.Like
c.Group
d.Min

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 115
Fundamentals of Database Systems Department of ECE

7.Which of the following is an authorization command of SQL


a. Access
b. Secondary key
c. Foreign Key
d. None

8. Which of the following is an aggregate SQL function returns no of rows?


a.Avg
b.Min
C.Count
d.Sum

9. Which of the following is not a DDL command?


a. TRUNCATE
b. ALTER
c. CREATE
d. UPDATE

10. SQL Views are also known as

a. Simple tables
b. Virtual tables
c. Complex tables
d. Actual Tables

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 116
Fundamentals of Database Systems Department of ECE

UNIT-IV
1. In the __________ normal form, a composite attribute is converted to individual attributes.
a) First
b) Second
c) Third
d) Fourth
2. A table on the many side of a one to many or many to many relationship must:
a) Be in Second Normal Form (2NF)
b) Be in Third Normal Form (3NF)
c) Have a single attribute key
d) Have a composite key
3. Functional Dependencies are the types of constraints that are based on______
a) Key
b) Key revisited
c) Superset key
d) None of the mentioned
4. Which forms has a relation that possesses data about an individual entity:
a) 2NF
b) 3NF
c) 4NF
d) 5NF
5. Which forms are based on the concept of functional dependency:
a) 1NF
b) 2NF
c) 3NF
d) 4NF
6. We can use the following three rules to find logically implied functional dependencies. This
collection of rules is called
a) Axioms
b) Armstrong’s axioms
c) Armstrong
d) Closure

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 117
Fundamentals of Database Systems Department of ECE

7. Which of the following is not Armstrong’s Axiom?


a) Reflexivity rule
b) Transitivity rule
c) Pseudotransitivity rule
d) Augmentation rule
8. What are the desirable properties of a decomposition
a) Partition constraint
b) Dependency preservation
c) Redundancy
d) Security
9.What is the best way to represent the attributes in a large database?
a) Relational-and
b) Concatenation
c) Dot representation
d) All of the mentioned
10. The Types of template Dependencies are
a. Constraint generating templates
b. Tuple Generating templates
c. Schema generating templates
d. none

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 118
Fundamentals of Database Systems Department of ECE

UNIT-V
1. Collections of operations that form a single logical unit of work are called __________
a) Views
b) Networks
c) Units
d) Transactions

2. Which of the following is a property of transactions?


a) Atomicity
b) Durability
c) Isolation
d) All of the mentioned

3. Which of the following is not a property of a transaction?


a) Atomicity
b) Simplicity
c) Isolation
d) Durability

4. Which of the following systems is responsible for ensuring isolation?


a) Recovery system
b) Atomic system
c) Concurrency control system
d) Compiler system
5. Which of the following is not a transaction state?
a) Active
b) Partially committed
c) Failed
d) Compensated

5.Consider the following schedule for transactions T1, T2 and T3:

1. T1 ->>T3->>T2
2. T2->>T1->>T3
3. T2->>T3->>T1
4. T3->>T1—T2

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 119
Fundamentals of Database Systems Department of ECE

6. Which of the following is the most expensive method?


a) Timestamping
b) Plain locking
c) Predicate locking
d) Snapshot isolation

7. The set of ________ in a precedence graph consists of all the transactions participating in
the schedule
a) Vertices
b) Edges
c) Directions
d) None of the mentioned

8. The average time for a transaction to be completed after it has been submitted is called as
__________
a) Minimum response time
b) Average response time
c) Average reaction time
d) Minimum reaction time

9. When is a timestamp allotted


a) When execution begins
b) When execution is taking place
c) When execution is completed
d) None of the mentioned

10. What is the disadvantage of locking?


a) Does not control concurrency
b) Is not atomic
c) Is not durable
d) Has a poor degree of concurrency

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 120
Fundamentals of Database Systems Department of ECE

Code No: 134AP R-16


JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY HYDERABAD
B.Tech II Year II Semester Examinations, May - 2019
DATABASE MANAGEMENT SYSTEMS
(Common to CSE, IT)
Short Answers

1. What is DBMS? What are the advantages of DBMS ?


2. Explain generalization, specialization and aggregation in E -R Model .
3. Define the terms primary key constrains and foreign key and check constraints.
4. Explain the following Operators in SQL with examples: i) SOME ii) NOT IN .
5. What is normalization? What are the conditions required for a relation to be in 1NF,
2NF ?
6. Explain what are the problems caused by redundancy .
7. What is locking Protocol?
8. Explain the ACID Properties of transaction with examples .
9. What is Indexing and Hashing?
10. Explain what are the differences between tree based and Hash based indexes .

Long Answers:

1. Develop an E -R Diagram for Banking enterprise system .


2. Explain the functions of Database Administrator
3. Compare between super key, Candidate key, Primary Key for a relation with examples.
4. Construct an ER -Diagram for a hospital with a set of patients and set of medical doctors.
Associated with each patient a log of the various tests and examinations conducted
5.Explain the fundamental operations in relational algebra with examples .
6. Explain various Domain constraints in SQL with examples .
7.When is a decomposition said to be dependency preserving? Why this property Useful?
8. Determine the closer of the following set of functional dependencies for a relation scheme.
R(A,B,C,D,E,F,G,H),
F={ AB ->C, BD ->EF, AD ->G,A ->H}
List the candidate keys of R .
9.Explain the Time Stamp - Based Concurrency Control protocol . How is it used to ensure
serializability?
10. Explain the Check point log based recovery scheme for recovering the data base .
11.Explain multiple granularity of locking protocol with example .
12. What is serializability? Explain
13. Explain about Validation -Based Protocol .

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 121
Fundamentals of Database Systems Department of ECE

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 122
Fundamentals of Database Systems Department of ECE

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 123
Fundamentals of Database Systems Department of ECE

References:

TEXT BOOK:

1. Abraham Silberschatz, Henry F. Korth, S. Sudarshan,” Database System


Concepts”, McGraw-Hill, 6th Edition , 2010.

2. Fundamental of Database Systems, by Elmasri, Navathe, Somayajulu, and


Gupta, Pearson Education.

REFERENCES:

1. Raghu Ramakrishnan, Johannes Gehrke, “Database Management System”, McGraw


Hill., 3rd Edition 2007.

2. Elmasri&Navathe,”Fundamentals of Database System,” Addison-Wesley Publishing,


5th Edition, 2008.

3. Date.C.J, “An Introduction to Database”, Addison-Wesley Pub Co, 8th Edition, 2006.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN(UGC –AUTONOMOUS –INSTITUTION)


Page | 124

You might also like