0% found this document useful (0 votes)
31 views

Rdbms Notes

The document provides comprehensive notes on Relational Database Management Systems (RDBMS) covering various units including DBMS introduction, relational models, database design, SQL commands, and PL/SQL structures. It discusses the objectives, advantages, components, and architecture of DBMS, along with detailed explanations of data, information, and the ER model. Additionally, it includes references to textbooks and online courses for further learning.

Uploaded by

rojamani ganta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Rdbms Notes

The document provides comprehensive notes on Relational Database Management Systems (RDBMS) covering various units including DBMS introduction, relational models, database design, SQL commands, and PL/SQL structures. It discusses the objectives, advantages, components, and architecture of DBMS, along with detailed explanations of data, information, and the ER model. Additionally, it includes references to textbooks and online courses for further learning.

Uploaded by

rojamani ganta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 193

lOMoARcPSD|51615745

Rdbms Notes

BCA (University of Madras)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Ganta Rojamani ([email protected])
lOMoARcPSD|51615745

RELATIONAL DATABASE MANAGEMENT SYSTEM

UNIT - I
Introduction to DBMS – Data and Information - Database – Database Management
System – Objectives - Advantages – Components - Architecture. ER Model: Building
blocks of ER Diagram – Relationship Degree – Classification – ER diagram to Tables –
ISA relationship – Constraints – Aggregation and Composition – Advantages
.
UNIT - II
Relational Model: CODD’s Rule- Relational Data Model - Key - Integrity – Relational
Algebra Operations – Advantages and limitations – Relational Calculus – Domain
Relational Calculus - QBE.

UNIT - III
Structure of Relational Database. Introduction to Relational Database Design -
Objectives – Tools – Redundancy and Data Anomaly – Functional Dependency -
Normalization – 1NF – 2NF – 3NF – BCNF. Transaction Processing – Database
Security.

UNIT - IV
SQL: Commands – Data types – DDL - Selection, Projection, Join and Set Operations –
Aggregate Functions – DML – Modification - Truncation - Constraints – Sub query.

UNIT - V
PL/SQL: Structure - Elements – Operators Precedence – Control Structure – Iterative
Control - Cursors - Procedure - Function - Packages – Exceptional Handling - Triggers.

TEXT BOOK:
1. S. Sumathi, S. Esakkirajan, “Fundamentals of Relational Database Management
System”, Springer International Edition 2007.

REFERENCE BOOKS:
1. Abraham Silberchatz, Henry F. Korth, S. Sudarshan, “Database System Concepts”,
McGrawHill 2019, 7th Edition.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

2. Alexis Leon & Mathews Leon, “Fundamentals of DBMS”, Vijay Nicole Publications
2014, 2nd Edition.

WEB REFERENCES:
NPTEL & MOOC courses titled Relational Database Management Systems
https://nptel.ac.in/courses/106106093/
https://nptel.ac.in/courses/106106095/

UNIT - I
Introduction to DBMS:

Database management system is a software which is used to manage the


database. It is collection of inter-related data and set of programs to store &
access those data in an easy and effective manner.

For example: MySQL, Oracle, etc are a very popular commercial database which
is used in different applications.

DBMS provides an interface to perform various operations like database


creation, storing data in it, updating data, creating a table in the database and a
lot more.

o It provides also protection and security to the database. In the case of


multiple users, it also maintains data consistency.

Data:

o Data is a raw and unorganized fact that required to be processed to make


it meaningful. Data can be simple at the same time unorganized unless it
is organized. Generally, data comprises facts, observations, perceptions
numbers, characters, symbols, image, etc.

Information:

o Information is a set of data which is processed in a meaningful way


according to the given requirement.
o Information assigns meaning and improves the reliability of the data.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Database:

The database is a collection of inter-related data which is used to retrieve, insert


and delete the data efficiently. It is also used to organize the data in the form of
a table, schema, views, and reports, etc.
For example: The college Database organizes the data about the admin, staff,
students and faculty etc.
Using the database, we can easily retrieve, insert, and delete the information.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Database systems are basically developed for large amount of data. When
dealing with huge amount of data, there are two things that require
optimization: Storage of data and retrieval of data.

Storage: According to the principles of database systems, the data is stored in


such a way that it acquires lot less space as the redundant data (duplicate
data) has been removed before storage.

Fast Retrieval of data: Along with storing the data in an optimized and
systematic manner, it is also important that we retrieve the data quickly when
needed. Database systems ensure that the data is retrieved as quickly as
possible

Objective of DBMS:

DBMS applications must be capable of solving challenging problems of different


organizations. some objectives of DBMS are given below

• Provide for mass storage of relevant data


• Making easy access to data for the authorized user.
• Providing prompt response to users’ requests for data.
• Eliminate redundantly (Duplicate) data.
• Allow multiple users to be active at one time.
• Allow the growth of the database system
• Provide data integrity.
• Protect the data from physical harm and unauthorized access.
• Serving different types of users.
• Provide security with a user access privilege.
• Combining interrelated data to generate a report
• Provide multiple views for the same data.

Advantages of DBMS:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Reduction of redundancies:

Centralized control of data by the DBA avoids unnecessary duplication of data


and effectively reduces the total amount of data storage required avoiding
duplication in the elimination of the inconsistencies that tend to be present in
redundant data files.

Sharing of Data:

A database allows the sharing of data under its control by any number of
application programs or users.

Data Integrity:

Data integrity means that the data contained in the database is both accurate
and consistent. Therefore data values being entered for storage could be
checked to ensure that they fall within a specified range and are of the correct
format.

Data Security:

The DBA who has the ultimate responsibility for the data in the dbms can
ensure that proper access procedures are followed including proper
authentication to access to the Data Base System and additional check before
permitting access to sensitive data.

Conflict Resolution:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

DBA resolve the conflict on requirements of various user and applications. The
DBA chooses the best file structure and access method to get optional
performance for the application.

Data Independence:

Data independence is usually considered from two points of views; physically


data independence and logical data independence.

Physical Data Independence allows changes in the physical storage devices or


organization of the files to be made without requiring changes in the conceptual
view or any of the external views and hence in the application programs using
the data base.

Logical Data Independence indicates that the conceptual schema can be


changed without affecting the existing external schema or any application
program.

Components of DBMS:
The database system consists of many components. Each component
performs very significant tasks in the database management system
environment. A database environment is a collective system of components
that comprise and regulates the group of data, management, and use of data,
which consist of software, hardware, people, techniques of handling
database, and the data also.

DBMS comes with various integrated components and tools necessary to


carry out almost all database management tasks. The common
components that are universal across all DBMS software, including:

Storage engine

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Query language

Query processor

Optimization engine

Metadata catalog

Log manager

Reporting and monitoring tools

Data utilities

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Storage engine

The storage engine is the core component of the DBMS that interacts with the
file system at an OS level to store data. All SQL queries which interact with the
underlying data go through the storage engine.

Query language

A database access language is required for interacting with a database, from


creating databases to simply inserting or retrieving data. A proper DBMS must
support one or multiple query languages and language dialects. Structured
query language (SQL) and MongoDB Query Language (MQL) are two query
languages that are used to interact with the databases.

In many query languages, the query language functionality can be further


categorized according to specific tasks:

• Data Definition Language (DDL). This consists of commands that can be


used to define database schemas or modify the structure of database
objects.
• Data Manipulation Language (DML). Commands that directly deal with
the data in the database. All CRUD operations come under DML.
• Data Control Language (DCL). This deals with the permissions and other
access controls of the database.
• Transaction Control Language (TCL). Command which deals with
internal database transactions.

Query processor
This is the intermediary between the user queries and the database. The query
processor interprets the queries of users and makes them actionable

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

commands that can be understood by the database to perform the appropriate


functionality.

Optimization engine

The optimization Engine allows the DBMS to provide insights into the
performance of the database in terms of optimizing the database itself and
queries. When coupled with database monitoring tools, it can provide a
powerful toolset to gain the best performance out of the database.

Metadata catalog
This is the centralized catalog of all the objects within the database. When an
object is created, the DBMS keeps a record of that object with some metadata
about it using the metadata catalog. Then, this record can be used to:

• Verify user requests to the appropriate database objects


• Provide an overview of the complete database structure

Log manager
This component will keep all the logs of the DBMS. These logs will consist of
user logins and activity, database functions, backups and restore functions, etc.
The log manager ensures all these logs are properly recorded and easily
accessible.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Reporting & monitoring tools


Reporting and monitoring tools are another standard component that comes
with a DBMS. Reporting tools will enable users to generate reports while
monitoring tools enable monitoring the databases for resource consumption,
user activity, etc.

Data utilities
In addition to all the above, most DBMS software comes with additional inbuilt
utilities to provide functionality such as:

• Data integrity checks


• Backup and restore
• Simple database repair
• Data validations
• Etc.

Architecture of DBMS:

o The DBMS design depends upon its architecture. The basic client/server
architecture is used to deal with a large number of PCs, web servers,
database servers and other components that are connected with
networks.
o The client/server architecture consists of many PCs and a workstation
which are connected via the network.
o DBMS architecture depends upon how users are connected to the
database to get their request done.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Types of DBMS Architecture:

Database architecture can be seen as a single tier or multi-tier. But logically,


database architecture is of two types like: 2-tier architecture and 3-tier
architecture.

1-Tier Architecture

o In this architecture, the database is directly available to the user. It means


the user can directly sit on the DBMS and uses it.
o Any changes done here will directly be done on the database itself. It
doesn't provide a handy tool for end users.
o The 1-Tier architecture is used for development of the local application,
where programmers can directly communicate with the database for the
quick response.

2-Tier Architecture

o The 2-Tier architecture is same as basic client-server. In the two-tier


architecture, applications on the client end can directly communicate

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

with the database at the server side. For this interaction, API's
like: ODBC, JDBC are used.
o The user interfaces and application programs are run on the client-side.
o The server side is responsible to provide the functionalities like: query
processing and transaction management.
o To communicate with the DBMS, client-side application establishes a
connection with the server side.

Fig: 2-tier Architecture

3-Tier Architecture

o The 3-Tier architecture contains another layer between the client and
server. In this architecture, client can't directly communicate with the
server.
o The application on the client-end interacts with an application server
which further communicates with the database system.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

o End user has no idea about the existence of the database beyond the
application server. The database also has no idea about any other user
beyond the application.
o The 3-Tier architecture is used in case of large web application.

Fig: 3-tier Architecture

DBMS 3-tier Architecture

DBMS 3-tier architecture divides the complete system into three inter-related
but independent modules as shown below

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

1. Physical Level: At the physical level, the information about the location of
database objects in the data store is kept. Various users of DBMS are unaware
of the locations of these objects.
2.Conceptual Level: At conceptual level, data is represented in the form of
various database tables. For Example, STUDENT database may contain
STUDENT and COURSE tables which will be visible to users but users are
unaware of their storage.
3.External Level: An external level specifies a view of the data in terms of
conceptual level tables. Each external level view is used to cater to the needs of
a particular category of users. For Example, FACULTY of a university is
interested in looking course details of students, STUDENTS are interested in
looking at all details related to academics, accounts, courses and hostel details
as well. So, different views can be generated for different users.
Data Independence
Data independence means a change of data at one level should not affect
another level. Two types of data independence are present in this architecture:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

1. Physical Data Independence: Any change in the physical location of


tables and indexes should not affect the conceptual level or external view
of data. This data independence is easy to achieve and implemented by
most of the DBMS.
2. Conceptual Data Independence: The data at conceptual level schema
and external level schema must be independent. This means a change in
conceptual schema should not affect external schema. e.g.; Adding or
deleting attributes of a table should not affect the user’s view of the table.
But this type of independence is difficult to achieve as compared to
physical data independence because the changes in conceptual schema
are reflected in the user’s view.

ER model
o ER model stands for an Entity-Relationship model. It is a high-level data
model. This model is used to define the data elements and relationship
for a specified system.
o It develops a conceptual design for the database. It also develops a very
simple and easy to design view of data.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

o In ER modeling, the database structure is portrayed as a diagram called


an entity-relationship diagram.

For example, Suppose we design a school database. In this database, the


student will be an entity with attributes like address, name, id, age, etc. The
address can be another entity with attributes like city, street name, pin code,
etc and there will be a relationship between them.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Component of ER Diagram (Building Blocks)

1. Entity:

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

Consider an organization as an example- manager, product, employee,


department etc. can be taken as an entity.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

a. Weak Entity

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

2. Attribute

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


represent an attribute.

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

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

a. Key Attribute

The key attribute is used to represent the main characteristics of an entity. It


represents a primary key. The key attribute is represented by an ellipse with
the text underlined.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

b. Composite Attribute

An attribute that composed of many other attributes is known as a composite


attribute. The composite attribute is represented by an ellipse, and those
ellipses are connected with an ellipse.

c. Multivalued Attribute

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

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

d. Derived Attribute

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

An attribute that can be derived from other attribute is known as a derived


attribute. It can be represented by a dashed ellipse.

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

3. Relationship

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


rhombus is used to represent the relationship.

Types of relationship are as follows:

a. One-to-One Relationship

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

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

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

b. One-to-many relationship

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

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

c. Many-to-one relationship

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

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

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

d. Many-to-many relationship

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

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

Notation of ER diagram

Database can be represented using the notations. In ER diagram, many


notations are used to express the cardinality. These notations are as follows:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Mapping Constraints
o A mapping constraint is a data constraint that expresses the number of
entities to which another entity can be related via a relationship set.
o It is most useful in describing the relationship sets that involve more than
two entity sets.
o For binary relationship set R on an entity set A and B, there are four possible
mapping cardinalities. These are as follows:
1. One to one (1:1)
2. One to many (1:M)
3. Many to one (M:1)
4. Many to many (M:M)

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

One-to-one
In one-to-one mapping, an entity in E1 is associated with at most one entity in E2,
and an entity in E2 is associated with at most one entity in E1.

One-to-many
In one-to-many mapping, an entity in E1 is associated with any number of entities
in E2, and an entity in E2 is associated with at most one entity in E1.

Many-to-one
In one-to-many mapping, an entity in E1 is associated with at most one entity in
E2, and an entity in E2 is associated with any number of entities in E1.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Many-to-many
In many-to-many mapping, an entity in E1 is associated with any number of
entities in E2, and an entity in E2 is associated with any number of entities in E1.

Reduction of ER diagram to Table


The database can be represented using the notations, and these notations can be
reduced to a collection of tables.

In the database, every entity set or relationship set can be represented in tabular
form.

The ER diagram is given below:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

There are some points for converting the ER diagram to the table:

o Entity type becomes a table.

In the given ER diagram, LECTURE, STUDENT, SUBJECT and COURSE forms


individual tables.

o All single-valued attribute becomes a column for the table.

In the STUDENT entity, STUDENT_NAME and STUDENT_ID form the column of


STUDENT table. Similarly, COURSE_NAME and COURSE_ID form the column of
COURSE table and so on.

o A key attribute of the entity type represented by the primary key.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

In the given ER diagram, COURSE_ID, STUDENT_ID, SUBJECT_ID, and LECTURE_ID


are the key attribute of the entity.

o The multivalued attribute is represented by a separate table.

In the student table, a hobby is a multivalued attribute. So it is not possible to


represent multiple values in a single column of STUDENT table. Hence we create a
table STUD_HOBBY with column name STUDENT_ID and HOBBY. Using both the
column, we create a composite key.

o Composite attribute represented by components.

In the given ER diagram, student address is a composite attribute. It contains CITY,


PIN, DOOR#, STREET, and STATE. In the STUDENT table, these attributes can
merge as an individual column.

o Derived attributes are not considered in the table.

In the STUDENT table, Age is the derived attribute. It can be calculated at any point
of time by calculating the difference between current date and Date of Birth.

Using these rules, you can convert the ER diagram to tables and columns and
assign the mapping between the tables. Table structure for the given ER diagram
is as below:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Figure: Table structure

Integrity Constraints
o Integrity constraints are a set of rules. It is used to maintain the quality of
information.
o Integrity constraints ensure that the data insertion, updating, and other
processes have to be performed in such a way that data integrity is not
affected.
o Thus, integrity constraint is used to guard against accidental damage to the
database.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Types of Integrity Constraint

1. Domain constraints

o Domain constraints can be defined as the definition of a valid set of values


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

Example:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

2. Entity integrity constraints

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

Example:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

3. Referential Integrity Constraints

o A referential integrity constraint is specified between two tables.


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

Example:

4. Key constraints

o Keys are the entity set that is used to identify an entity within its entity set
uniquely.
o An entity set can have multiple keys, but out of which one key will be the
primary key. A primary key can contain a unique and null value in the
relational table.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Example:

Keys
o Keys play an important role in the relational database.
o It is used to uniquely identify any record or row of data from the table. It is also used to
establish and identify relationships between tables.

For example, ID is used as a key in the Student table because it is unique for each student.
In the PERSON table, passport_number, license_number, SSN are keys since they are unique
for each person.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Types of keys:

1. Primary key

o It is the first key used to identify one and only one instance of an entity uniquely. An entity
can contain multiple keys, as we saw in the PERSON table. The key which is most suitable
from those lists becomes a primary key.
o In the EMPLOYEE table, ID can be the primary key since it is unique for each employee. In the
EMPLOYEE table, we can even select License_Number and Passport_Number as primary keys
since they are also unique.
o For each entity, the primary key selection is based on requirements and developers.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

2. Candidate key

o A candidate key is an attribute or set of attributes that can uniquely identify a tuple.
o Except for the primary key, the remaining attributes are considered a candidate key. The
candidate keys are as strong as the primary key.

For example: In the EMPLOYEE table, id is best suited for the primary key. The rest of the
attributes, like SSN, Passport_Number, License_Number, etc., are considered a candidate key.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

3. Super Key
Super key is an attribute set that can uniquely identify a tuple. A super key is a superset of a
candidate key.

For example: In the above EMPLOYEE table, for(EMPLOEE_ID, EMPLOYEE_NAME), the


name of two employees can be the same, but their EMPLYEE_ID can't be the same. Hence,
this combination can also be a key.

The super key would be EMPLOYEE-ID (EMPLOYEE_ID, EMPLOYEE-NAME), etc.

4. Foreign key

o Foreign keys are the column of the table used to point to the primary key of another table.
o Every employee works in a specific department in a company, and employee and department
are two different entities. So we can't store the department's information in the employee
table. That's why we link these two tables through the primary key of one table.
o We add the primary key of the DEPARTMENT table, Department_Id, as a new attribute in the
EMPLOYEE table.
o In the EMPLOYEE table, Department_Id is the foreign key, and both the tables are related.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

5. Alternate key
There may be one or more attributes or a combination of attributes that uniquely identify
each tuple in a relation. These attributes or combinations of the attributes are called the
candidate keys. One key is chosen as the primary key from these candidate keys, and the
remaining candidate key, if it exists, is termed the alternate key. In other words, the total
number of the alternate keys is the total number of candidate keys minus the primary key.
The alternate key may or may not exist. If there is only one candidate key in a relation, it does
not have an alternate key.

For example, employee relation has two attributes, Employee_Id and PAN_No, that act as
candidate keys. In this relation, Employee_Id is chosen as the primary key, so the other
candidate key, PAN_No, acts as the Alternate key.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

6. Composite key
Whenever a primary key consists of more than one attribute, it is known as a composite key.
This key is also known as Concatenated Key.

For example, in employee relations, we assume that an employee may be assigned multiple
roles, and an employee may work on multiple projects simultaneously. So the primary key
will be composed of all three attributes, namely Emp_ID, Emp_role, and Proj_ID in
combination. So these attributes act as a composite key since the primary key comprises
more than one attribute.

7. Artificial key

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

The key created using arbitrarily assigned data are known as artificial keys. These keys are
created when a primary key is large and complex and has no relationship with many other
relations. The data values of the artificial keys are usually numbered in a serial order.

For example, the primary key, which is composed of Emp_ID, Emp_role, and Proj_ID, is large
in employee relations. So it would be better to add a new virtual attribute to identify each
tuple in the relation uniquely.

Foreign Key
The use of a foreign key is simply to link the attributes of two tables together with
the help of a primary key attribute. Thus, it is used for creating and maintaining
the relationship between the two relations.

Example of Foreign Key


Let's discuss an example to understand the working of a foreign key.

Consider two tables Student and Department having their respective attributes
as shown in the below table structure:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

In the tables, one attribute, you can see, is common, that is Stud_Id, but it has
different key constraints for both tables. In the Student table, the field Stud_Id is
a primary key because it is uniquely identifying all other fields of the Student
table. On the other hand, Stud_Id is a foreign key attribute for the Department
table because it is acting as a primary key attribute for the Student table. It means
that both the Student and Department table are linked with one another because
of the Stud_Id attribute.

In the below-shown figure, you can view the following structure of the relationship
between the two tables.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Aggregation
In aggregation, the relation between two entities is treated as a single entity. In aggregation,
relationship with its corresponding entities is aggregated into a higher level entity.

For example: Center entity offers the Course entity act as a single entity in the relationship
which is in a relationship with another entity visitor. In the real world, if a visitor visits a
coaching center then he will never enquiry about the Course only or just about the Center
instead he will ask the enquiry about both.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Aggregation is a special type of Association. Aggregation is "*the*" relationship


among objects. We can say it is a direct association among the objects. In
Aggregation, the direction specifies which object contains the other object. There
are mutual dependencies among objects.

For example, departments and employees, a department has many employees


but a single employee is not associated with multiple departments.

UML Representation of Aggregation (white diamond):

The UML representation of the example above (relation between employee and
department):

Composition
Composition is special type of Aggregation. It is a strong type of Aggregation. In
this type of Aggregation the child object does not have their own life cycle. The
child object's life depends on the parent's life cycle. Only the parent object has an
independent life cycle. If we delete the parent object then the child object(s) will
also be deleted. We can define the Composition as a "Part of" relationship.

For example, the company and company location, a single company has multiple
locations. If we delete the company then all the company locations are
automatically deleted. The company location does not have their independent
life cycle, it depends on the company object's life (parent object).

UML Representation of Composition (black diamond):

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

UML representation of the example above (relation between Company and


Company Location):

Advantages of ER Model
Conceptually it is very simple: ER model is very simple because if we know relationship
between entities and attributes, then we can easily draw an ER diagram.

Better visual representation: ER model is a diagrammatic representation of any logical


structure of database. By seeing ER diagram, we can easily understand relationship among
entities and relationship.

Effective communication tool: It is an effective communication tool for database designer.

Highly integrated with relational model: ER model can be easily converted into relational
model by simply converting ER model into tables.

Easy conversion to any data model: ER model can be easily converted into another data model
like hierarchical data model, network data model and so on.

Disadvantages of ER Model
Limited constraints and specification

Loss of information content: Some information be lost or hidden in ER model

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Limited relationship representation: ER model represents limited relationship as compared


to another data models like relational model etc.

No representation of data manipulation: It is difficult to show data manipulation in ER model.

Popular for high level design: ER model is very popular for designing high level design

UNIT –II

Relational Model concept


Relational model can represent as a table with columns and rows. Each row is
known as a tuple. Each table of the column has a name or attribute.

Domain: It contains a set of atomic values that an attribute can take.

Attribute: It contains the name of a column in a particular table. Each attribute Ai


must have a domain, dom(Ai)

Relational instance: In the relational database system, the relational instance is


represented by a finite set of tuples. Relation instances do not have duplicate
tuples.

Relational schema: A relational schema contains the name of the relation and
name of all columns or attributes.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Relational key: In the relational key, each row has one or more attributes. It can
identify the row in the relation uniquely.

Example: STUDENT Relation

NAME ROLL_NO PHONE_NO ADDRESS AGE

Ram 14795 7305758992 Noida 24

Shyam 12839 9026288936 Delhi 35

Laxman 33289 8583287182 Gurugram 20

Mahesh 27857 7086819134 Ghaziabad 27

Ganesh 17282 9028 9i3988 Delhi 40

o In the given table, NAME, ROLL_NO, PHONE_NO, ADDRESS, and AGE are the
attributes.
o The instance of schema STUDENT has 5 tuples.
o t3 = <Laxman, 33289, 8583287182, Gurugram, 20>

Properties of Relations
o Name of the relation is distinct from all other relations.
o Each relation cell contains exactly one atomic (single) value
o Each attribute contains a distinct name
o Attribute domain has no significance
o tuple has no duplicate value
o Order of tuple can have a different sequence

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Constraints in Relational Model

While designing Relational Model, we define some conditions which must


hold for data present in database are called Constraints. These
constraints are checked before performing any operation (insertion,
deletion and updation) in database. If there is a violation in any of
constrains, operation will fail.
Domain Constraints: These are attribute level constraints. An attribute
can only take values which lie inside the domain range. e.g,; If a
constrains AGE>0 is applied on STUDENT relation, inserting negative
value of AGE will result in failure.
Key Integrity: Every relation in the database should have atleast one set
of attributes which defines a tuple uniquely. Those set of attributes is
called key. e.g.; ROLL_NO in STUDENT is a key. No two students can have
same roll number. So a key has two properties:
• It should be unique for all tuples.
• It can’t have NULL values.
Referential Integrity: When one attribute of a relation can only take
values from other attribute of same relation or any other relation, it is
called referential integrity. Let us suppose we have 2 relations

STUDENT
ROLL_N ADDRES AG BRANCH_COD
O NAME S PHONE E E

945512345
1 RAM DELHI 1 18 CS

RAMES GURGAO 965243154


2 H N 3 18 CS

915625313
3 SUJIT ROHTAK 1 20 ECE

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

BRANCH
BRANCH_CODE BRANCH_NAME

CS COMPUTER SCIENCE

IT INFORMATION TECHNOLOGY

ECE ELECTRONICS AND COMMUNICATION ENGINEERING

CV CIVIL ENGINEERING

BRANCH_CODE of STUDENT can only take the values which are present in
BRANCH_CODE of BRANCH which is called referential integrity constraint.
The relation which is referencing to other relation is called REFERENCING
RELATION (STUDENT in this case) and the relation to which other
relations refer is called REFERENCED RELATION (BRANCH in this case).

Codd's Rules
Every database has tables, and constraints cannot be referred to as a rational
database system. And if any database has only relational data model, it cannot
be a Relational Database System (RDBMS). So, some rules define a database
to be the correct RDBMS. These rules were developed by Dr. Edgar F. Codd
(E.F. Codd) in 1985, who has vast research knowledge on the Relational Model
of database Systems. Codd presents his 13 rules for a database to test the
concept of DBMS against his relational model, and if a database follows the rule,
it is called a true relational database (RDBMS). These 13 rules are popular in
RDBMS, known as Codd's 12 rules.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Rule 0: The Foundation Rule


The database must be in relational form. So that the system can handle the database through
its relational capabilities.

Rule 1: Information Rule


A database contains various information, and this information must be stored in each cell of
a table in the form of rows and columns.

Rule 2: Guaranteed Access Rule


Every single or precise data (atomic value) may be accessed logically from a relational
database using the combination of primary key value, table name, and column name.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Rule 3: Systematic Treatment of Null Values


This rule defines the systematic treatment of Null values in database records. The null value
has various meanings in the database, like missing the data, no value in a cell, inappropriate
information, unknown data and the primary key should not be null.

Rule 4: Active/Dynamic Online Catalog based on the relational model


It represents the entire logical structure of the descriptive database that must be stored
online and is known as a database dictionary. It authorizes users to access the database and
implement a similar query language to access the database.

Rule 5: Comprehensive Data SubLanguage Rule


The relational database supports various languages, and if we want to access the database,
the language must be the explicit, linear or well-defined syntax, character strings and
supports the comprehensive: data definition, view definition, data manipulation, integrity
constraints, and limit transaction management operations. If the database allows access to
the data without any language, it is considered a violation of the database.

Rule 6: View Updating Rule


All views table can be theoretically updated and must be practically updated by the database
systems.

Rule 7: Relational Level Operation (High-Level Insert, Update and


delete) Rule
A database system should follow high-level relational operations such as insert, update, and
delete in each level or a single row. It also supports union, intersection and minus operation
in the database system.

Rule 8: Physical Data Independence Rule


All stored data in a database or an application must be physically independent to access the
database. Each data should not depend on other data or an application. If data is updated or
the physical structure of the database is changed, it will not show any effect on external
applications that are accessing the data from the database.

Rule 9: Logical Data Independence Rule


It is similar to physical data independence. It means, if any changes occurred to the logical
level (table structures), it should not affect the user's view (application). For example,

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

suppose a table either split into two tables, or two table joins to create a single table, these
changes should not be impacted on the user view application.

Rule 10: Integrity Independence Rule


A database must maintain integrity independence when inserting data into table's cells using
the SQL query language. All entered values should not be changed or rely on any external
factor or application to maintain integrity. It is also helpful in making the database-
independent for each front-end application.

Rule 11: Distribution Independence Rule


The distribution independence rule represents a database that must work properly, even if
it is stored in different locations and used by different end-users. Suppose a user accesses
the database through an application; in that case, they should not be aware that another user
uses particular data, and the data they always get is only located on one site. The end users
can access the database, and these access data should be independent for every user to
perform the SQL queries.

Rule 12: Non Subversion Rule


The non-submersion rule defines RDBMS as a SQL language to store and manipulate the data
in the database. If a system has a low-level or separate language other than SQL to access the
database system, it should not subvert or bypass integrity to transform data.

Relational Algebra
Relational algebra is a procedural query language. It gives a step by step process
to obtain the result of the query. It uses operators to perform queries.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Types of Relational operation

1. Select Operation:

o The select operation selects tuples that satisfy a given predicate.


o It is denoted by sigma (σ).

1. Notation: σ p(r)

Where:

σ is used for selection prediction


r is used for relation
p is used as a propositional logic formula which may use connectors like: AND
OR and NOT. These relational can use as relational operators like =, ≠, ≥, <, >, ≤.

For example: LOAN Relation

BRANCH_NAME LOAN_NO AMOUNT

Downtown L-17 1000

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Redwood L-23 2000

Perryride L-15 1500

Downtown L-14 1500

Mianus L-13 500

Roundhill L-11 900

Perryride L-16 1300

Input:

1. σ BRANCH_NAME="perryride" (LOAN)

Output:

BRANCH_NAME LOAN_NO AMOUNT

Perryride L-15 1500

Perryride L-16 1300

2. Project Operation:

o This operation shows the list of those attributes that we wish to appear in
the result. Rest of the attributes are eliminated from the table.
o It is denoted by ∏.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

1. Notation: ∏ A1, A2, An (r)

Where

A1, A2, A3 is used as an attribute name of relation r.

Example: CUSTOMER RELATION

NAME STREET CITY

Jones Main Harrison

Smith North Rye

Hays Main Harrison

Curry North Rye

Johnson Alma Brooklyn

Brooks Senator Brooklyn

Input:

1. ∏ NAME, CITY (CUSTOMER)

Output:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

NAME CITY

Jones Harrison

Smith Rye

Hays Harrison

Curry Rye

Johnson Brooklyn

Brooks Brooklyn

3. Union Operation:

o Suppose there are two tuples R and S. The union operation contains all the
tuples that are either in R or S or both in R & S.
o It eliminates the duplicate tuples. It is denoted by ∪.

1. Notation: R ∪ S

A union operation must hold the following condition:

o R and S must have the attribute of the same number.


o Duplicate tuples are eliminated automatically.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Example:
DEPOSITOR RELATION

CUSTOMER_NAME ACCOUNT_NO

Johnson A-101

Smith A-121

Mayes A-321

Turner A-176

Johnson A-273

Jones A-472

Lindsay A-284

BORROW RELATION

CUSTOMER_NAME LOAN_NO

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Jones L-17

Smith L-23

Hayes L-15

Jackson L-14

Curry L-93

Smith L-11

Williams L-17

Input:

1. ∏ CUSTOMER_NAME (BORROW) ∪ ∏ CUSTOMER_NAME (DEPOSITOR)

Output:

CUSTOMER_NAME

Johnson

Smith

Hayes

Turner

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Jones

Lindsay

Jackson

Curry

Williams

Mayes

4. Set Intersection:

o Suppose there are two tuples R and S. The set intersection operation
contains all tuples that are in both R & S.
o It is denoted by intersection ∩.

1. Notation: R ∩ S

Example: Using the above DEPOSITOR table and BORROW table

Input:

1. ∏ CUSTOMER_NAME (BORROW) ∩ ∏ CUSTOMER_NAME (DEPOSITOR)

Output:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

CUSTOMER_NAME

Smith

Jones

5. Set Difference:

o Suppose there are two tuples R and S. The set intersection operation
contains all tuples that are in R but not in S.
o It is denoted by intersection minus (-).

1. Notation: R - S

Example: Using the above DEPOSITOR table and BORROW table

Input:

1. ∏ CUSTOMER_NAME (BORROW) - ∏ CUSTOMER_NAME (DEPOSITOR)

Output:

CUSTOMER_NAME

Jackson

Hayes

Willians

Curry

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

6. Cartesian product

o The Cartesian product is used to combine each row in one table with each
row in the other table. It is also known as a cross product.
o It is denoted by X.

1. Notation: E X D

Example:
EMPLOYEE

EMP_ID EMP_NAME EMP_DEPT

1 Smith A

2 Harry C

3 John B

DEPARTMENT

DEPT_NO DEPT_NAME

A Marketing

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

B Sales

C Legal

Input:

1. EMPLOYEE X DEPARTMENT

Output:

EMP_ID EMP_NAME EMP_DEPT DEPT_NO DEPT_NAME

1 Smith A A Marketing

1 Smith A B Sales

1 Smith A C Legal

2 Harry C A Marketing

2 Harry C B Sales

2 Harry C C Legal

3 John B A Marketing

3 John B B Sales

3 John B C Legal

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

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

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


STUDENT1.

1. ρ(STUDENT1, STUDENT)

Join Operations:
A Join operation combines related tuples from different relations, if and only if a
given join condition is satisfied. It is denoted by ⋈.

Example:
EMPLOYEE

EMP_CODE EMP_NAME

101 Stephan

102 Jack

103 Harry

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

EMP_CODE
EMP_CODE EMP_NAME
SALARY SALARY

101 101 Stephan 50000 50000

102 102 Jack 30000 30000

103 103 Harry 25000 25000

SALARY

1. Operation: (EMPLOYEE ⋈ SALARY)

Result:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Types of Join operations:

1. Natural Join:

o A natural join is the set of tuples of all combinations in R and S that are equal
on their common attribute names.
o It is denoted by ⋈.

Example: Let's use the above EMPLOYEE table and SALARY table:

Input:

1. ∏EMP_NAME, SALARY (EMPLOYEE ⋈ SALARY)

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Output:

EMP_NAME SALARY

Stephan 50000

Jack 30000

Harry 25000

2. Outer Join:
The outer join operation is an extension of the join operation. It is used to deal
with missing information.

Example:

EMPLOYEE

EMP_NAME STREET CITY

Ram Civil line Mumbai

Shyam Park street Kolkata

Ravi M.G. Street Delhi

Hari Nehru nagar Hyderabad

FACT_WORKERS

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

EMP_NAME BRANCH SALARY

Ram Infosys 10000

Shyam Wipro 20000

Kuber HCL 30000

Hari TCS 50000

Input:

1. (EMPLOYEE ⋈ FACT_WORKERS)

Output:

EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000

Shyam Park street Kolkata Wipro 20000

Hari Nehru nagar Hyderabad TCS 50000

An outer join is basically of three types:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

a. Left outer join


b. Right outer join
c. Full outer join

a. Left outer join:

o Left outer join contains the set of tuples of all combinations in R and S that
are equal on their common attribute names.
o In the left outer join, tuples in R have no matching tuples in S.
o It is denoted by ⟕.

Example: Using the above EMPLOYEE table and FACT_WORKERS table

Input:

1. EMPLOYEE ⟕ FACT_WORKERS

EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000

Shyam Park street Kolkata Wipro 20000

Hari Nehru street Hyderabad TCS 50000

Ravi M.G. Street Delhi NULL NULL

b. Right outer join:

o Right outer join contains the set of tuples of all combinations in R and S that
are equal on their common attribute names.
o In right outer join, tuples in S have no matching tuples in R.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

o It is denoted by ⟖.

Example: Using the above EMPLOYEE table and FACT_WORKERS Relation

Input:

1. EMPLOYEE ⟖ FACT_WORKERS

Output:

EMP_NAME BRANCH SALARY STREET CITY

Ram Infosys 10000 Civil line Mumbai

Shyam Wipro 20000 Park street Kolkata

Hari TCS 50000 Nehru street Hyderabad

Kuber HCL 30000 NULL NULL

c. Full outer join:

o Full outer join is like a left or right join except that it contains all rows from
both tables.
o In full outer join, tuples in R that have no matching tuples in S and tuples in
S that have no matching tuples in R in their common attribute name.
o It is denoted by ⟗.

Example: Using the above EMPLOYEE table and FACT_WORKERS table

Input:

1. EMPLOYEE ⟗ FACT_WORKERS

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Output:

EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000

Shyam Park street Kolkata Wipro 20000

Hari Nehru street Hyderabad TCS 50000

Ravi M.G. Street Delhi NULL NULL

Kuber NULL NULL HCL 30000

3. Equi join:
It is also known as an inner join. It is the most common join. It is based on matched
data as per the equality condition. The equi join uses the comparison operator(=).

Example:

CUSTOMER RELATION

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

PRODUCT_ID CITY

1 Delhi

2 Mumbai

3 Noida

CLASS_ID NAME

1 John

2 Harry

3 Jackson

PRODUCT

Input:

1. CUSTOMER ⋈ PRODUCT

Output:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

CLASS_ID NAME PRODUCT_ID CITY

1 John 1 Delhi

2 Harry 2 Mumbai

3 Harry 3 Noida

Relational Calculus
There is an alternate way of formulating queries known as Relational Calculus.
Relational calculus is a non-procedural query language. In the non-procedural
query language, the user is concerned with the details of how to obtain the end
results. The relational calculus tells what to do but never explains how to do. Most
commercial relational languages are based on aspects of relational calculus
including SQL-QBE and QUEL.

Relational Calculus
It is based on Predicate calculus, a name derived from branch of symbolic
language. A predicate is a truth-valued function with arguments. On substituting
values for the arguments, the function result in an expression called a proposition.
It can be either true or false. It is a tailored version of a subset of the Predicate
Calculus to communicate with the relational database.

Many of the calculus expressions involves the use of Quantifiers. There are
two types of quantifiers:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

o Universal Quantifiers: The universal quantifier denoted by ∀ is read as for


all which means that in a given set of tuples exactly all tuples satisfy a given
condition.
o Existential Quantifiers: The existential quantifier denoted by ∃ is read as
for all which means that in a given set of tuples there is at least one
occurrences whose value satisfy a given condition.

Before using the concept of quantifiers in formulas, we need to know the concept
of Free and Bound Variables.

A tuple variable t is bound if it is quantified which means that if it appears in any


occurrences a variable that is not bound is said to be free.

Free and bound variables may be compared with global and local variable of
programming languages.

Types of Relational calculus:

1. Tuple Relational Calculus (TRC)


It is a non-procedural query language which is based on finding a number of tuple
variables also known as range variable for which predicate holds true. It describes

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

the desired information without giving a specific procedure for obtaining that
information. The tuple relational calculus is specified to select the tuples in a
relation. In TRC, filtering variable uses the tuples of a relation. The result of the
relation can have one or more tuples.

Notation:

A Query in the tuple relational calculus is expressed as following notation

1. {T | P (T)} or {T | Condition (T)}

Where

T is the resulting tuples

P(T) is the condition used to fetch T.

For example:

1. { T.name | Author(T) AND T.article = 'database' }

Output: This query selects the tuples from the AUTHOR relation. It returns a tuple
with 'name' from Author who has written an article on 'database'.

TRC (tuple relation calculus) can be quantified. In TRC, we can use Existential (∃)
and Universal Quantifiers (∀).

For example:

1. { R| ∃T ∈ Authors(T.article='database' AND R.name=T.name)}

Output: This query will yield the same result as the previous one.

2. Domain Relational Calculus (DRC)


The second form of relation is known as Domain relational calculus. In domain
relational calculus, filtering variable uses the domain of attributes. Domain
relational calculus uses the same operators as tuple calculus. It uses logical
connectives ∧ (and), ∨ (or) and ┓ (not). It uses Existential (∃) and Universal
Quantifiers (∀) to bind the variable. The QBE or Query by example is a query
language related to domain relational calculus.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Notation:

1. { a1, a2, a3, ..., an | P (a1, a2, a3, ... ,an)}

Where

a1, a2 are attributes


P stands for formula built by inner attributes

For example:

1. {< article, page, subject > | ∈ javatpoint ∧ subject = 'database'}

Output: This query will yield the article, page, and subject from the relational
javatpoint, where the subject is a database.

Query By Example (QBE)


If we talk about normal queries we fire on the database they should be
correct and in a well-defined structure which means they should follow a
proper syntax if the syntax or query is wrong definitely we will get an error
and due to that our application or calculation definitely going to stop. So to
overcome this problem QBE was introduced. QBE stands for Query By
Example and it was developed in 1970 by Moshe Zloof at IBM.
It is a graphical query language where we get a user interface and then we
fill some required fields to get our proper result.
In SQL we will get an error if the query is not correct but in the case of QBE
if the query is wrong either we get a wrong answer or the query will not be
going to execute but we will never get any error.
Note-:
In QBE we don’t write complete queries like SQL or other database
languages it comes with some blank so we need to just fill that blanks and
we will get our required result.
Example
Consider the example where a table ‘SAC’ is present in the database with

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Name, Phone_Number, and Branch fields. And we want to get the name of
the SAC-Representative name who belongs to the MCA Branch. If we write
this query in SQL we have to write it like
SELECT NAME
FROM SAC
WHERE BRANCH = 'MCA'"

And definitely, we will get our correct result. But in the case of QBE, it may
be done as like there is a field present and we just need to fill it with “MCA”
and then click on the SEARCH button we will get our required result.
Points about QBE:

• Supported by most of the database programs.


• It is a Graphical Query Language.
• Created in parallel to SQL development.

UNIT – III

Structure of Relational Database

1. A relational database consists of a collection of tables, each having a


unique name.

A row in a table represents a relationship among a set of values.

Thus a table represents a collection of relationships.

2. There is a direct correspondence between the concept of a table and the


mathematical concept of a relation. A substantial theory has been
developed for relational databases.

Basic Structure

1. Figure 3.1 shows the deposit and customer tables for our banking example.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Figure 3.1: The deposit and customer relations.

o It has four attributes.


o For each attribute there is a permitted set of values, called
the domain of that attribute.
o E.g. the domain of bname is the set of all branch names.

2. Mathematicians define a relation to be a subset of a Cartesian product of a


list of domains. You can see the correspondence with our tables.

We will use the terms relation and tuple in place of table and row from
now on.

3. Some more formalities:

o let the tuple variable refer to a tuple of the relation .

o We say to denote that the tuple is in relation .

o Then [bname] = [1] = the value of on


the bname attribute.

o So [bname] = [1] = ``Downtown'',

o and [cname] = [3] = ``Johnson''.


4. We'll also require that the domains of all attributes be indivisible units.
o A domain is atomic if its elements are indivisible units.
o For example, the set of integers is an atomic domain.
o The set of all sets of integers is not.
o Why? Integers do not have subparts, but sets do - the integers
comprising them.
o We could consider integers non-atomic if we thought of them as
ordered lists of digits.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Database Scheme

1. We distinguish between a database scheme (logical design) and a database


instance (data in the database at a point in time).
2. A relation scheme is a list of attributes and their corresponding domains.
3. The text uses the following conventions:
o italics for all names
o lowercase names for relations and attributes
o names beginning with an uppercase for relation schemes

These notes will do the same.

For example, the relation scheme for the deposit relation:

o Deposit-scheme = (bname, account#, cname, balance)

We may state that deposit is a relation on scheme Deposit-scheme by


writing deposit(Deposit-scheme).

If we wish to specify domains, we can write:

o (bname: string, account#: integer, cname: string, balance: integer).

Note that customers are identified by name. In the real world, this would not be allowed, as
two or more customers might share the same name.

Figure 3.2 shows the E-R diagram for a banking enterprise.

Figure 3.2: E-R diagram for the banking enterprise

4. The relation schemes for the banking example used throughout the text are:
o Branch-scheme = (bname, assets, bcity)
o Customer-scheme = (cname, street, ccity)
o Deposit-scheme = (bname, account#, cname, balance)
o Borrow-scheme = (bname, loan#, cname, amount)

Note: some attributes appear in several relation schemes (e.g. bname, cname). This
is legal, and provides a way of relating tuples of distinct relations.

5. Why not put all attributes in one relation?

Suppose we use one large relation instead of customer and deposit:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

o Account-scheme = (bname, account#, cname, balance, street, ccity)


o If a customer has several accounts, we must duplicate her or his
address for each account.
o If a customer has an account but no current address, we cannot build
a tuple, as we have no values for the address.

Keys

1. The notions of superkey, candidate key and primary key all apply to the
relational model.
2. For example, in Branch-scheme,
o {bname} is a superkey.
o {bname, bcity} is a superkey.
o {bname, bcity} is not a candidate key, as the superkey {bname} is contained in
it.
o {bname} is a candidate key.
o {bcity} is not a superkey, as branches may be in the same city.
o We will use {bname} as our primary key.
3. The primary key for Customer-scheme is {cname}.

4. More formally, if we say that a subset of is a superkey for , we are

restricting consideration to relations in which no two distinct tuples have the

same values on all attributes in .

What is Redundancy in DBMS?

Redundancy in DBMS is the problem that arises when the database is not normalized. It is
the concept of storing multiple copies of the same data in different parts of the database.

Example for Redundancy in DBMS

Let's understand the concept of redundancy in DBMS with a simple student table.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

student_id student_name student_age dept_id dept_name dept_head

1 Tony Stark 18 100 Computer Science Steve Rogers

2 Thor Odinson 18 100 Computer Science Steve Rogers

In this student table, we have repeated the same department details, dept_id, dept_name,
and dept_head in every student record. This causes redundancy in the student table.

How does Data Redundancy Occur?

Data redundancy in DBMS may occur due to any of the below reasons.

1. The database is not normalized through DBMS normalization.


2. The same data is stored in multiple places by multiple systems causing redundancy
in data.
3. Mistake during database design causes the same data to be stored multiple times.

Problems Caused by Redundancy in Database

Redundancy in DMBS can cause several problems while performing operations on data
such as insert, delete, and update. Let's use the below student table to
understand insertion, updation, and deletion anomalies.

student_id student_name student_age dept_id dept_name dept_head

1 Tony Stark 18 100 Computer Science Steve Rogers

2 Thor Odinson 18 100 Computer Science Steve Rogers

3 Bruce Banner 18 101 Mechanical Natasha Romanoff

Insertion Anomaly

An insertion anomaly occurs when specific details cannot be inserted into the database
without the other details.

Example: Without knowing the department details, we cannot insert the student details in
the above table. The student details (student_id, student_name, and student_age) depends
on the department details (dept_id, dept_name, and dept_head).

Deletion Anomaly

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Deletion anomaly occurs when deleting specific details loses some unrelated information
from the database.

Example:- If we delete the student with student_id 3 from the above student table, we also
lose the department details with dept_id 101. Deleting student details result in losing
unrelated department details.

Updation Anomaly

Updation anomaly occurs when there is data inconsistency resulting from a partial data
update.

Example:- We wanted to update the dept_head to Peter Parker for dept_id 101; we need
to update it in all places. If the update didn't occur in all the places (partial update), it may
result in data inconsistency.

How To Avoid Redundancy in DBMS?

Redundancy in DBMS can be avoided by following the below approaches.

• Redundancy in DBMS can be avoided by normalizing the data through


database normalization.
• Redundancy can be avoided using Master Data. Master data is a single source of data
accessed by several applications and systems.
• Proper database architecture design can avoid data redundancy.

Advantages of Data Redundancy

• Data redundancy can help disaster recovery by backing up the data in a different
place.
• Data redundancy can help during malicious attacks. Data integrity can be verified if
we have multiple copies of the same data.

Disadvantages of Data Redundancy

• Data redundancy can cause an increase in storage space due to duplicate data which
may increase the cost of the data storage.
• Data redundancy increase the size of the database, which increases the complexity
of performing operations on the data.
• Data redundancy can cause inconsistency in data due to partial updates to the
database.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Types of Functional dependencies in


DBMS

A functional dependency is a constraint that specifies the relationship


between two sets of attributes where one set can accurately determine the
value of other sets. It is denoted as X → Y, where X is a set of attributes that
is capable of determining the value of Y. The attribute set on the left side of
the arrow, X is called Determinant, while on the right side, Y is called
the Dependent. Functional dependencies are used to mathematically
express relations among database entities and are very important to
understand advanced concepts in Relational Database System and
understanding problems in competitive exams like Gate.
Example:
roll_no name dept_name dept_building

42 abc CO A4

43 pqr IT A3

44 xyz CO A4

45 xyz IT A3

46 mno EC B2

47 jkl ME B2

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

From the above table we can conclude some valid functional


dependencies:
• roll_no → { name, dept_name, dept_building },→ Here, roll_no can
determine values of fields name, dept_name and dept_building, hence a
valid Functional dependency
• roll_no → dept_name , Since, roll_no can determine whole set of {name,
dept_name, dept_building}, it can determine its subset dept_name also.
• dept_name → dept_building , Dept_name can identify the dept_building
accurately, since departments with different dept_name will also have a
different dept_building
• More valid functional dependencies: roll_no → name, {roll_no, name} ⇢
{dept_name, dept_building}, etc.
Here are some invalid functional dependencies:
• name → dept_name Students with the same name can have different
dept_name, hence this is not a valid functional dependency.
• dept_building → dept_name There can be multiple departments in the
same building, For example, in the above table departments ME and EC
are in the same building B2, hence dept_building → dept_name is an
invalid functional dependency.
• More invalid functional dependencies: name → roll_no, {name,
dept_name} → roll_no, dept_building → roll_no, etc.
Armstrong’s axioms/properties of functional dependencies:
1. Reflexivity: If Y is a subset of X, then X→Y holds by reflexivity rule
For example, {roll_no, name} → name is valid.
2. Augmentation: If X → Y is a valid dependency, then XZ → YZ is also
valid by the augmentation rule.
For example, If {roll_no, name} → dept_building is valid, hence {roll_no,
name, dept_name} → {dept_building, dept_name} is also valid.→
3. Transitivity: If X → Y and Y → Z are both valid dependencies, then X→Z
is also valid by the Transitivity rule.
For example, roll_no → dept_name & dept_name → dept_building, then
roll_no → dept_building is also valid.
Types of Functional dependencies in DBMS:
1. Trivial functional dependency
2. Non-Trivial functional dependency
3. Multivalued functional dependency
4. Transitive functional dependency

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

1. Trivial Functional Dependency


In Trivial Functional Dependency, a dependent is always a subset of the
determinant.
i.e. If X → Y and Y is the subset of X, then it is called trivial functional
dependency
For example,
roll_no name age

42 abc 17

43 pqr 18

44 xyz 18

Here, {roll_no, name} → name is a trivial functional dependency, since the


dependent name is a subset of determinant set {roll_no, name}
Similarly, roll_no → roll_no is also an example of trivial functional
dependency.
2. Non-trivial Functional Dependency
In Non-trivial functional dependency, the dependent is strictly not a
subset of the determinant.
i.e. If X → Y and Y is not a subset of X, then it is called Non-trivial
functional dependency.
For example,
roll_no name age

42 abc 17

43 pqr 18

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

roll_no name age

44 xyz 18

Here, roll_no → name is a non-trivial functional dependency, since the


dependent name is not a subset of determinant roll_no
Similarly, {roll_no, name} → age is also a non-trivial functional
dependency, since age is not a subset of {roll_no, name}
3. Multivalued Functional Dependency
In Multivalued functional dependency, entities of the dependent set
are not dependent on each other.
i.e. If a → {b, c} and there exists no functional dependency between b and
c, then it is called a multivalued functional dependency.
For example,
roll_no name age

42 abc 17

43 pqr 18

44 xyz 18

45 abc 19

Here, roll_no → {name, age} is a multivalued functional dependency, since


the dependents name & age are not dependent on each other(i.e. name →
age or age → name doesn’t exist !)
4. Transitive Functional Dependency
In transitive functional dependency, dependent is indirectly dependent on
determinant.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

i.e. If a → b & b → c, then according to axiom of transitivity, a → c. This is


a transitive functional dependency
For example,
enrol_no name dept building_no

42 abc CO 4

43 pqr EC 2

44 xyz IT 1

45 abc EC 2

Here, enrol_no → dept and dept → building_no,


Hence, according to the axiom of transitivity, enrol_no → building_no is a
valid functional dependency. This is an indirect functional dependency,
hence called Transitive functional dependency.

Normalization
A large database defined as a single relation may result in data duplication. This
repetition of data may result in:

o Making relations very large.


o It isn't easy to maintain and update data as it would involve searching many
records in relation.
o Wastage and poor utilization of disk space and resources.
o The likelihood of errors and inconsistencies increases.

So to handle these problems, we should analyze and decompose the relations with
redundant data into smaller, simpler, and well-structured relations that are satisfy

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

desirable properties. Normalization is a process of decomposing the relations into


relations with fewer attributes.

What is Normalization?
o Normalization is the process of organizing the data in the database.
o Normalization is used to minimize the redundancy from a relation or set of
relations. It is also used to eliminate undesirable characteristics like
Insertion, Update, and Deletion Anomalies.
o Normalization divides the larger table into smaller and links them using
relationships.
o The normal form is used to reduce redundancy from the database table.

Why do we need Normalization?

The main reason for normalizing the relations is removing these anomalies.
Failure to eliminate anomalies leads to data redundancy and can cause data
integrity and other problems as the database grows. Normalization consists of a
series of guidelines that helps to guide you in creating a good database structure.

Data modification anomalies can be categorized into three types:

o Insertion Anomaly: Insertion Anomaly refers to when one cannot insert a


new tuple into a relationship due to lack of data.
o Deletion Anomaly: The delete anomaly refers to the situation where the
deletion of data results in the unintended loss of some other important data.
o Updatation Anomaly: The update anomaly is when an update of a single
data value requires multiple rows of data to be updated.

Types of Normal Forms:


Normalization works through a series of stages called Normal forms. The normal
forms apply to individual relations. The relation is said to be in particular normal
form if it satisfies constraints.

Following are the various types of Normal forms:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Normal Description
Form

1NF A relation is in 1NF if it contains an atomic value.

2NF A relation will be in 2NF if it is in 1NF and all non-key attributes are
fully functional dependent on the primary key.

3NF A relation will be in 3NF if it is in 2NF and no transition dependency


exists.

BCNF A stronger definition of 3NF is known as Boyce Codd's normal form.

4NF A relation will be in 4NF if it is in Boyce Codd's normal form and has
no multi-valued dependency.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

5NF A relation is in 5NF. If it is in 4NF and does not contain any join
dependency, joining should be lossless.

Advantages of Normalization
o Normalization helps to minimize data redundancy.
o Greater overall database organization.
o Data consistency within the database.
o Much more flexible database design.
o Enforces the concept of relational integrity.

Disadvantages of Normalization
o You cannot start building the database before knowing what the user needs.
o The performance degrades when normalizing the relations to higher normal
forms, i.e., 4NF, 5NF.
o It is very time-consuming and difficult to normalize relations of a higher
degree.
o Careless decomposition may lead to a bad database design, leading to
serious problems.

First Normal Form (1NF)


o A relation will be 1NF if it contains an atomic value.
o It states that an attribute of a table cannot hold multiple values. It must hold
only single-valued attribute.
o First normal form disallows the multi-valued attribute, composite attribute,
and their combinations.

Example: Relation EMPLOYEE is not in 1NF because of multi-valued attribute


EMP_PHONE.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

EMPLOYEE table:

EMP_ID EMP_NAME EMP_PHONE EMP_STATE

14 John 7272826385, UP
9064738238

20 Harry 8574783832 Bihar

12 Sam 7390372389, Punjab


8589830302

The decomposition of the EMPLOYEE table into 1NF has been shown below:

EMP_ID EMP_NAME EMP_PHONE EMP_STATE

14 John 7272826385 UP

14 John 9064738238 UP

20 Harry 8574783832 Bihar

12 Sam 7390372389 Punjab

12 Sam 8589830302 Punjab

Second Normal Form (2NF)


o In the 2NF, relational must be in 1NF.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

o In the second normal form, all non-key attributes are fully functional
dependent on the primary key

Example: Let's assume, a school can store the data of teachers and the subjects
they teach. In a school, a teacher can teach more than one subject.

TEACHER table

TEACHER_ID SUBJECT TEACHER_AGE

25 Chemistry 30

25 Biology 30

47 English 35

83 Math 38

83 Computer 38

In the given table, non-prime attribute TEACHER_AGE is dependent on


TEACHER_ID which is a proper subset of a candidate key. That's why it violates
the rule for 2NF.

To convert the given table into 2NF, we decompose it into two tables:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

TEACHER_DETAIL table:

TEACHER_ID TEACHER_AGE

25 30

47 35

83 38

TEACHER_SUBJECT table:

TEACHER_ID SUBJECT

25 Chemistry

25 Biology

47 English

83 Math

83 Computer

Third Normal Form (3NF)


o A relation will be in 3NF if it is in 2NF and not contain any transitive partial
dependency.
o 3NF is used to reduce the data duplication. It is also used to achieve the data
integrity.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

o If there is no transitive dependency for non-prime attributes, then the


relation must be in third normal form.

A relation is in third normal form if it holds atleast one of the following conditions
for every non-trivial function dependency X → Y.

1. X is a super key.
2. Y is a prime attribute, i.e., each element of Y is part of some candidate key.

Example:

EMPLOYEE_DETAIL table:

EMP_ID EMP_NAME EMP_ZIP EMP_STATE EMP_CITY

222 Harry 201010 UP Noida

333 Stephan 02228 US Boston

444 Lan 60007 US Chicago

555 Katharine 06389 UK Norwich

666 John 462007 MP Bhopal

Super key in the table above:

1. {EMP_ID}, {EMP_ID, EMP_NAME}, {EMP_ID, EMP_NAME, EMP_ZIP}....so on

Candidate key: {EMP_ID}

Non-prime attributes: In the given table, all attributes except EMP_ID are
non-prime.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Here, EMP_STATE & EMP_CITY dependent on EMP_ZIP and EMP_ZIP


dependent on EMP_ID. The non-prime attributes (EMP_STATE, EMP_CITY)
transitively dependent on super key(EMP_ID). It violates the rule of third
normal form.

That's why we need to move the EMP_CITY and EMP_STATE to the new
<EMPLOYEE_ZIP> table, with EMP_ZIP as a Primary key.

EMPLOYEE table:

EMP_ID EMP_NAME EMP_ZIP

222 Harry 201010

333 Stephan 02228

444 Lan 60007

555 Katharine 06389

666 John 462007

EMPLOYEE_ZIP table:

EMP_ZIP EMP_STATE EMP_CITY

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

201010 UP Noida

02228 US Boston

60007 US Chicago

06389 UK Norwich

462007 MP Bhopal

Boyce Codd normal form (BCNF)


o BCNF is the advance version of 3NF. It is stricter than 3NF.
o A table is in BCNF if every functional dependency X → Y, X is the super key
of the table.
o For BCNF, the table should be in 3NF, and for every FD, LHS is super key.

Example: Let's assume there is a company where employees work in more than
one department.

EMPLOYEE table:

EMP_ID EMP_COUNTRY EMP_DEPT DEPT_TYPE EMP_DEPT_NO

264 India Designing D394 283

264 India Testing D394 300

364 UK Stores D283 232

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

364 UK Developing D283 549

In the above table Functional dependencies are as follows:

1. EMP_ID → EMP_COUNTRY
2. EMP_DEPT → {DEPT_TYPE, EMP_DEPT_NO}

Candidate key: {EMP-ID, EMP-DEPT}

The table is not in BCNF because neither EMP_DEPT nor EMP_ID alone are keys.

To convert the given table into BCNF, we decompose it into three tables:

EMP_COUNTRY table:

EMP_ID EMP_COUNTRY

264 India

264 India

EMP_DEPT table:

EMP_DEPT DEPT_TYPE EMP_DEPT_NO

Designing D394 283

Testing D394 300

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Stores D283 232

Developing D283 549

EMP_DEPT_MAPPING table:

EMP_ID EMP_DEPT

D394 283

D394 300

D283 232

D283 549

Functional dependencies:

1. EMP_ID → EMP_COUNTRY
2. EMP_DEPT → {DEPT_TYPE, EMP_DEPT_NO}

Candidate keys:

For the first table: EMP_ID


For the second table: EMP_DEPT
For the third table: {EMP_ID, EMP_DEPT}

Now, this is in BCNF because left side part of both the functional dependencies is
a key

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Transaction
o The transaction is a set of logically related operation. It contains a group of
tasks.
o 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.

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's Account

1. Open_Account(X)
2. Old_Balance = X.balance
3. New_Balance = Old_Balance - 800
4. X.balance = New_Balance
5. Close_Account(X)

Y's Account

1. Open_Account(Y)
2. Old_Balance = Y.balance
3. New_Balance = Old_Balance + 800
4. Y.balance = New_Balance
5. Close_Account(Y)

Operations of Transaction:
Following are the main 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.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Let's take an example to debit transaction from an account which consists of


following operations:

1. 1. R(X);
2. 2. X = X - 500;
3. 3. W(X);

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

o The first operation reads X's value from database and stores it in a buffer.
o The second operation will decrease the value of X by 500. So buffer will
contain 3500.
o 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:

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

Rollback: It is used to undo the work done.

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

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

3. Isolation
4. Durability

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

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

Atomicity involves the following two operations:

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

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

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
o The integrity constraints are maintained so that the database is consistent
before and after the transaction.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

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

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.

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

Durability
o The durability property is used to indicate the performance of the
database's consistent state. It states that the transaction made the
permanent changes.
o 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

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

reaches a state known as the consistent state. That consistent state cannot
be lost, even in the event of a system's failure.
o The recovery subsystem of the DBMS has the responsibility of Durability
property.

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

Active state

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

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Partially committed

o In the partially committed state, a transaction executes its final operation,


but the data is still not saved to the database.
o In the total mark calculation example, a final display of the total marks step
is executed in this state.

Committed
A transaction is said to be in a committed state if it executes all its operations
successfully. In this state, all the effects are now permanently saved on the
database system.

Failed state

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

Aborted

o If any of the checks fail and the transaction has reached a failed state then
the database recovery system will make sure that the database is in its
previous consistent state. If not then it will abort or roll back the transaction
to bring the database into a consistent state.
o If the transaction fails in the middle of the transaction then before executing
the transaction, all the executed transactions are rolled back to its
consistent state.
o After aborting the transaction, the database recovery module will select one
of the two operations:
1. Re-start the transaction
2. Kill the transaction

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Database Security
Security of databases refers to the array of controls, tools, and procedures
designed to ensure and safeguard confidentiality, integrity, and accessibility. This
tutorial will concentrate on confidentiality because it's a component that is most
at risk in data security breaches.

Security for databases must cover and safeguard the following aspects:

o The database containing data.


o Database management systems (DBMS)
o Any applications that are associated with it.
o Physical database servers or the database server virtual, and the hardware
that runs it.
o The infrastructure for computing or network that is used to connect to the
database.

Security of databases is a complicated and challenging task that requires all


aspects of security practices and technologies. This is inherently at odds with the
accessibility of databases. The more usable and accessible the database is, the
more susceptible we are to threats from security. The more vulnerable it is to
attacks and threats, the more difficult it is to access and utilize.

Why Database Security is Important?


According to the definition, a data breach refers to a breach of data integrity in
databases. The amount of damage an incident like a data breach can cause our
business is contingent on various consequences or elements.

o Intellectual property that is compromised: Our intellectual property--


trade secrets, inventions, or proprietary methods -- could be vital for our
ability to maintain an advantage in our industry. If our intellectual property
has been stolen or disclosed and our competitive advantage is lost, it could
be difficult to keep or recover.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

o The damage to our brand's reputation: Customers or partners may not


want to purchase goods or services from us (or deal with our business) If
they do not feel they can trust our company to protect their data or their
own.
o The concept of business continuity (or lack of it): Some businesses
cannot continue to function until a breach has been resolved.
o Penalties or fines to be paid for not complying: The cost of not complying
with international regulations like the Sarbanes-Oxley Act (SAO) or
Payment Card Industry Data Security Standard (PCI DSS) specific to
industry regulations on data privacy, like HIPAA or regional privacy laws
like the European Union's General Data Protection Regulation (GDPR) could
be a major problem with fines in worst cases in excess of many million
dollars for each violation.
o Costs for repairing breaches and notifying consumers about
them: Alongside notifying customers of a breach, the company that has
been breached is required to cover the investigation and forensic services
such as crisis management, triage repairs to the affected systems, and much
more.

Common Threats and Challenges


Numerous software configurations that are not correct, weaknesses, or patterns
of carelessness or abuse can lead to a breach of security. Here are some of the most
prevalent kinds of reasons for security attacks and the reasons.

Insider Dangers
An insider threat can be an attack on security from any three sources having an
access privilege to the database.

o A malicious insider who wants to cause harm


o An insider who is negligent and makes mistakes that expose the database to
attack. vulnerable to attacks

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

o An infiltrator is an outsider who acquires credentials by using a method like


phishing or accessing the database of credential information in the database
itself.

Insider dangers are among the most frequent sources of security breaches to
databases. They often occur as a consequence of the inability of employees to have
access to privileged user credentials.

Human Error
The unintentional mistakes, weak passwords or sharing passwords, and other
negligent or uninformed behaviours of users remain the root causes of almost half
(49 percent) of all data security breaches.

Database Software Vulnerabilities can be Exploited


Hackers earn their money by identifying and exploiting vulnerabilities in software
such as databases management software. The major database software companies
and open-source databases management platforms release regular security
patches to fix these weaknesses. However, failing to implement the patches on
time could increase the risk of being hacked.

SQL/NoSQL Injection Attacks


A specific threat to databases is the infusing of untrue SQL as well as other non-
SQL string attacks in queries for databases delivered by web-based apps and HTTP
headers. Companies that do not follow the safe coding practices for web
applications and conduct regular vulnerability tests are susceptible to attacks
using these.

Buffer Overflow is a way to Exploit Buffers


Buffer overflow happens when a program seeks to copy more data into the
memory block with a certain length than it can accommodate. The attackers may
make use of the extra data, which is stored in adjacent memory addresses, to
establish a basis for they can begin attacks.

DDoS (DoS/DDoS) Attacks

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

In a denial-of-service (DoS) attack in which the attacker overwhelms the targeted


server -- in this case, the database server with such a large volume of requests that
the server is unable to meet no longer legitimate requests made by actual users. In
most cases, the server is unstable or even fails to function.

Malware
Malware is software designed to exploit vulnerabilities or cause harm to
databases. Malware can be accessed via any device that connects to the databases
network.

Attacks on Backups
Companies that do not protect backup data using the same rigorous controls
employed to protect databases themselves are at risk of cyberattacks on backups.

The following factors amplify the threats:

o Data volumes are growing: Data capture, storage, and processing continue
to increase exponentially in almost all organizations. Any tools or methods
must be highly flexible to meet current as well as far-off needs.
o The infrastructure is sprawling: Network environments are becoming
more complicated, especially as companies shift their workloads into
multiple clouds and hybrid cloud architectures and make the selection of
deployment, management, and administration of security solutions more
difficult.
o More stringent requirements for regulatory compliance: The
worldwide regulatory compliance landscape continues to increase by
complexity. This makes the compliance of every mandate more challenging.

Best use of Database Security


As databases are almost always accessible via the network, any security risk to any
component or part of the infrastructure can threaten the database. Likewise, any
security attack that impacts a device or workstation could endanger the database.
Therefore, security for databases must go beyond the limits of the database.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

In evaluating the security of databases in our workplace to determine our


organization's top priorities, look at each of these areas.

o Security for physical security: If the database servers are on-premises or


the cloud data centre, they should be placed in a secure, controlled climate.
(If our server for database is located in a cloud-based data centre, the cloud
provider will handle the security on our behalf.)
o Access to the network and administrative restrictions: The practical
minimum number of users granted access to the database and their access
rights should be restricted to the minimum level required to fulfil their
tasks. Additionally, access to the network is limited to the minimum
permissions needed.
o End security of the user account or device: Be aware of who has access
to the database and when and how data is used. Monitoring tools for data
can notify you of data-related activities that are uncommon or seem to be
dangerous. Any device that connects to the network hosting the database
must be physically secured (in the sole control of the appropriate person)
and be subject to security checks throughout the day.
o Security: ALL data--including data stored in databases, as well as credential
information should be secured using the highest-quality encryption when
in storage and while in transport. All encryption keys must be used in
accordance with the best practices guidelines.
o Security of databases using software: Always use the most current
version of our software to manage databases and apply any patches
immediately after they're released.
o Security for web server applications and websites: Any application or
web server that connects to the database could be a target and should be
subjected to periodic security testing and best practices management.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

o Security of backups: All backups, images, or copies of the database should


have the identical (or equally rigorous) security procedures as the database
itself.
o Auditing: Audits of security standards for databases should be conducted
every few months. Record all the logins on the server as well as the
operating system. Also, record any operations that are made on sensitive
data, too.

Data protection tools and platforms


Today, a variety of companies provide data protection platforms and tools. A
comprehensive solution should have all of the following features:

o Discovery: The ability to discover is often needed to meet regulatory


compliance requirements. Look for a tool that can detect and categorize
weaknesses across our databases, whether they're hosted in the cloud or
on-premises. It will also provide recommendations to address any
vulnerabilities that are discovered.
o Monitoring of Data Activity: The solution should be capable of monitoring
and analysing the entire data activity in all databases, whether our
application is on-premises, in the cloud, or inside a container. It will alert us
to suspicious activity in real-time to allow us to respond more quickly to
threats. It also provides visibility into the state of our information through
an integrated and comprehensive user interface. It is also important to
choose a system that enforces rules that govern policies, procedures, and
the separation of duties. Be sure that the solution we select is able to
generate the reports we need to comply with the regulations.
o The ability to Tokenize and Encrypt Data: In case of an incident,
encryption is an additional line of protection against any compromise. Any
software we choose to use must have the flexibility to protect data cloud,
on-premises hybrid, or multi-cloud environments. Find a tool with volume,

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

file, and application encryption features that meet our company's


regulations for compliance. This could require tokenization (data
concealing) or advanced key management of security keys.
o Optimization of Data Security and Risk Analysis: An application that will
provide contextual insights through the combination of security data with
advanced analytics will allow users to perform optimizing, risk assessment,
and reporting in a breeze. Select a tool that is able to keep and combine large
amounts of recent and historical data about the security and state of your
databases. Also, choose a solution that provides data exploration, auditing,
and reporting capabilities via an extensive but user-friendly self-service
dashboard.

UNIT – IV

SQL Commands
o SQL commands are instructions. It is used to communicate with the
database. It is also used to perform specific tasks, functions, and queries of
data.
o SQL can perform various tasks like create a table, add data to tables, drop
the table, modify the table, set permission for users.

Types of SQL Commands


There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

1. Data Definition Language (DDL)

o DDL changes the structure of the table like creating a table, deleting a table,
altering a table, etc.
o All the command of DDL are auto-committed that means it permanently
save all the changes in the database.

Here are some commands that come under DDL:

o CREATE
o ALTER
o DROP

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

o TRUNCATE

a. CREATE It is used to create a new table in the database.

Syntax:

CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);

Example:

CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB


DATE);

b. DROP: It is used to delete both the structure and record stored in the table.

Syntax

DROP TABLE table_name;

Example

DROP TABLE EMPLOYEE;

c. ALTER: It is used to alter the structure of the database. This change could be
either to modify the characteristics of an existing attribute or probably to add a
new attribute.

Syntax:

To add a new column in the table

ALTER TABLE table_name ADD column_name COLUMN-definition;

To modify existing column in the table:

ALTER TABLE table_name MODIFY(column_definitions....);

EXAMPLE

ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));

d. TRUNCATE: It is used to delete all the rows from the table and free the space
containing the table.

Syntax:

TRUNCATE TABLE table_name;

Example:

TRUNCATE TABLE EMPLOYEE;

2. Data Manipulation Language

o DML commands are used to modify the database. It is responsible for all
form of changes in the database.
o The command of DML is not auto-committed that means it can't
permanently save all the changes in the database. They can be rollback.

Here are some commands that come under DML:

o INSERT
o UPDATE
o DELETE

a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the
row of a table.

Syntax:

INSERT INTO TABLE_NAME


(col1, col2, col3,.... col N)
VALUES (value1, value2, value3, .... valueN);

Or

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

INSERT INTO TABLE_NAME


VALUES (value1, value2, value3, .... valueN);

For example:

INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS");

b. UPDATE: This command is used to update or modify the value of a column in


the table.

Syntax:

UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [W


HERE CONDITION]

For example:

UPDATE students
SET User_Name = 'Sonoo'
WHERE Student_Id = '3'

c. DELETE: It is used to remove one or more row from a table.

Syntax:

DELETE FROM table_name [WHERE condition];

For example:

DELETE FROM javatpoint


WHERE Author="Sonoo";

3. Data Control Language


DCL commands are used to grant and take back authority from any database user.

Here are some commands that come under DCL:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

o Grant
o Revoke

a. Grant: It is used to give user access privileges to a database.

Example

GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;

b. Revoke: It is used to take back permissions from the user.

Example

REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;

4. Transaction Control Language


TCL commands can only use with DML commands like INSERT, DELETE and
UPDATE only.

These operations are automatically committed in the database that's why they
cannot be used while creating tables or dropping them.

Here are some commands that come under TCL:

o COMMIT
o ROLLBACK
o SAVEPOINT

a. Commit: Commit command is used to save all the transactions to the database.

Syntax:

COMMIT;

Example:

DELETE FROM CUSTOMERS

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

WHERE AGE = 25;


COMMIT;

b. Rollback: Rollback command is used to undo transactions that have not already
been saved to the database.

Syntax:

ROLLBACK;

Example:

DELETE FROM CUSTOMERS


WHERE AGE = 25;
ROLLBACK;

c. SAVEPOINT: It is used to roll the transaction back to a certain point without


rolling back the entire transaction.

Syntax:

SAVEPOINT SAVEPOINT_NAME;

5. Data Query Language


DQL is used to fetch the data from the database.

It uses only one command:

o SELECT

a. SELECT: This is the same as the projection operation of relational algebra. It is


used to select the attribute based on the condition described by WHERE clause.

Syntax:

SELECT expressions

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

FROM TABLES
WHERE conditions;

For example:

SELECT emp_name
FROM employee
WHERE age > 20;

SQL Datatype
o SQL Datatype is used to define the values that a column can contain.
o Every column is required to have a name and data type in the database table.

Datatype of SQL:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

1. Binary Datatypes
There are Three types of binary Datatypes which are given below:

Data Description
Type

binary It has a maximum length of 8000 bytes. It contains fixed-length binary data.

varbinary It has a maximum length of 8000 bytes. It contains variable-length binary data.

image It has a maximum length of 2,147,483,647 bytes. It contains variable-length binary data.

2. Approximate Numeric Datatype :


The subtypes are given below:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Data From To Description


type

float -1.79E + 308 1.79E + 308 It is used to specify a floating-point value e.g. 6.2, 2.9 etc.

real -3.40e + 38 3.40E + 38 It specifies a single precision floating point number

3. Exact Numeric Datatype


The subtypes are given below:

Data type Description

int It is used to specify an integer value.

smallint It is used to specify small integer value.

bit It has the number of bits to store.

decimal It specifies a numeric value that can have a decimal number.

numeric It is used to specify a numeric value.

4. Character String Data type


The subtypes are given below:

Data Description
type

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

char It has a maximum length of 8000 characters. It contains Fixed-length non-unicode characters.

varchar It has a maximum length of 8000 characters. It contains variable-length non-unicode


characters.

text It has a maximum length of 2,147,483,647 characters. It contains variable-length non-unicode


characters.

5. Date and time Datatypes


The subtypes are given below:

Datatype Description

date It is used to store the year, month, and days value.

time It is used to store the hour, minute, and second values.

timestamp It stores the year, month, day, hour, minute, and the second value.

SELECT Operation in Relational


Algebra
Select operation chooses the subset of tuples from the relation that
satisfies the given condition mentioned in the syntax of selection. The
selection operation is also known as horizontal partitioning since it
partitions the table or relation horizontally.
Notation:
σ c(R)
where ‘c’ is selection condition which is a boolean expression(condition),
we can have a single condition like Roll= 3 or combination of condition like

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

X>2 AND Y<1,


symbol ‘σ (sigma)’ is used to denote select(choose) operator,
R is a relational algebra expression, whose result is a relation. The boolean
expression specified in condition ‘c’ can be written in the following form:
<attribute name> <comparison operator> <constant value> or <attribute name>

where, <attribute name> is obviously name of an attribute of relation,


<comparison operator> is any of the operator {<, >, =, <=, >=, !=} and,
<constant value> is constant value taken from the domain of the relation.
Example-1:
σ Place = 'Mumbai' or Salary >= 1000000 (Citizen)
σ Department = 'Analytics'(σLocation = 'NewYork'(Manager))
The query above(immediate) is called nested expression, here, as usual, we
evaluate the inner expression first (which results in relation say
Manager1), then we calculate the outer expression on Manager1(the
relation we obtained from evaluating the inner expression), which results
in relation again, which is an instance of a relation we input.
Example-2:
Given a relation Student(Roll, Name, Class, Fees, Team) with the following
tuples:

Roll Name Department Fees Team

1 Bikash CSE 22000 A

2 Josh CSE 34000 A

3 Kevin ECE 36000 C

4 Ben ECE 56000 D

Select all the student of Team A :

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

σ Team = 'A' (Student)

Roll Name Department Fees Team

1 Bikash CSE 22000 A

2 Josh CSE 34000 A

Select all the students of department ECE whose fees is greater then equal
to 10000 and belongs to Team other than A.
σ Fees >= 10000(σClass != 'A' (Student))

Roll Name Department Fees Team

3 Kevin ECE 36000 C

4 Ben ECE 56000 D

Important points about Select operation :


Select operator is Unary, means it it applied to single relation only.
Selection operation is commutative that is,
σ c1(σ c2(R)) = σ c2(σ c1(R))
The degree (number of attributes) of resulting relation from a Selection
operation is same as the degree of the Relation given. The cardinality
(number of tuples) of resulting relation from a Selection operation is,
0 <= σ c (R) <= |R|

Projection operation
It displays the specific column of a table. It is denoted by pie (∏). It is a vertical
subset of the original relation. It eliminates duplicate tuples.

Syntax
The syntax is as follows −
∏regno(student)

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Example
Consider the student table:

Regno Branch Section

1 CSE A

2 ECE B

3 CIVIL B

4 IT A

To display regno column of student table, we can use the following command −
∏regno(student)
Output
RegNo

To display branch, section column of student table, use the following command −
∏branch,section(student)
The result is as follows −

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Branch Section

CSE A

ECE B

CIVIL B

IT A

To display regno, section of ECE students, use the following command −


∏regno,section(σbranch=ECE(student))

Output
Regno Section

2 B

Note: Conditions can be written in select operation but not in projection


operation.
Consider the employee table to know more about projection.
• If no condition is specified in the query then, Π empid, ename, salary,
address, dno (emp).
• If condition is specified then, the composition of the select and projection is
as follows −
∏ empid, ename, salary, address, dno (σ salary >20,00 ^ LOC = HOD ^ dno=20) (emp)

SQL Set Operation


The SQL Set operation is used to combine the two or more SQL SELECT statements.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Types of Set Operation


1. Union
2. UnionAll
3. Intersect
4. Minus

1. Union

o The SQL Union operation is used to combine the result of two or more SQL
SELECT queries.
o In the union operation, all the number of datatype and columns must be
same in both the tables on which UNION operation is being applied.
o The union operation eliminates the duplicate rows from its resultset.

Syntax

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

SELECT column_name FROM table1


UNION
SELECT column_name FROM table2;

Example:

The First table

ID NAME

1 Jack

2 Harry

3 Jackson

The Second table

ID NAME

3 Jackson

4 Stephan

5 David

Union SQL query will be:

SELECT * FROM First


UNION
SELECT * FROM Second;

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

The resultset table will look like:

ID NAME

1 Jack

2 Harry

3 Jackson

4 Stephan

5 David

2. Union All
Union All operation is equal to the Union operation. It returns the set without
removing duplication and sorting the data.

Syntax:

SELECT column_name FROM table1


UNION ALL
SELECT column_name FROM table2;

Example: Using the above First and Second table.

Union All query will be like:

SELECT * FROM First

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

UNION ALL
SELECT * FROM Second;

The resultset table will look like:

ID NAME

1 Jack

2 Harry

3 Jackson

3 Jackson

4 Stephan

5 David

3. Intersect

o It is used to combine two SELECT statements. The Intersect operation


returns the common rows from both the SELECT statements.
o In the Intersect operation, the number of datatype and columns must be the
same.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

o It has no duplicates and it arranges the data in ascending order by default.

Syntax

SELECT column_name FROM table1


INTERSECT
SELECT column_name FROM table2;

Example:

Using the above First and Second table.

Intersect query will be:

SELECT * FROM First


INTERSECT
SELECT * FROM Second;

The resultset table will look like:

ID NAME

3 Jackson

4. Minus

o It combines the result of two SELECT statements. Minus operator is used to


display the rows which are present in the first query but absent in the
second query.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

o It has no duplicates and data arranged in ascending order by default.

Syntax:

SELECT column_name FROM table1


MINUS
SELECT column_name FROM table2;

Example

Using the above First and Second table.

Minus query will be:

SELECT * FROM First


MINUS
SELECT * FROM Second;

The resultset table will look like:

ID NAME

1 Jack

2 Harry

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Join Operations:
A Join operation combines related tuples from different relations, if and only if a
given join condition is satisfied. It is denoted by ⋈.

Example:
EMPLOYEE

EMP_CODE EMP_NAME

101 Stephan

102 Jack

103 Harry

SALARY

EMP_CODE SALARY

101 50000

102 30000

103 25000

1. Operation: (EMPLOYEE ⋈ SALARY)

Result:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

EMP_CODE EMP_NAME SALARY

101 Stephan 50000

102 Jack 30000

103 Harry 25000

Types of Join operations:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

1. Natural Join:

o A natural join is the set of tuples of all combinations in R and S that are equal
on their common attribute names.
o It is denoted by ⋈.

Example: Let's use the above EMPLOYEE table and SALARY table:

Input:

1. ∏EMP_NAME, SALARY (EMPLOYEE ⋈ SALARY)

Output:

EMP_NAME SALARY

Stephan 50000

Jack 30000

Harry 25000

2. Outer Join:
The outer join operation is an extension of the join operation. It is used to deal
with missing information.

Example:

EMPLOYEE

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

EMP_NAME STREET CITY

Ram Civil line Mumbai

Shyam Park street Kolkata

Ravi M.G. Street Delhi

Hari Nehru nagar Hyderabad

FACT_WORKERS

EMP_NAME BRANCH SALARY

Ram Infosys 10000

Shyam Wipro 20000

Kuber HCL 30000

Hari TCS 50000

Input:

1. (EMPLOYEE ⋈ FACT_WORKERS)

Output:

EMP_NAME STREET CITY BRANCH SAL

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Ram Civil line Mumbai Infosys 1000

Shyam Park street Kolkata Wipro 2000

Hari Nehru nagar Hyderabad TCS 5000

An outer join is basically of three types:

a. Left outer join


b. Right outer join
c. Full outer join

a. Left outer join:

o Left outer join contains the set of tuples of all combinations in R and S that
are equal on their common attribute names.
o In the left outer join, tuples in R have no matching tuples in S.
o It is denoted by ⟕.

Example: Using the above EMPLOYEE table and FACT_WORKERS table

Input:

1. EMPLOYEE ⟕ FACT_WORKERS

EMP_NAME STREET CITY BRANCH SAL

Ram Civil line Mumbai Infosys 1000

Shyam Park street Kolkata Wipro 2000

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Hari Nehru street Hyderabad TCS 5000

Ravi M.G. Street Delhi NULL NUL

b. Right outer join:

o Right outer join contains the set of tuples of all combinations in R and S that
are equal on their common attribute names.
o In right outer join, tuples in S have no matching tuples in R.
o It is denoted by ⟖.

Example: Using the above EMPLOYEE table and FACT_WORKERS Relation

Input:

1. EMPLOYEE ⟖ FACT_WORKERS

Output:

EMP_NAME BRANCH SALARY STREET CITY

Ram Infosys 10000 Civil line Mumb

Shyam Wipro 20000 Park street Kolka

Hari TCS 50000 Nehru street Hyder

Kuber HCL 30000 NULL NULL

c. Full outer join:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

o Full outer join is like a left or right join except that it contains all rows from
both tables.
o In full outer join, tuples in R that have no matching tuples in S and tuples in
S that have no matching tuples in R in their common attribute name.
o It is denoted by ⟗.

Example: Using the above EMPLOYEE table and FACT_WORKERS table

Input:

1. EMPLOYEE ⟗ FACT_WORKERS

Output:

EMP_NAME STREET CITY BRANCH SAL

Ram Civil line Mumbai Infosys 1000

Shyam Park street Kolkata Wipro 2000

Hari Nehru street Hyderabad TCS 5000

Ravi M.G. Street Delhi NULL NUL

Kuber NULL NULL HCL 3000

3. Equi join:
It is also known as an inner join. It is the most common join. It is based on matched
data as per the equality condition. The equi join uses the comparison operator(=).

Example:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

CUSTOMER RELATION

CLASS_ID NAME

1 John

2 Harry

3 Jackson

PRODUCT

PRODUCT_ID CITY

1 Delhi

2 Mumbai

3 Noida

Input:

1. CUSTOMER ⋈ PRODUCT

Output:

CLASS_ID NAME PRODUCT_ID CITY

1 John 1 Delhi

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

2 Harry 2 Mumb

3 Harry 3 Noida

Aggregate functions

Aggregate functions in DBMS take multiple rows from the table and return a value
according to the query.
All the aggregate functions are used in Select statement.
Syntax −
SELECT <FUNCTION NAME> (<PARAMETER>) FROM <TABLE NAME>

AVG Function
This function returns the average value of the numeric column that is supplied as
a parameter.
Example: Write a query to select average salary from employee table.
Select AVG(salary) from Employee

COUNT Function
The count function returns the number of rows in the result. It does not count the
null values.
Example: Write a query to return number of rows where salary > 20000.
Select COUNT(*) from Employee where Salary > 20000;
Types −
• COUNT(*): Counts all the number of rows of the table including null.
• COUNT( COLUMN_NAME): count number of non-null values in column.
• COUNT( DISTINCT COLUMN_NAME): count number of distinct values in a
column.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

MAX Function
The MAX function is used to find maximum value in the column that is supplied
as a parameter. It can be used on any type of data.
Example − Write a query to find the maximum salary in employee table.
Select MAX(salary) from Employee

SUM Function
This function sums up the values in the column supplied as a parameter.
Example: Write a query to get the total salary of employees.
Select SUM(salary) from Employee

STDDEV Function
The STDDEV function is used to find standard deviation of the column specified
as argument.
Example − Write a query to find standard deviation of salary in Employee table.
Select STDDEV(salary) from Employee

VARIANCE Function
The VARIANCE Function is used to find variance of the column specified as
argument.
Example −
Select VARIANCE(salary) from Employee

SQL Sub Query


A Subquery is a query within another SQL query and embedded within the WHERE
clause.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Important Rule:

o A subquery can be placed in a number of SQL clauses like WHERE clause,


FROM clause, HAVING clause.
o You can use Subquery with SELECT, UPDATE, INSERT, DELETE statements
along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
o A subquery is a query within another query. The outer query is known as
the main query, and the inner query is known as a subquery.
o Subqueries are on the right side of the comparison operator.
o A subquery is enclosed in parentheses.
o In the Subquery, ORDER BY command cannot be used. But GROUP BY
command can be used to perform the same function as ORDER BY
command.

1. Subqueries with the Select Statement


SQL subqueries are most frequently used with the Select statement.

Syntax

1. SELECT column_name
2. FROM table_name
3. WHERE column_name expression operator
4. ( SELECT column_name from table_name WHERE ... );

Example

Consider the EMPLOYEE table have the following records:

ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

4 Alina 29 UK 6500.00

5 Kathrin 34 Bangalore 8500.00

6 Harry 42 China 4500.00

7 Jackson 25 Mizoram 10000.00

The subquery with a SELECT statement will be:

1. SELECT *
2. FROM EMPLOYEE
3. WHERE ID IN (SELECT ID
4. FROM EMPLOYEE
5. WHERE SALARY > 4500);

This would produce the following result:

ID NAME AGE ADDRESS SALARY

4 Alina 29 UK 6500.00

5 Kathrin 34 Bangalore 8500.00

7 Jackson 25 Mizoram 10000.00

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

2. Subqueries with the INSERT Statement


o SQL subquery can also be used with the Insert statement. In the insert
statement, data returned from the subquery is used to insert into another
table.
o In the subquery, the selected data can be modified with any of the character,
date functions.

Syntax:

1. INSERT INTO table_name (column1, column2, column3....)


2. SELECT *
3. FROM table_name
4. WHERE VALUE OPERATOR

Example

Consider a table EMPLOYEE_BKP with similar as EMPLOYEE.

Now use the following syntax to copy the complete EMPLOYEE table into the
EMPLOYEE_BKP table.

1. INSERT INTO EMPLOYEE_BKP


2. SELECT * FROM EMPLOYEE
3. WHERE ID IN (SELECT ID
4. FROM EMPLOYEE);

3. Subqueries with the UPDATE Statement


The subquery of SQL can be used in conjunction with the Update statement. When
a subquery is used with the Update statement, then either single or multiple
columns in a table can be updated.

Syntax

1. UPDATE table

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

2. SET column_name = new_value


3. WHERE VALUE OPERATOR
4. (SELECT COLUMN_NAME
5. FROM TABLE_NAME
6. WHERE condition);

Example

Let's assume we have an EMPLOYEE_BKP table available which is backup of


EMPLOYEE table. The given example updates the SALARY by .25 times in the
EMPLOYEE table for all employee whose AGE is greater than or equal to 29.

1. UPDATE EMPLOYEE
2. SET SALARY = SALARY * 0.25
3. WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
4. WHERE AGE >= 29);

This would impact three rows, and finally, the EMPLOYEE table would have the
following records.

ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

4 Alina 29 UK 1625.00

5 Kathrin 34 Bangalore 2125.00

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

6 Harry 42 China 1125.00

7 Jackson 25 Mizoram 10000.00

4. Subqueries with the DELETE Statement


The subquery of SQL can be used in conjunction with the Delete statement just like
any other statements mentioned above.

Syntax

1. DELETE FROM TABLE_NAME


2. WHERE VALUE OPERATOR
3. (SELECT COLUMN_NAME
4. FROM TABLE_NAME
5. WHERE condition);

Example

Let's assume we have an EMPLOYEE_BKP table available which is backup of


EMPLOYEE table. The given example deletes the records from the EMPLOYEE
table for all EMPLOYEE whose AGE is greater than or equal to 29.

1. DELETE FROM EMPLOYEE


2. WHERE AGE IN (SELECT AGE FROM EMPLOYEE_BKP
3. WHERE AGE >= 29 );

This would impact three rows, and finally, the EMPLOYEE table would have the
following records.

ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

7 Jackson 25 Mizoram 10000.00

UNIT – V

PL/SQL Structure:
In PL/SQL, the code is not executed in single line format, but it is always
executed by grouping the code into a single element called Blocks. In this
tutorial, you are going to learn about these blocks.

Blocks contain both PL/SQL as well as SQL instruction. All these


instruction will be executed as a whole rather than executing a single
instruction at a time.

In this tutorial, you will learn:

• What is PL/SQL block?


• Block Structure
• PL/SQL Block Syntax

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

• Types of PL/SQL block

Block Structure
PL/SQL blocks have a pre-defined structure in which the code is to be
grouped. Below are different sections of PL/SQL blocks.

1. Declaration section
2. Execution section
3. Exception-Handling section

The below picture illustrates the different PL/SQL block and their
section order.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Declaration Section
This is the first section of the PL/SQL blocks. This section is an optional
part. This is the section in which the declaration of variables, cursors,
exceptions, subprograms, pragma instructions and collections that are
needed in the block will be declared. Below are few more characteristics
of this part.

Execution Section
Execution part is the main and mandatory part which actually executes
the code that is written inside it. Since the PL/SQL expects the executable
statements from this block this cannot be an empty block, i.e., it should
have at least one valid executable code line in it. Below are few more
characteristics of this part.

• This can contain both PL/SQL code and SQL code.


• This can contain one or many blocks inside it as a nested block.
• This section starts with the keyword ‘BEGIN’.
• This section should be followed either by ‘END’ or Exception-
Handling section (if present)

Exception-Handling Section:
The exception is unavoidable in the program which occurs at run-time
and to handle this Oracle has provided an Exception-handling section in
blocks. This section can also contain PL/SQL statements. This is an
optional section of the PL/SQL blocks.

• This is the section where the exception raised in the execution


block is handled.
• This section is the last part of the PL/SQL block.
• Control from this section can never return to the execution block.
• This section starts with the keyword ‘EXCEPTION’.
• This section should always be followed by the keyword ‘END’.

The Keyword ‘END’ marks the end of PL/SQL block.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

PL/SQL Block Syntax


Below is the syntax of the PL/SQL block structure.

DECLARE --optional
<declarations>

BEGIN --mandatory
<executable statements. At least one executable statement is mandatory>

EXCEPTION --optional
<exception handles>

END; --mandatory
/
Note: A block should always be followed by ‘/’ which sends the
information to the compiler about the end of the block.

Types of PL/SQL block


PL/SQL blocks are of mainly two types.

1. Anonymous blocks

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

2. Named Blocks

Anonymous blocks:
Anonymous blocks are PL/SQL blocks which do not have any names
assigned to them. They need to be created and used in the same session
because they will not be stored in the server as database objects.

Since they need not store in the database, they need no compilation
steps. They are written and executed directly, and compilation and
execution happen in a single process.

Below are few more characteristics of Anonymous blocks.

• These blocks don’t have any reference name specified for them.
• These blocks start with the keyword ‘DECLARE’ or ‘BEGIN’.
• Since these blocks do not have any reference name, these cannot be
stored for later purpose. They shall be created and executed in the
same session.
• They can call the other named blocks, but call to anonymous block
is not possible as it is not having any reference.
• It can have nested block in it which can be named or anonymous. It
can also be nested in any blocks.
• These blocks can have all three sections of the block, in which
execution section is mandatory, the other two sections are
optional.

Named blocks:
Named blocks have a specific and unique name for them. They are stored
as the database objects in the server. Since they are available as database
objects, they can be referred to or used as long as it is present on the
server. The compilation process for named blocks happens separately
while creating them as a database objects.

Below are few more characteristics of Named blocks.

• These blocks can be called from other blocks.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

• The block structure is same as an anonymous block, except it will


never start with the keyword ‘DECLARE’. Instead, it will start with
the keyword ‘CREATE’ which instruct the compiler to create it as a
database object.
• These blocks can be nested within other blocks. It can also contain
nested blocks.
• Named blocks are basically of two types:

1. Procedure
2. Function

We will learn more about these named blocks in “Procedure” and


“Function” topics in later tutorial.

Elements of PL/SQL

PL/SQL Program Units


A PL/SQL unit is any one of the following −

• PL/SQL block
• Function
• Package
• Package body
• Procedure
• Trigger
• Type
• Type body

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

PL/SQL OPERATORS:
An operator is a symbol that tells the compiler to perform specific mathematical
or logical manipulation. PL/SQL language is rich in built-in operators and provides
the following types of operators −

• Arithmetic operators
• Relational operators
• Comparison operators
• Logical operators
• String operators
Here, we will understand the arithmetic, relational, comparison and logical
operators one by one. The String operators will be discussed in a later chapter
− PL/SQL - Strings.

Arithmetic Operators
Following table shows all the arithmetic operators supported by PL/SQL. Let us
assume variable A holds 10 and variable B holds 5, then −
Show Examples

Operator Description Example

+ Adds two operands A + B will give 15

- Subtracts second operand from the first A - B will give 5

* Multiplies both operands A * B will give 50

/ Divides numerator by de-numerator A / B will give 2

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

** Exponentiation operator, raises one operand to the power of A ** B will give


other 100000

Relational Operators
Relational operators compare two expressions or values and return a Boolean
result. Following table shows all the relational operators supported by PL/SQL.
Let us assume variable A holds 10 and variable B holds 20, then –

Show Examples

Operator Description Example

Checks if the values of two operands are equal or not, if yes then (A = B) is not
=
condition becomes true. true.

!=
Checks if the values of two operands are equal or not, if values are (A != B) is
<> not equal then condition becomes true. true.
~=

Checks if the value of left operand is greater than the value of right (A > B) is not
>
operand, if yes then condition becomes true. true.

Checks if the value of left operand is less than the value of right (A < B) is true.
<
operand, if yes then condition becomes true.

Checks if the value of left operand is greater than or equal to the (A >= B) is not
>=
value of right operand, if yes then condition becomes true. true.

Checks if the value of left operand is less than or equal to the value (A <= B) is
<=
of right operand, if yes then condition becomes true. true

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Comparison Operators
Comparison operators are used for comparing one expression to another. The
result is always either TRUE, FALSE or NULL.
Show Examples

Operator Description Example

The LIKE operator compares a character, If 'Zara Ali' like 'Z% A_i' returns a
string, or CLOB value to a pattern and returns Boolean true, whereas, 'Nuha Ali'
LIKE
TRUE if the value matches the pattern and like 'Z% A_i' returns a Boolean
FALSE if it does not. false.

If x = 10 then, x between 5 and 20


The BETWEEN operator tests whether a value
returns true, x between 5 and 10
BETWEEN lies in a specified range. x BETWEEN a AND b
returns true, but x between 11 and
means that x >= a and x <= b.
20 returns false.

The IN operator tests set membership. x IN If x = 'm' then, x in ('a', 'b', 'c')
IN (set) means that x is equal to any member of returns Boolean false but x in ('m',
set. 'n', 'o') returns Boolean true.

The IS NULL operator returns the BOOLEAN


value TRUE if its operand is NULL or FALSE if it If x = 'm', then 'x is null' returns
IS NULL
is not NULL. Comparisons involving NULL Boolean false.
values always yield NULL.

Logical Operators
Following table shows the Logical operators supported by PL/SQL. All these
operators work on Boolean operands and produce Boolean results. Let us
assume variable A holds true and variable B holds false, then −
Show Examples

Operator Description Examples

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Called the logical AND operator. If both the operands are true then (A and B) is
and
condition becomes true. false.

Called the logical OR Operator. If any of the two operands is true (A or B) is


or
then condition becomes true. true.

Called the logical NOT Operator. Used to reverse the logical state of not (A and B)
not its operand. If a condition is true then Logical NOT operator will is true.
make it false.

PL/SQL Operator Precedence


Operator precedence determines the grouping of terms in an expression. This
affects how an expression is evaluated. Certain operators have higher precedence
than others; for example, the multiplication operator has higher precedence than
the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has
higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those
with the lowest appear at the bottom. Within an expression, higher precedence
operators will be evaluated first.
The precedence of operators goes as follows: =, <, >, <=, >=, <>, !=, ~=, ^=, IS NULL,
LIKE, BETWEEN, IN.
Show Examples

Operator Operation

** exponentiation

+, - identity, negation

*, / multiplication, division

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

+, -, || addition, subtraction, concatenation

comparison

NOT logical negation

AND conjunction

OR inclusion

PL/SQL Control statements


PL/SQL supports the conditional statements and iterative statements like other
programming languages such as C++, java etc.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

PL/SQL IF Statements

1. IF-THEN Statement

Syntax

IF condition
THEN
Statement;
END IF;

This syntax is used when user needs to execute statements when condition is true.

2. IF-THEN-ELSE Statement

Syntax

IF condition
THEN
[Statements to execute when condition is TRUE]
ELSE
[Statements to execute when condition is FALSE]
END IF;

This syntax is used to execute one set of statements when condition is TRUE or
different set of statements when condition is FALSE.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

3. IF-THEN-ELSIF statement

Syntax

IF Condition1
THEN
Statements to execute when condition1 is TRUE
ELSIF condition2
THEN
Statements to execute when condition2 is TRUE
END IF;

This syntax is used to execute one set of statements when condition1 is TRUE or a
different set of statements when condition is FALSE.

4. IF-THEN-ELS-IF-ELSE Statement

Syntax

IF condition1
THEN
Statements to execute when condition1 is TRUE
ELSIF condition2
THEN
Statements to execute when condition2 is TRUE
ELSE
Statements to execute when both condition1 and condition2 are FALSE
END IF;

This syntax is used to execute one set of statements if condition1 is TRUE, a different
set of statements when condition2 is TRUE or a third set of statements when both
condition1 and condition2 are false.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Lets take an example to understand the IF-THEN statement.

Example

DECLARE
a number(3) := 200;
BEGIN
-- check the boolean condition using if statement
IF( a < 10 ) THEN
-- if condition is true then print the following
dbms_output.put_line('a is less than 10 ' );
ELSE
dbms_output.put_line('a is not less than 10 ' );
END IF;
dbms_output.put_line('value of a is : ' || a);
END;

Output:
a is not less than 10
value of a is : 200

PL/SQL Case statement


The PL/SQL CASE Statement provides facility to execute a sequence of statements
based on a selector. A selector may be variable, function or an expression.

Syntax

CASE [expression]
WHEN condition1 THEN result1
WHEN condition2 THEN result2

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

…....................
WHEN condition_n THEN result_n
ELSE result
END;

Example

DECLARE
grade char(1) := 'C';
BEGIN
CASE grade
when 'A' then dbms_output.put_line('Distinction');
when 'B' then dbms_output.put_line('First class');
when 'C' then dbms_output.put_line('Second class');
when 'D' then dbms_output.put_line('Pass class');
else dbms_output.put_line('Failed');
END CASE;
END;
/

Output:
Second class

PL/SQL Loop

• Loops are iterative control statements.


• They are used to repeat execution of one or more statements for defined number of
times.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Syntax

LOOP
Sequence of statements;
END LOOP;

The four types of loops are:

1. PL/SQL Exit Loop

• It is used a set of statements is executed at least once before termination of loop.


• There should be an EXIT condition in the loop, otherwise the loop will get into an
infinite number of iterations.
Syntax

LOOP
Statements;
EXIT;
[or EXIT WHEN condition;]
END LOOP;

Lets take an example to understand Exit loop.

Example

DECLARE
i NUMBER := 1;
BEGIN
LOOP
EXIT WHEN i>5;
dbms_output.put_line(i);

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

i := i+1;
END LOOP;
END;

Output:
1
2
3
4
5

2. PL/SQL WHILE Loop

• It is used when a set of statements should be executed as long as condition is true.


• The condition is decided at the beginning of each iteration and continues until
condition becomes false.
Syntax

WHILE [condition]
LOOP Statements;
END LOOP;

Example

DECLARE
i INTEGER := 1;
BEGIN
WHILE i <= 5 LOOP
dbms_output.put_line(i);
i := i+1;

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

END LOOP;
END;

Output:
1
2
3
4
5

3. PL/SQL FOR Loop

• It is used to execute a set of statements for a fixed number of times.


• It is iterated between the start and end integer values.
Syntax

FOR counter IN initial_value .. final_value LOOP


LOOP statements;
END LOOP;

Example

BEGIN
FOR k IN 1..5 LOOP
dbms_output.put_line(k)
END LOOP;
END;

Output:
1
2
3
4

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

4. PL/SQL GOTO Statement


In PL/SQL, GOTO statement makes you able to get an unconditional jump from the
GOTO to a specific executable statement label in the same subprogram of the PL/SQL
block.

Syntax

I) GOTO label_name;

II) GOTO label_name;


…....
…....
<<label_name>>
Statement;

In the above syntax, the label declaration contains the label_name is encapsulated
within the << >> symbol and it should be followed by at least one statement to execute.

Lets take an example to understand how to use GOTO statement.

Example

DECLARE
a number(2) := 50;
BEGIN
<<loopstart>>
-- while loop execution
WHILE a < 60LOOP
dbms_output.put_line ('value of a: ' || a);

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

a := a + 1;
IF a = 55 THEN
a := a + 1;
GOTO loopstart;
END IF;
END LOOP;
END;
/

Output:
value of a: 50
value of a: 51
value of a: 52
value of a: 53
value of a: 54
value of a: 56
value of a: 57
value of a: 58
value of a: 59

Cursor function:

A cursor is a pointer to this context area. PL/SQL controls the context area
through a cursor. A cursor holds the rows (one or more) returned by a SQL
statement. The set of rows the cursor holds is referred to as the active set.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

You can name a cursor so that it could be referred to in a program to fetch and
process the rows returned by the SQL statement, one at a time. There are two types
of cursors −

• Implicit cursors
• Explicit cursors

Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement
is executed, when there is no explicit cursor for the statement. Programmers
cannot control the implicit cursors and the information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit
cursor is associated with this statement. For INSERT operations, the cursor holds
the data that needs to be inserted. For UPDATE and DELETE operations, the cursor
identifies the rows that would be affected.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor,
which always has attributes such as %FOUND, %ISOPEN, %NOTFOUND,
and %ROWCOUNT. The SQL cursor has additional
attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed for use
with the FORALL statement. The following table provides the description of the
most used attributes −

S.No Attribute & Description

%FOUND
1 Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more
rows or a SELECT INTO statement returned one or more rows. Otherwise, it returns
FALSE.

%NOTFOUND
2 The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE
statement affected no rows, or a SELECT INTO statement returned no rows.
Otherwise, it returns FALSE.

3 %ISOPEN

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.

%ROWCOUNT
4
Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement,
or returned by a SELECT INTO statement.

Any SQL cursor attribute will be accessed as sql%attribute_name as shown


below in the example.
Example
We will be using the CUSTOMERS table we had created and used in the previous
chapters.
Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
The following program will update the table and increase the salary of each
customer by 500 and use the SQL%ROWCOUNT attribute to determine the
number of rows affected −
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

END;
/
When the above code is executed at the SQL prompt, it produces the following
result −
6 customers selected

PL/SQL procedure successfully completed.


If you check the records in customers table, you will find that the rows have been
updated −
Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+

Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over
the context area. An explicit cursor should be defined in the declaration section
of the PL/SQL Block. It is created on a SELECT Statement which returns more than
one row.
The syntax for creating an explicit cursor is −
CURSOR cursor_name IS select_statement;
Working with an explicit cursor includes the following steps −

• Declaring the cursor for initializing the memory


• Opening the cursor for allocating the memory
• Fetching the cursor for retrieving the data
• Closing the cursor to release the allocated memory

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Declaring the Cursor


Declaring the cursor defines the cursor with a name and the associated SELECT
statement. For example −
CURSOR c_customers IS
SELECT id, name, address FROM customers;

Opening the Cursor


Opening the cursor allocates the memory for the cursor and makes it ready for
fetching the rows returned by the SQL statement into it. For example, we will open
the above defined cursor as follows −
OPEN c_customers;

Fetching the Cursor


Fetching the cursor involves accessing one row at a time. For example, we will
fetch rows from the above-opened cursor as follows −
FETCH c_customers INTO c_id, c_name, c_addr;

Closing the Cursor


Closing the cursor means releasing the allocated memory. For example, we will
close the above-opened cursor as follows −
CLOSE c_customers;
Example
Following is a complete example to illustrate the concepts of explicit cursors
&minua;
DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

END LOOP;
CLOSE c_customers;
END;
/
When the above code is executed at the SQL prompt, it produces the following
result −
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP

PL/SQL procedure successfully completed.

PL/SQL Procedure
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which
performs one or more specific tasks. It is just like procedures in other
programming languages.

The procedure contains a header and a body.

o Header: The header contains the name of the procedure and the
parameters or variables passed to the procedure.
o Body: The body contains a declaration section, execution section and
exception section similar to a general PL/SQL block.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

How to pass parameters in procedure:


When you want to create a procedure or function, you have to define parameters
.There is three ways to pass parameters in procedure:

1. IN parameters: The IN parameter can be referenced by the procedure or


function. The value of the parameter cannot be overwritten by the
procedure or the function.
2. OUT parameters: The OUT parameter cannot be referenced by the
procedure or function, but the value of the parameter can be overwritten by
the procedure or function.
3. INOUT parameters: The INOUT parameter can be referenced by the
procedure or function and the value of the parameter can be overwritten by
the procedure or function.

A procedure may or may not return any value.

PL/SQL Create Procedure


Syntax for creating procedure:

1. CREATE [OR REPLACE] PROCEDURE procedure_name


2. [ (parameter [,parameter]) ]
3. IS
4. [declaration_section]
5. BEGIN
6. executable_section
7. [EXCEPTION
8. exception_section]
9. END [procedure_name];

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Create procedure example


In this example, we are going to insert record in user table. So you need to create
user table first.

Table creation:

1. create table user(id number(10) primary key,name varchar2(100));

Now write the procedure code to insert record in user table.

Procedure Code:

1. create or replace procedure "INSERTUSER"


2. (id IN NUMBER,
3. name IN VARCHAR2)
4. is
5. begin
6. insert into user values(id,name);
7. end;
8. /

Output:
Procedure created.

PL/SQL program to call procedure


Let's see the code to call above created procedure.

1. BEGIN
2. insertuser(101,'Rahul');
3. dbms_output.put_line('record inserted successfully');
4. END;
5. /

Now, see the "USER" table, you will see one record is inserted.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

ID Name

101 Rahul

PL/SQL Drop Procedure


Syntax for drop procedure

DROP PROCEDURE procedure_name;

Example of drop procedure


DROP PROCEDURE pro1;

PL/SQL Function
The PL/SQL Function is very similar to PL/SQL Procedure. The main difference
between procedure and a function is, a function must always return a value, and
on the other hand a procedure may or may not return a value. Except this, all the
other things of PL/SQL procedure are true for PL/SQL function too.

Syntax to create a function:

1. CREATE [OR REPLACE] FUNCTION function_name [parameters]


2. [(parameter_name [IN | OUT | IN OUT] type [, ...])]
3. RETURN return_datatype
4. {IS | AS}
5. BEGIN
6. < function_body >
7. END [function_name];

Here:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

o Function_name: specifies the name of the function.


o [OR REPLACE] option allows modifying an existing function.
o The optional parameter list contains name, mode and types of the
parameters.
o IN represents that value will be passed from outside and OUT represents
that this parameter will be used to return a value outside of the procedure.

The function must contain a return statement.

o RETURN clause specifies that data type you are going to return from the
function.
o Function_body contains the executable part.
o The AS keyword is used instead of the IS keyword for creating a standalone
function.

PL/SQL Function Example


Let's see a simple example to create a function.

1. create or replace function adder(n1 in number, n2 in number)


2. return number
3. is
4. n3 number(8);
5. begin
6. n3 :=n1+n2;
7. return n3;
8. end;
9. /

Now write another program to call the function.

1. DECLARE

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

2. n3 number(2);
3. BEGIN
4. n3 := adder(11,22);
5. dbms_output.put_line('Addition is: ' || n3);
6. END;
7. /

Output:
Addition is: 33
Statement processed.
0.05 seconds

Another PL/SQL Function Example


Let's take an example to demonstrate Declaring, Defining and Invoking a simple
PL/SQL function which will compute and return the maximum of two values.

1. DECLARE
2. a number;
3. b number;
4. c number;
5. FUNCTION findMax(x IN number, y IN number)
6. RETURN number
7. IS
8. z number;
9. BEGIN
10. IF x > y THEN
11. z:= x;
12. ELSE
13. Z:= y;
14. END IF;
15.
16. RETURN z;

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

17.END;
18.BEGIN
19. a:= 23;
20. b:= 45;
21.
22. c := findMax(a, b);
23. dbms_output.put_line(' Maximum of (23,45): ' || c);
24.END;
25./

Output:
Maximum of (23,45): 45
Statement processed.
0.02 seconds

PL/SQL function example using table


Let's take a customer table. This example illustrates creating and calling a
standalone function. This function will return the total number of CUSTOMERS in
the customers table.

Create customers table and have records in it.

Customers

Id Name Department Salary

1 alex web developer 35000

2 ricky program developer 45000

3 mohan web designer 35000

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

4 dilshad database manager 44000

Create Function:

1. CREATE OR REPLACE FUNCTION totalCustomers


2. RETURN number IS
3. total number(2) := 0;
4. BEGIN
5. SELECT count(*) into total
6. FROM customers;
7. RETURN total;
8. END;
9. /

After the execution of above code, you will get the following result.
Function created.

Calling PL/SQL Function:

While creating a function, you have to give a definition of what the function has to
do. To use a function, you will have to call that function to perform the defined
task. Once the function is called, the program control is transferred to the called
function.

After the successful completion of the defined task, the call function returns
program control back to the main program.

To call a function you have to pass the required parameters along with function
name and if function returns a value then you can store returned value. Following
program calls the function totalCustomers from an anonymous block:

1. DECLARE
2. c number(2);
3. BEGIN
4. c := totalCustomers();

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

5. dbms_output.put_line('Total no. of Customers: ' || c);


6. END;
7. /

After the execution of above code in SQL prompt, you will get the following result.
Total no. of Customers: 4
PL/SQL procedure successfully completed.

PL/SQL Recursive Function


You already know that a program or a subprogram can call another subprogram.
When a subprogram calls itself, it is called recursive call and the process is known
as recursion.

Example to calculate the factorial of a number


Let's take an example to calculate the factorial of a number. This example
calculates the factorial of a given number by calling itself recursively.

1. DECLARE
2. num number;
3. factorial number;
4.
5. FUNCTION fact(x number)
6. RETURN number
7. IS
8. f number;
9. BEGIN
10. IF x=0 THEN
11. f := 1;
12. ELSE
13. f := x * fact(x-1);
14. END IF;
15.RETURN f;

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

16.END;
17.
18.BEGIN
19. num:= 6;
20. factorial := fact(num);
21. dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);
22.END;
23./

After the execution of above code at SQL prompt, it produces the following result.
Factorial 6 is 720
PL/SQL procedure successfully completed.

PL/SQL Drop Function


Syntax for removing your created function:

If you want to remove your created function from the database, you should use the
following syntax.

1. DROP FUNCTION function_name;

Packages:
Packages are schema objects that groups logically related PL/SQL types, variables,
and subprograms.
A package will have two mandatory parts −

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

• Package specification
• Package body or definition

Package Specification
The specification is the interface to the package. It just DECLARES the types,
variables, constants, exceptions, cursors, and subprograms that can be referenced
from outside the package. In other words, it contains all information about the
content of the package, but excludes the code for the subprograms.
All objects placed in the specification are called public objects. Any subprogram
not in the package specification but coded in the package body is called
a private object.
The following code snippet shows a package specification having a single
procedure. You can have many global variables defined and multiple procedures
or functions inside a package.
CREATE PACKAGE cust_sal AS
PROCEDURE find_sal(c_id customers.id%type);
END cust_sal;
/
When the above code is executed at the SQL prompt, it produces the following
result −
Package created.

Package Body
The package body has the codes for various methods declared in the package
specification and other private declarations, which are hidden from the code
outside the package.
The CREATE PACKAGE BODY Statement is used for creating the package body.
The following code snippet shows the package body declaration for
the cust_sal package created above. I assumed that we already have CUSTOMERS
table created in our database as mentioned in the PL/SQL - Variables chapter.
CREATE OR REPLACE PACKAGE BODY cust_sal AS

PROCEDURE find_sal(c_id customers.id%TYPE) IS


c_sal customers.salary%TYPE;
BEGIN
SELECT salary INTO c_sal

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

FROM customers
WHERE id = c_id;
dbms_output.put_line('Salary: '|| c_sal);
END find_sal;
END cust_sal;
/
When the above code is executed at the SQL prompt, it produces the following
result −
Package body created.

Using the Package Elements


The package elements (variables, procedures or functions) are accessed with the
following syntax −
package_name.element_name;
Consider, we already have created the above package in our database schema, the
following program uses the find_sal method of the cust_sal package −
DECLARE
code customers.id%type := &cc_id;
BEGIN
cust_sal.find_sal(code);
END;
/
When the above code is executed at the SQL prompt, it prompts to enter the
customer ID and when you enter an ID, it displays the corresponding salary as
follows −
Enter value for cc_id: 1
Salary: 3000

PL/SQL procedure successfully completed.


Example
The following program provides a more complete package. We will use the
CUSTOMERS table stored in our database with the following records −
Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

| 1 | Ramesh | 32 | Ahmedabad | 3000.00 |


| 2 | Khilan | 25 | Delhi | 3000.00 |
| 3 | kaushik | 23 | Kota | 3000.00 |
| 4 | Chaitali | 25 | Mumbai | 7500.00 |
| 5 | Hardik | 27 | Bhopal | 9500.00 |
| 6 | Komal | 22 | MP | 5500.00 |
+----+----------+-----+-----------+----------+
The Package Specification
CREATE OR REPLACE PACKAGE c_package AS
-- Adds a customer
PROCEDURE addCustomer(c_id customers.id%type,
c_name customers.Name%type,
c_age customers.age%type,
c_addr customers.address%type,
c_sal customers.salary%type);

-- Removes a customer
PROCEDURE delCustomer(c_id customers.id%TYPE);
--Lists all customers
PROCEDURE listCustomer;

END c_package;
/
When the above code is executed at the SQL prompt, it creates the above package
and displays the following result −
Package created.
Creating the Package Body
CREATE OR REPLACE PACKAGE BODY c_package AS
PROCEDURE addCustomer(c_id customers.id%type,
c_name customers.Name%type,
c_age customers.age%type,
c_addr customers.address%type,
c_sal customers.salary%type)
IS
BEGIN
INSERT INTO customers (id,name,age,address,salary)
VALUES(c_id, c_name, c_age, c_addr, c_sal);
END addCustomer;

PROCEDURE delCustomer(c_id customers.id%type) IS


BEGIN
DELETE FROM customers

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

WHERE id = c_id;
END delCustomer;

PROCEDURE listCustomer IS
CURSOR c_customers is
SELECT name FROM customers;
TYPE c_list is TABLE OF customers.Name%type;
name_list c_list := c_list();
counter integer :=0;
BEGIN
FOR n IN c_customers LOOP
counter := counter +1;
name_list.extend;
name_list(counter) := n.name;
dbms_output.put_line('Customer(' ||counter|| ')'||name_list(counter));
END LOOP;
END listCustomer;

END c_package;
/
The above example makes use of the nested table. We will discuss the concept of
nested table in the next chapter.
When the above code is executed at the SQL prompt, it produces the following
result −
Package body created.
Using The Package
The following program uses the methods declared and defined in the
package c_package.
DECLARE
code customers.id%type:= 8;
BEGIN
c_package.addcustomer(7, 'Rajnish', 25, 'Chennai', 3500);
c_package.addcustomer(8, 'Subham', 32, 'Delhi', 7500);
c_package.listcustomer;
c_package.delcustomer(code);
c_package.listcustomer;
END;
/
When the above code is executed at the SQL prompt, it produces the following
result −

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Customer(1): Ramesh
Customer(2): Khilan
Customer(3): kaushik
Customer(4): Chaitali
Customer(5): Hardik
Customer(6): Komal
Customer(7): Rajnish
Customer(8): Subham
Customer(1): Ramesh
Customer(2): Khilan
Customer(3): kaushik
Customer(4): Chaitali
Customer(5): Hardik
Customer(6): Komal
Customer(7): Rajnish

PL/SQL procedure successfully completed

Exception Handling
An exception is an error condition during a program execution. PL/SQL supports
programmers to catch such conditions using EXCEPTION block in the program
and an appropriate action is taken against the error condition. There are two types
of exceptions −

• System-defined exceptions
• User-defined exceptions

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Syntax for Exception Handling


The general syntax for exception handling is as follows. Here you can list down as
many exceptions as you can handle. The default exception will be handled
using WHEN others THEN −
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
WHEN others THEN
exception3-handling-statements
END;
Example
Let us write a code to illustrate the concept. We will be using the CUSTOMERS table
we had created and used in the previous chapters −
DECLARE
c_id customers.id%type := 8;
c_name customerS.Name%type;
c_addr customers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);

EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

/
When the above code is executed at the SQL prompt, it produces the following
result −
No such customer!

PL/SQL procedure successfully completed.


The above program displays the name and address of a customer whose ID is
given. Since there is no customer with ID value 8 in our database, the program
raises the run-time exception NO_DATA_FOUND, which is captured in
the EXCEPTION block.

Raising Exceptions
Exceptions are raised by the database server automatically whenever there is any
internal database error, but exceptions can be raised explicitly by the programmer
by using the command RAISE. Following is the simple syntax for raising an
exception −
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;
You can use the above syntax in raising the Oracle standard exception or any user-
defined exception. In the next section, we will give you an example on raising a
user-defined exception. You can raise the Oracle standard exceptions in a similar
way.

User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your
program. A user-defined exception must be declared and then raised explicitly,
using either a RAISE statement or the
procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.
The syntax for declaring an exception is −

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

DECLARE
my-exception EXCEPTION;
Example
The following example illustrates the concept. This program asks for a customer
ID, when the user enters an invalid ID, the exception invalid_id is raised.
DECLARE
c_id customers.id%type := &cc_id;
c_name customerS.Name%type;
c_addr customers.address%type;
-- user defined exception
ex_invalid_id EXCEPTION;
BEGIN
IF c_id <= 0 THEN
RAISE ex_invalid_id;
ELSE
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
END IF;

EXCEPTION
WHEN ex_invalid_id THEN
dbms_output.put_line('ID must be greater than zero!');
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
When the above code is executed at the SQL prompt, it produces the following
result −
Enter value for cc_id: -6 (let's enter a value -6)
old 2: c_id customers.id%type := &cc_id;
new 2: c_id customers.id%type := -6;
ID must be greater than zero!

PL/SQL procedure successfully completed.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Pre-defined Exceptions
PL/SQL provides many pre-defined exceptions, which are executed when any
database rule is violated by a program. For example, the predefined exception
NO_DATA_FOUND is raised when a SELECT INTO statement returns no rows. The
following table lists few of the important pre-defined exceptions −

Oracle
Exception SQLCODE Description
Error

It is raised when a null object is automatically


ACCESS_INTO_NULL 06530 -6530
assigned a value.

It is raised when none of the choices in the


CASE_NOT_FOUND 06592 -6592 WHEN clause of a CASE statement is selected,
and there is no ELSE clause.

It is raised when a program attempts to apply


collection methods other than EXISTS to an
uninitialized nested table or varray, or the
COLLECTION_IS_NULL 06531 -6531
program attempts to assign values to the
elements of an uninitialized nested table or
varray.

It is raised when duplicate values are attempted


DUP_VAL_ON_INDEX 00001 -1
to be stored in a column with unique index.

It is raised when attempts are made to make a


INVALID_CURSOR 01001 -1001 cursor operation that is not allowed, such as
closing an unopened cursor.

It is raised when the conversion of a character


INVALID_NUMBER 01722 -1722 string into a number fails because the string does
not represent a valid number.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

It is raised when a program attempts to log on to


LOGIN_DENIED 01017 -1017 the database with an invalid username or
password.

It is raised when a SELECT INTO statement


NO_DATA_FOUND 01403 +100
returns no rows.

It is raised when a database call is issued without


NOT_LOGGED_ON 01012 -1012
being connected to the database.

It is raised when PL/SQL has an internal


PROGRAM_ERROR 06501 -6501
problem.

It is raised when a cursor fetches value in a


ROWTYPE_MISMATCH 06504 -6504
variable having incompatible data type.

It is raised when a member method is invoked,


SELF_IS_NULL 30625 -30625 but the instance of the object type was not
initialized.

It is raised when PL/SQL ran out of memory or


STORAGE_ERROR 06500 -6500
memory was corrupted.

It is raised when a SELECT INTO statement


TOO_MANY_ROWS 01422 -1422
returns more than one row.

It is raised when an arithmetic, conversion,


VALUE_ERROR 06502 -6502
truncation, or sizeconstraint error occurs.

It is raised when an attempt is made to divide a


ZERO_DIVIDE 01476 1476
number by zero.

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

Triggers
Triggers are stored programs, which are automatically executed or fired when
some events occur. Triggers are, in fact, written to be executed in response to any
of the following events −
• A database manipulation (DML) statement (DELETE, INSERT, or
UPDATE)
• A database definition (DDL) statement (CREATE, ALTER, or DROP).
• A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the
event is associated.
Benefits of Triggers
Triggers can be written for the following purposes −

• Generating some derived column values automatically


• Enforcing referential integrity
• Event logging and storing information on table access
• Auditing
• Synchronous replication of tables
• Imposing security authorizations
• Preventing invalid transactions

Creating Triggers
The syntax for creating a trigger is −
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

EXCEPTION
Exception-handling-statements
END;
Where,
• CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an
existing trigger with the trigger_name.
• {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be
executed. The INSTEAD OF clause is used for creating trigger on a view.
• {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
• [OF col_name] − This specifies the column name that will be updated.
• [ON table_name] − This specifies the name of the table associated with the
trigger.
• [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old
values for various DML statements, such as INSERT, UPDATE, and DELETE.
• [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be
executed for each row being affected. Otherwise the trigger will execute just
once when the SQL statement is executed, which is called a table level
trigger.
• WHEN (condition) − This provides a condition for rows for which the trigger
would fire. This clause is valid only for row-level triggers.
Example
To start with, we will be using the CUSTOMERS table we had created and used in
the previous chapters −
Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
The following program creates a row-level trigger for the customers table that
would fire for INSERT or UPDATE or DELETE operations performed on the
CUSTOMERS table. This trigger will display the salary difference between the old
values and new values −

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

CREATE OR REPLACE TRIGGER display_salary_changes


BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/
When the above code is executed at the SQL prompt, it produces the following
result −
Trigger created.
The following points need to be considered here −
• OLD and NEW references are not available for table-level triggers, rather
you can use them for record-level triggers.
• If you want to query the table in the same trigger, then you should use the
AFTER keyword, because triggers can query the table or change it again
only after the initial changes are applied and the table is back in a consistent
state.
• The above trigger has been written in such a way that it will fire before any
DELETE or INSERT or UPDATE operation on the table, but you can write
your trigger on a single or multiple operations, for example BEFORE
DELETE, which will fire whenever a record will be deleted using the
DELETE operation on the table.

Triggering a Trigger
Let us perform some DML operations on the CUSTOMERS table. Here is one
INSERT statement, which will create a new record in the table −
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (7, 'Kriti', 22, 'HP', 7500.00 );
When a record is created in the CUSTOMERS table, the above create
trigger, display_salary_changes will be fired and it will display the following
result −
Old salary:

Downloaded by Ganta Rojamani ([email protected])


lOMoARcPSD|51615745

New salary: 7500


Salary difference:
Because this is a new record, old salary is not available and the above result comes
as null. Let us now perform one more DML operation on the CUSTOMERS table.
The UPDATE statement will update an existing record in the table −
UPDATE customers
SET salary = salary + 500
WHERE id = 2;
When a record is updated in the CUSTOMERS table, the above create
trigger, display_salary_changes will be fired and it will display the following
result −
Old salary: 1500
New salary: 2000
Salary difference: 500

Downloaded by Ganta Rojamani ([email protected])

You might also like