You are on page 1of 160

DATABASE

MANAGEMENT
SYSTEMS
(22319)
Department of Computer Engineering

Prepared By: Mr. Hitesh Mhatre

PRAVIN PATIL COLLEGE OF DIPLOMA ENGINEERING AND TECHNOLOGY


Mahavidyalaya Marg, Navghar Road, Bhayander East, 401105
1
Database Management Systems – 22319 CO-3I

Unit – I: Database System Concepts

Course Outcomes (COs):

 Design normalized database on given data.

Unit Outcomes (UOs):

 State the importance of DBMS over file processing in the given situation.
 Describe the overall structure of the given DBMS
 Identify the relevant database model in the given situation.
 Draw the E-R diagram of the given database and identify relationship between the
entities.

1.1 Data:
 Data is nothing but the information which is having implicit meaning.
 Data is a set of values of qualitative or quantitative variables about one or more objects.
 It is facts and statistics collected together for reference or analysis.

1.2 Database:
 A database is a collection of information that is organized so that it can be easily
accessed, managed and updated.

1.3 Database Management System (DBMS):


 A database management system (DBMS) is system software for creating and
managing databases. A DBMS makes it possible for end users to create, read, update
and delete data in a database.

1.4 Primary Goal of Database Management System:


 Primary goal of database management system is to provide a way to store and
retrieve database information that is convenient and efficient.
 Management of data involves both defining structure for storage of information and
providing mechanism for manipulation of information.

Prof. Hitesh Mhatre 1-1


Database Management Systems – 22319 CO-3I

1.5 Services provided by DBMS:


1. Define the structure. (Creation of Database)
2. Manage the storage.
3. Manipulate the database. (Insert, Update, Delete, etc. from/into Database)
4. Manage database usage. (Give rights to users to access database and optimize process)
5. Monitor and analyze database usage.
6. Performing tuning and maintenance of database.

1.6 Application Areas of Database Management System:

Sector Use of DBMS

Banking For customer information, account activities, payments, deposits,


loans, etc.

Airlines For reservations and schedule information.

Universities For student information, course registrations, colleges and grades.

Telecommunication It helps to keep call records, monthly bills, maintaining balances,


etc.

Finance For storing information about stock, sales, and purchases of


financial instruments like stocks and bonds.

Sales Use for storing customer, product & sales information.

Manufacturing It is used for the management of supply chain and for tracking
production of items. Inventories status in warehouses.

HR Management For information about employees, salaries, payroll, deduction,


generation of paychecks, etc.

1.7 Disadvantages of File Processing System:


1.7.1 Data redundancy and inconsistency:
 The data files and application programs are created by different programmers over a
long period.
 The data files are likely to have different formats.
 Programs may be written in several programming languages.
 The same information may be duplicated in several files.
Prof. Hitesh Mhatre 1-2
Database Management Systems – 22319 CO-3I

 Example: Information of student like roll number, class, division, name, etc. is
repeated in student details file system and library details file system.
 Duplication of data results in data redundancy.
 Data redundancy increases the cost of storing and retrieving the data.
 If some update is done on these database and if the values of these common fields are
not matching for some records in both files, then it results in inconsistent data.

1.7.2 Difficulty in accessing data:


 Conventional file processing system does not allow required data to be retrieved in
convenient and efficient manner.
 Example:
 This makes accessing of data difficult.

1.7.3 Data isolation:


 As data is scattered in various files and files may be in different format and different
location, it is difficult to write new application program to retrieve appropriate
information.

1.7.4 Integrating problem:


 The data stored in database must satisfy certain type of consistency constraints.
 Example: Suppose University maintains results records for various departments.
University may require that the percentage data to be between 0 – 100. Developers will
add constraints by adding appropriate code in the application programs which will
check if marks are entered in proper range.
 But, when the new constraints are added, it is difficult to change the program to enforce
them.

1.7.5 Atomicity problem:


 A computer system like any other device is subject to failure.
 In many applications, it is crucial that if a failure occurs the data be stored to consistent
state that existed prior to failure.
 Example: A transaction is a monetary transfer from Account A to B. It consists of
operations such as withdrawing from A and depositing to B. But during this process,
there is a power failure for few seconds and transaction is terminated. It may happen
that amount is withdrawn from A but not deposited in B.
 This is atomicity problem.

Prof. Hitesh Mhatre 1-3


Database Management Systems – 22319 CO-3I

1.7.6 Concurrent access anomalies:


 For overall performance of the system and faster response many system allow multiple
users to update the data simultaneously.
 In such situation, concurrent update is possible but it may result in inconsistent data.
 Example: Consider inventory database where it shows remaining stocks (say 40 items).
Now 2 customers try to book 20 and 30 items concurrently. Since total requirement is
more than the remaining stock, so one of the transaction couldn’t complete. But both
can see 40 as available stock, this will result in wrong data to accessed by user.

1.7.7 Security problem:


 Not every user of the database system should be able to access all the data.
 Example: In University, payroll personnel need to see only the part of database that
has financial information. They do not need to access the information of academics.
But in file processing system, it is difficult to assign such constraints.

1.8 Data Abstraction:


 Abstraction means hiding the complexity of the data and showing relevant information.
 A major purpose of database system is to provide users with an abstract view of data,
which means the system hides certain details of how the data are stored and maintained.
 Developers hide the complexity from user through several levels of abstraction to
simplify user’s interaction with the system.
 Following figure shows different levels of abstraction

Figure 1: Levels of Abstraction

Prof. Hitesh Mhatre 1-4


Database Management Systems – 22319 CO-3I

1.8.1 Physical Level:


 The lowest level of abstraction describes how the data are actually stored and
how to retrieve those data.

1.8.2 Logical Level:


 The next higher level of abstraction describes what data are stored in database
and what relationship exists among those data.

1.8.3 View Level:


 The highest level of abstraction describes only part of database.
 Many users of the database system do not need all the information of database instead
they need to access only part of database.

1.9 Advantages of DBMS:


1.9.1 Improved data sharing:
 DBMS helps to create an environment in which end users have better access to more
and better managed data.
 Such access makes it possible for end users to responds quickly to changes in their
environment.

1.9.2 Improved data security:


 The more users access the data, the greater the risks of data security breaches.
 Corporations invests considerable amount of time, efforts and money to ensure the data
is used properly.
 It provides the framework for better enforcement of data privacy and security policies.

1.9.3 Better data integration:


 Wider access to well-managed data promotes an integrated view of organizations
operations and view of big picture.
 It becomes much easier to see how actions in one segment of company affects other
segments.

1.9.4 Controlling data redundancy:


 All data of an organization is integrated into single database file.
 The data is recorded in only one place in the database and it is not duplicated.
Prof. Hitesh Mhatre 1-5
Database Management Systems – 22319 CO-3I

1.9.5 Data consistency:


 Data consistency exists when different versions of same data appear in different places.

1.9.6 Data atomicity:


 Any complete transaction in database is called atomic unit.
 DBMS complete the transaction, if any transaction is partially completed than it will
roll back to the consistent state.

1.9.7 Data concurrency:


 Concurrent access to data means more than one user is accessing the same data at the
same time.
 Anomalies occur when changes made by one user get lost because of changes made by
other user.
 File system does not provide any procedure to stop anomalies, whereas DBMS provides
a locking system to stop anomalies to occur.

1.10 Instances and Schemas:


 Instance: The value of a variable in the program at a point of time corresponds to an
instance of the database schema. (Data stored in database at particular moment)
 Schema: Overall design of the database is known as database schema.

1.11 Data Independence:


 The capacity to change the schema definition in one level of database system without
having to change the schema definition of the next higher level is called as data
independence.
 There are two types of data independence – logical and physical data independence.

 Logical data independence: It is the capacity to change the logical schema (conceptual
schema) without having to change external schema or application program.

 Physical data independence: It is the capacity to change internal schema without


having to change logical schema (conceptual schema) and external schema.

Prof. Hitesh Mhatre 1-6


Database Management Systems – 22319 CO-3I

1.12 Components of Database Management System:


 The database management system can be divided in 5 major components – Hardware,
Software, Procedure, Database Access Language and Data.
 Hardware: There are various hardware in computer system – hard disk, I/O channel
for data, any other physical component. When we run Oracle or MySQL on the system
and we use keyboard, hard disk, RAM, ROM, etc. while typing commands. Thus, all
become part of DBMS.
 Software: This is the main components as this is the program which controls
everything. The DBMS software is more like a wrapper around the physical database
which provides easy to use interface to store, access and update. The DBMS software
is capable of understanding the database access language and interpret it into actual
database commands to execute them on database.
 Data: It is that resource for which DBMS is designed. The motivation behind creation
of DBMS was to store and utilize the data.
 Procedure: It is referred to general instructions to use a DBMS. These includes
procedures to set-up and install a DBMS, to log-in and log-out of DBMS, to manage
databases, to take backups and generating reports, etc.
 Database Access Languages: It is a simple language designed to write commands
to access, insert, update and delete data stored in any database.

1.13 Database Users:


 Four different types of database users are Naïve Users, Application Programmers,
Sophisticated Users and Specialized Users

 Naïve Users: They are unsophisticated user to interact with system by using pre-
developed application program.

 Application Programmers: They are computer professional who interact with the
system through Data Manipulation Language calls. DBMS calls which are embedded
in a program written in a host system language.

 Sophisticated Users: They interact with system without writing programs instead
they form their request in a database query language.

 Specialized Users: They are also sophisticated users who writes specialized databases
applications that do not fit in traditional data processing unit.

Prof. Hitesh Mhatre 1-7


Database Management Systems – 22319 CO-3I

1.14 Database Architecture:

Figure 2: Database Architecture

Query Processor:
 As query is very much necessary to find out only the data user need from tons of data
of the database, query processor is very important to process these query requests.
 Query processors come with the following components,
1. DDL Interpreter: It interprets the DDL statements and records the definitions in
data dictionary.
2. DML Compiler: It translates the DML statements in a query language into an
evaluation plan consisting of low-level instructions that the query evaluation
understands. It also performs query optimization which actually picks up the lowest
cost evaluation plan from various alternatives.
3. Query Evaluation Engine: It executes the low level instruction compiled by the
DML compiler.

Prof. Hitesh Mhatre 1-8


Database Management Systems – 22319 CO-3I

Storage Manager:
 A storage manager is a program module which is responsible for storing, retrieving and
updating data in the database.
 Following are the components of the storage manager;
1. Authorization and Integrity Manager: It tests the integrity constraints and checks
the authorization of users to access data.
2. Transaction Manager: It ensures that no kind of change will be brought to the
database until a transaction has been completed totally.
3. File Manager: It manages the allocation of space on disk storage and the data
structures used to represent information stored on disk.
4. Buffer Manager: It decides which data is in need to be cached in main memory
and then fetch it up in main memory. This is very important as it defines the speed
in which the database can be used.

Data Structures Implemented by the Storage Manager:


 The storage manager implements several data structures as part of the physical system
implementation.
1. Data Files: It stores the database itself.
2. Data Dictionary: It stores metadata about the structures of the database, in particular
schema of the database.
3. Indices: It can provide fast access to data items. It provides pointers to those data items
that hold a particular value.

1.15 Data Modeling:


 Data modeling (data modelling) is the process of creating a data model for the data to
be stored in a Database.
 This data model is a conceptual representation of Data objects, the associations between
different data objects and the rules.
 Data modeling helps in the visual representation of data and enforces business rules,
regulatory compliances, and government policies on the data.
 Data Models ensure consistency in naming conventions, default values, semantics, and
security while ensuring quality of the data.
 Data model emphasizes on what data is needed and how it should be organized instead
of what operations need to be performed on the data.
 Data Model is like architect's building plan which helps to build a conceptual model
and set the relationship between data items.
 The primary goal of using data model are:
o Ensures that all data objects required by the database are accurately represented.
Omission of data will lead to creation of faulty reports and produce incorrect
results.

Prof. Hitesh Mhatre 1-9


Database Management Systems – 22319 CO-3I

o A data model helps design the database at the conceptual, physical and logical
levels.
o Data Model structure helps to define the relational tables, primary and foreign
keys and stored procedures.
o It provides a clear picture of the base data and can be used by database
developers to create a physical database.
o It is also helpful to identify missing and redundant data.
o Though the initial creation of data model is labor and time consuming, in the
long run, it makes your IT infrastructure upgrade and maintenance cheaper and
faster.

1.16 Hierarchical Model:


 A hierarchical model represents the data in a tree-like structure in which there is a single
parent for each record.
 To maintain order there is a sort field which keeps sibling nodes into a recorded manner.
 These types of models are designed basically for the early mainframe database
management systems, like the Information Management System (IMS) by IBM.
 This model structure allows the one-to-one and a one-to-many relationship between
two/ various types of data.
 This structure is very helpful in describing many relationships in the real world; table
of contents, any nested and sorted information.
 The hierarchical structure is used as the physical order of records in storage.
 One can access the records by navigating down through the data structure using pointers
which are combined with sequential accessing. Therefore, the hierarchical structure is
not suitable for certain database operations when a full path is not also included for
each record.
 Data in this type of database is structured hierarchically and is typically developed as
an inverted tree. The "root" in the structure is a single table in the database and other
tables act as the branches flowing from the root.
 The diagram below shows a typical hierarchical database structure.

Figure 3: Hierarchical Model

Prof. Hitesh Mhatre 1-10


Database Management Systems – 22319 CO-3I

Advantages:
 A user can retrieve data very quickly due to the presence of explicit links between the
table structures.
 The referential integrity is built in and automatically enforced due to which a record in
a child table must be linked to an existing record in a parent table, along with that if a
record deleted in the parent table then that will cause all associated records in the child
table to be deleted as well.

Disadvantages:
 When a user needs to store a record in a child table that is currently unrelated to any
record in a parent table, it gets difficulty in recording and user must record an additional
entry in the parent table.
 This type of database cannot support complex relationships, and there is also a problem
of redundancy, which can result in producing inaccurate information due to the
inconsistent recording of data at various sites.

1.17 Network Model:


 The network model is the extension of the hierarchical structure because it allows
many-to-many relationships to be managed in a tree-like structure that allows multiple
parents.
 There are two fundamental concepts of a network model −
o Records contain fields which need hierarchical organization.
o Sets are used to define one-to-many relationships between records that contain
one owner, many members.
 A record may act as an owner in any number of sets, and a member in any number of
sets.
 A set is designed with the help of circular linked lists where one record type, the owner
of the set also called as a parent, appears once in each circle, and a second record type,
also known as the subordinate or child, may appear multiple times in each circle.
 A hierarchy is established between any two record types where one type (A) is the
owner of another type (B). At the same time, another set can be developed where the
latter set (B) is the owner of the former set (A). In this model, ownership is defined by
the direction, thus all the sets comprise a general directed graph.
 Access to records is developed by the indexing structure of circular linked lists.
 The network model has the following major features:
 It can represent redundancy in data more efficiently than that in the hierarchical
model.
 There can be more than one path from a previous node to successor node/s.
 The operations of the network model are maintained by indexing structure of
linked list (circular) where a program maintains a current position and navigates

Prof. Hitesh Mhatre 1-11


Database Management Systems – 22319 CO-3I

from one record to another by following the relationships in which the record
participates.
 Records can also be located by supplying key values.
 The following diagram depicts a network model. An agent represents several clients
and manages several entertainers. Each client schedules any number of engagements
and makes payments to the agent for his or her services. Each entertainer performs
several engagements and may play a variety of musical styles.

Figure 4: Network Model

Advantages:
 Fast data access.
 It also allows users to create queries that are more complex than those they created
using a hierarchical database. So, a variety of queries can be run over this model.

Disadvantages:
 A user must be very familiar with the structure of the database to work through the set
structures.
 Updating inside this database is a tedious task. One cannot change a set structure
without affecting the application programs that use this structure to navigate through
the data. If you change a set structure, you must also modify all references made from
within the application program to that structure.

1.18 Client Server Model:


 It is a network architecture in which every computer or process on the network is either
client or server.
 Servers are powerful computers and processes dedicated to managing disk drives (file
servers), or network servers.

Prof. Hitesh Mhatre 1-12


Database Management Systems – 22319 CO-3I

Figure 5: Client-Server Model

Advantages:
 Improved data sharing: Data is retained by usual business process and manipulated
on a server is available for designated users (clients) over an authorized access.
 Integration of services: Every client is given the opportunity to access corporate
information via desktop interface eliminating the necessity to log into a terminal node
or process.
 Easy maintenance: In distributed model, responsibilities are dispersed among
independent computers integrated across a network. Therefore, it is easy to replace,
repair, upgrade and relocate a server while clients remain unaffected.
 Security: Servers have better control access and resources to ensure that only
authorized clients can access or manipulate data and server updates are administered
effectively.

Disadvantages:
 Overloaded Servers: When there are frequent simultaneous client requests, server
services get overloaded forming traffic congestion.
 Impact of Centralized Architecture: Since, it is centralized, if the critical server fails,
client’s requests are not accomplished. Therefore, client-servers lacks the robustness of
the good network.

A. Two tier architecture

Figure 6: Two-Tier Architecture

Prof. Hitesh Mhatre 1-13


Database Management Systems – 22319 CO-3I

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

B. Three tier architecture

Figure 7: Three-Tier Architecture

 In three-tier architecture, another layer is present between the client machine and server
machine.
 In this architecture, the client application doesn’t communicate directly with the
database systems present at the server machine, rather the client application
communicates with server application and the server application internally
communicates with the database system present at the server.

1.19 Entity-Relationship Model:


 The ER model defines the conceptual view of a database. It works around real-world
entities and the associations among them. At view level, the ER model is considered a
good option for designing databases.

Entity:
 An entity can be a real-world object, either animate or inanimate, that can be easily
identifiable.
 For example, in a school database, students, teachers, classes, and courses offered can
be considered as entities.

Prof. Hitesh Mhatre 1-14


Database Management Systems – 22319 CO-3I

 All these entities have some attributes or properties that give them their identity.
 An entity set is a collection of similar types of entities. An entity set may contain
entities with attribute sharing similar values.
 For example, a Students set may contain all the students of a school; likewise a
Teachers set may contain all the teachers of a school from all faculties.

Strong Entity:
 A strong entity is not dependent of any other entity in the schema. A strong entity will
always have a primary key.

Weak Entity:
 A weak entity is an entity that cannot be uniquely identified by its attributes alone;
therefore, it must use a foreign key in conjunction with its attributes to create a primary
key.
 For example: a ROOM can only exist in a BUILDING. On the other hand, a TIRE might
be considered as a strong entity because it also can exist without being attached to
a CAR.

Attributes and its types:


 Entities are represented by means of their properties, called attributes.
 All attributes have values. For example, a student entity may have name, class, and age
as attributes.
 There exists a domain or range of values that can be assigned to attributes. For example,
a student's name cannot be a numeric value. It has to be alphabetic. A student's age
cannot be negative, etc.
 Types of Attributes:
 Simple attribute − Simple attributes are atomic values, which cannot be
divided further. For example, a student's phone number is an atomic value of
10 digits.

 Composite attribute − Composite attributes are made of more than one simple
attribute. For example, a student's complete name may have first_name and
last_name.

 Derived attribute − Derived attributes are the attributes that do not exist in the
physical database, but their values are derived from other attributes present in
the database. For example, average_salary in a department should not be saved
directly in the database, instead it can be derived. For another example, age can
be derived from data_of_birth.

Prof. Hitesh Mhatre 1-15


Database Management Systems – 22319 CO-3I

 Single-value attribute − Single-value attributes contain single value. For


example − Aadhar_Number.

 Multi-value attribute − Multi-value attributes may contain more than one


values. For example, a person can have more than one phone number,
email_address, etc.
 These attribute types can come together in a way like −
 simple single-valued attributes
 simple multi-valued attributes
 composite single-valued attributes
 composite multi-valued attributes

Relationship:
 The association among entities is called a relationship.
 For example, an employee works_at a department, a student enrolls in a course. Here,
works_at and enrolls are called relationships.

Relationship Set:
 A set of relationships of similar type is called a relationship set.
 Like entities, a relationship too can have attributes.
 These attributes are called descriptive attributes.

Degree of Relationship:
 The number of participating entities in a relationship defines the degree of the
relationship.
o Binary = degree 2
o Ternary = degree 3
o n-ary = degree N

Mapping Cardinalities:
 Cardinality defines the number of entities in one entity set, which can be associated
with the number of entities of other set via relationship set.
 One-to-one − One entity from entity set A can be associated with at most one entity
of entity set B and vice versa.

Prof. Hitesh Mhatre 1-16


Database Management Systems – 22319 CO-3I

Figure 8: One to One Mapping

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

Figure 9: One to Many Mapping

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

Figure 10: Many to One Mapping

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

Prof. Hitesh Mhatre 1-17


Database Management Systems – 22319 CO-3I

Figure 11: Many to Many Mapping

1.20 E-R Diagrams:


 Any object, for example, entities, attributes of an entity, relationship sets, and attributes
of relationship sets, can be represented with the help of an ER diagram.
1.20.1 Entity:
 Entities are represented by means of rectangles. Rectangles are named with the entity
set they represent.

Figure 12: Entity

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

Figure 13: Attributes

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

Prof. Hitesh Mhatre 1-18


Database Management Systems – 22319 CO-3I

Figure 14: Composite Attributes

 Multivalued attributes are depicted by double ellipse.

Figure 15: Multivalued Attributes

 Derived attributes are depicted by dashed ellipse.

Figure 16: Derived Attributes

Prof. Hitesh Mhatre 1-19


Database Management Systems – 22319 CO-3I

1.20.3 Relationship:
 Relationships are represented by diamond-shaped box. Name of the relationship is
written inside the diamond-box. All the entities (rectangles) participating in a
relationship, are connected to it by a line.
Binary Relationship and Cardinality
 A relationship where two entities are participating is called a binary relationship.
Cardinality is the number of instance of an entity from a relation that can be associated
with the relation.
 One-to-one: When only one instance of an entity is associated with the relationship,
it is marked as '1:1'. The following image reflects that only one instance of each entity
should be associated with the relationship. It depicts one-to-one relationship.

Figure 17: One to One Relationship

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


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

Figure 18: One to Many Relationship

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

Figure 19: Many to One Relationship

Prof. Hitesh Mhatre 1-20


Database Management Systems – 22319 CO-3I

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

Figure 20: Many to Many Relationship

1.20.4 Participation Constraints:


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

Figure 21: Total and Partial Participation

 The ER Model has the power of expressing database entities in a conceptual


hierarchical manner.
 As the hierarchy goes up, it generalizes the view of entities, and as we go deep in the
hierarchy, it gives us the detail of every entity included.
 Going up in this structure is called generalization, where entities are clubbed together
to represent a more generalized view.
 For example, a particular student named Mira can be generalized along with all the
students. The entity shall be a student, and further, the student is a person. The reverse
is called specialization where a person is a student, and that student is Mira.

1.21 Generalization:
 As mentioned above, the process of generalizing entities, where the generalized
entities contain the properties of all the generalized entities, is called generalization.
 In generalization, a number of entities are brought together into one generalized entity
based on their similar characteristics.
 For example, pigeon, house sparrow, crow and dove can all be generalized as Birds.

Prof. Hitesh Mhatre 1-21


Database Management Systems – 22319 CO-3I

Figure 22: Generalization

1.22 Specialization:
 Specialization is the opposite of generalization. In specialization, a group of entities is
divided into sub-groups based on their characteristics.
 Take a group ‘Person’ for example. A person has name, date of birth, gender, etc.
These properties are common in all persons, human beings. But in a company, persons
can be identified as employee, employer, customer, or vendor, based on what role they
play in the company.

Figure 23: Specialization

 Similarly, in a school database, persons can be specialized as teacher, student, or a


staff, based on what role they play in school as entities.

1.23 Inheritance
 We use all the above features of ER-Model in order to create classes of objects in
object-oriented programming.
 The details of entities are generally hidden from the user; this process known
as abstraction.
 Inheritance is an important feature of Generalization and Specialization.
 It allows lower-level entities to inherit the attributes of higher-level entities.

Prof. Hitesh Mhatre 1-22


Database Management Systems – 22319 CO-3I

Figure 24: Inheritance

 For example, the attributes of a Person class such as name, age, and gender can be
inherited by lower-level entities such as Student or Teacher.

1.24 E-R Diagram Examples

Figure 25: E-R Diagram - Library Management System

Prof. Hitesh Mhatre 1-23


Database Management Systems – 22319 CO-3I

Figure 26: E-R Diagram - Hospital Management System

Figure 27: E-R Diagram-Hotel Management System

Prof. Hitesh Mhatre 1-24


Database Management Systems – 22319 CO-3I

Unit – II: Relational Data Model

Course Outcomes (COs):

 Create and manage database using SQL command.

Unit Outcomes (UOs):

 Explain the concept of RDBMS also appropriateness for the given problem.
 Design normalized database structure in the given problem.
 Design SQL queries to create relational database and apply in the given data
constraints.
 Identify the operators for queries implementation of the given problem.

2.1 Fundamentals of RDBMS:


 Relational data model is the primary data model, which is used widely around the world
for data storage and processing.
 This model is simple and it has all the properties and capabilities required to process
data with storage efficiency.
 Tables: In relational data model, relations are saved in the format of Tables. This
format stores the relation among entities. A table has rows and columns, where rows
represents records and columns represent the attributes.
 Tuple: A single row of a table, which contains a single record for that relation is called
a tuple.
 Record: Records are composed of fields, each of which contains one item of
information. A set of records constitutes a file.
 Fields: Each record consists of several fields; the fields of all records form the columns.
 Relation instance: A finite set of tuples in the relational database system represents
relation instance. Relation instances do not have duplicate tuples.
 Relation schema: A relation schema describes the relation name (table name),
attributes, and their names.
 Relation key: Each row has one or more attributes, known as relation key, which can
identify the row in the relation (table) uniquely.
 Attribute domain: Every attribute has some pre-defined value scope, known as
attribute domain.
 Data types: A database data type refers to the format of data storage that can hold a
distinct type or range of values.

Prof. Hitesh Mhatre 2-1


Database Management Systems – 22319 CO-3I

2.2 E. F. Codd’s Rule for RDBMS:


 Dr Edgar F. Codd, after his extensive research on the Relational Model of database
systems, came up with twelve rules of his own, which according to him, a database
must obey in order to be regarded as a true relational database.
 These rules can be applied on any database system that manages stored data using only
its relational capabilities.
 This is a foundation rule, which acts as a base for all the other rules.
 Rule 1: Information Rule
The data stored in a database, may it be user data or metadata, must be a value of some
table cell. Everything in a database must be stored in a table format.
 Rule 2: Guaranteed Access Rule
Every single data element (value) is guaranteed to be accessible logically with a
combination of table-name, primary-key (row value), and attribute-name (column
value). No other means, such as pointers, can be used to access data.
 Rule 3: Systematic Treatment of NULL Values
The NULL values in a database must be given a systematic and uniform treatment.
This is a very important rule because a NULL can be interpreted as one the following
− data is missing, data is not known, or data is not applicable.
 Rule 4: Active Online Catalog
The structure description of the entire database must be stored in an online catalog,
known as data dictionary, which can be accessed by authorized users. Users can use
the same query language to access the catalog which they use to access the database
itself.
 Rule 5: Comprehensive Data Sub-Language Rule
A database can only be accessed using a language having linear syntax that supports
data definition, data manipulation, and transaction management operations. This
language can be used directly or by means of some application. If the database allows
access to data without any help of this language, then it is considered as a violation.
 Rule 6: View Updating Rule
All the views of a database, which can theoretically be updated, must also be updatable
by the system.
 Rule 7: High-Level Insert, Update, and Delete Rule
A database must support high-level insertion, updation, and deletion. This must not be
limited to a single row, that is, it must also support union, intersection and minus
operations to yield sets of data records.
 Rule 8: Physical Data Independence

Prof. Hitesh Mhatre 2-2


Database Management Systems – 22319 CO-3I

The data stored in a database must be independent of the applications that access the
database. Any change in the physical structure of a database must not have any impact
on how the data is being accessed by external applications.
 Rule 9: Logical Data Independence
The logical data in a database must be independent of its user’s view (application). Any
change in logical data must not affect the applications using it. For example, if two
tables are merged or one is split into two different tables, there should be no impact or
change on the user application. This is one of the most difficult rule to apply.
 Rule 10: Integrity Independence
A database must be independent of the application that uses it. All its integrity
constraints can be independently modified without the need of any change in the
application. This rule makes a database independent of the front-end application and
its interface.
 Rule 11: Distribution Independence
The end-user must not be able to see that the data is distributed over various locations.
Users should always get the impression that the data is located at one site only. This
rule has been regarded as the foundation of distributed database systems.
 Rule 12: Non-Subversion Rule
If a system has an interface that provides access to low-level records, then the interface
must not be able to subvert the system and bypass security and integrity constraints.

2.3 Key Concepts:


 Key is an attribute or collection of attributes that uniquely identifies an entity among
entity set.
 For example, the roll_number of a student makes him/her identifiable among students.
 Super Key: A set of attributes (one or more) that collectively identifies an entity in an
entity set.
 Candidate Key: A minimal super key is called a candidate key. An entity set may have
more than one candidate key.
 Primary Key: A primary key is one of the candidate keys chosen by the database
designer to uniquely identify the entity set.
 Foreign Key: A foreign key is a key attribute of a relation that can be referred in other
relation

2.4 Constraints
 Every relation has some conditions that must hold for it to be a valid relation.
 These conditions are called Relational Integrity Constraints.
 There are three main integrity constraints:
Prof. Hitesh Mhatre 2-3
Database Management Systems – 22319 CO-3I

o Key constraints
o Domain constraints
o Referential integrity constraints

2.4.1 Key Constraints


 There must be at least one minimal subset of attributes in the relation, which can
identify a tuple uniquely.
 This minimal subset of attributes is called key for that relation. If there are more than
one such minimal subsets, these are called candidate keys.
 Key constraints force that −
o In a relation with a key attribute, no two tuples can have identical values for
key attributes.
o A key attribute cannot have NULL values.
 Key constraints are also referred to as Entity Constraints.

2.4.2 Domain Constraints


 Attributes have specific values in real-world scenario. For example, age can only be a
positive integer.
 The same constraints have been tried to employ on the attributes of a relation.
 Every attribute is bound to have a specific range of values. For example, age cannot
be less than zero and telephone numbers cannot contain a digit outside 0-9.

2.4.3 Referential integrity Constraints


 Referential integrity constraints work on the concept of Foreign Keys.
 A foreign key is a key attribute of a relation that can be referred in other relation.
 Referential integrity constraint states that if a relation refers to a key attribute of a
different or same relation, then that key element must exist.

2.5 Normalization:
 If a database design is not perfect, it may contain anomalies, which are like a bad dream
for any database administrator. Managing a database with anomalies is next to
impossible.
o Update anomalies: If data items are scattered and are not linked to each other
properly, then it could lead to strange situations. For example, when we try to
update one data item having its copies scattered over several places, a few
instances get updated properly while a few others are left with old values. Such
instances leave the database in an inconsistent state.

Prof. Hitesh Mhatre 2-4


Database Management Systems – 22319 CO-3I

o Deletion anomalies: We tried to delete a record, but parts of it was left


undeleted because of unawareness, the data is also saved somewhere else.
o Insert anomalies: We tried to insert data in a record that does not exist at all.
 Normalization is a method to remove all these anomalies and bring the database to a
consistent state.

2.6 Need of Normalization:


 There are two primary advantages of having a highly normalized data schema:
1. Increased consistency: Information is stored in one place and one place only,
reducing the possibility of inconsistent data.
2. Easier object-to-data mapping: Highly-normalized data schemas in general are
closer conceptually to object-oriented schemas because the object-oriented goals of
promoting high cohesion and loose coupling between classes results in similar
solutions (at least from a data point of view).

2.7 Types of Normalization:

2.7.1 First Normal Form


 First Normal Form is defined in the definition of relations (tables) itself.
 This rule defines that all the attributes in a relation must have atomic domains.
 The values in an atomic domain are indivisible units.

 We re-arrange the relation (table) as below, to convert it to First Normal Form.

 Each attribute must contain only a single value from its pre-defined domain.

Prof. Hitesh Mhatre 2-5


Database Management Systems – 22319 CO-3I

2.7.2 Second Normal Form


 Before we learn about the second normal form, we need to understand the following:
o Prime attribute: An attribute, which is a part of the candidate-key, is known
as a prime attribute.
o Non-prime attribute: An attribute, which is not a part of the primary-key, is
said to be a non-prime attribute.
 If we follow second normal form, then every non-prime attribute should be fully
functionally dependent on prime key attribute. That is, if X → A holds, then there
should not be any proper subset Y of X, for which Y → A also holds true.

 We see here in Student_Project relation that the prime key attributes are Stu_ID and
Proj_ID.
 According to the rule, non-key attributes, i.e. Stu_Name and Proj_Name must be
dependent upon both and not on any of the prime key attribute individually.
 But we find that Stu_Name can be identified by Stu_ID and Proj_Name can be
identified by Proj_ID independently.
 This is called partial dependency, which is not allowed in Second Normal Form.

 We broke the relation in two as depicted in the above picture. So there exists no partial
dependency.

2.7.3 Third Normal Form


 For a relation to be in Third Normal Form, it must be in Second Normal form and the
following must satisfy:
o No non-prime attribute is transitively dependent on prime key attribute.
o For any non-trivial functional dependency, X → A, then either:
 X is a super key or, A is prime attribute.

Prof. Hitesh Mhatre 2-6


Database Management Systems – 22319 CO-3I

 We find that in the above Student_Detail relation, Stu_ID is the key and only prime
key attribute.
 We find that City can be identified by Stu_ID as well as Zip itself.
 Neither Zip is a super key nor is City a prime attribute.
 Additionally, Stu_ID → Zip → City, so there exists transitive dependency.
 To bring this relation into third normal form, we break the relation into two relations
as follows −

2.7.4 Boyce-Codd Normal Form:


 Boyce-Codd Normal Form (BCNF) is an extension of Third Normal Form on strict
terms.
 BCNF states that –
o For any non-trivial functional dependency, X → A, X must be a super-key.
 In the above image, Stu_ID is the super-key in the relation Student_Detail and Zip is
the super-key in the relation ZipCodes.
 So, Stu_ID → Stu_Name, Zip and Zip → City. Which confirms that both the relations
are in BCNF.

2.8 Introduction to SQL:


 SQL stands for Structured Query Language
 SQL lets you access and manipulate databases
 SQL became a standard of the American National Standards Institute (ANSI) in 1986,
and of the International Organization for Standardization (ISO) in 1987
 SQL can execute queries against a database
 SQL can retrieve data from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases

Prof. Hitesh Mhatre 2-7


Database Management Systems – 22319 CO-3I

 SQL can create new tables in a database


 SQL can create stored procedures in a database
 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views

2.9 Data types in SQL:

 SQL Data Types define the type of value that can be stored in a table column.
 SQL data types can be broadly divided into following categories.
1. Numeric data types such as int, tinyint, bigint, float, real etc.
2. Date and Time data types such as Date, Time, Datetime etc.
3. Character and String data types such as char, varchar, text etc.
4. Unicode character string data types, for example nchar, nvarchar, ntext etc.
5. Binary data types such as binary, varbinary etc.
6. Miscellaneous data types – clob, blob, xml, cursor, table etc.

Figure 1: Data types in SQL

SQL Numeric Data Types

Datatype From To

bit 0 1

tinyint 0 255

smallint -32,768 32,767

Prof. Hitesh Mhatre 2-8


Database Management Systems – 22319 CO-3I

int -2,147,483,648 2,147,483,647

bigint -9,223,372,036, 854,775,808 9,223,372,036, 854,775,807

decimal -10^38 +1 10^38 -1

numeric -10^38 +1 10^38 -1

float -1.79E + 308 1.79E + 308

real -3.40E + 38 3.40E + 38

SQL Date and Time Data Types

Datatype Description

DATE Stores date in the format YYYY-MM-DD

TIME Stores time in the format HH:MI:SS

Stores date and time information in the format YYYY-MM-


DATETIME
DD HH:MI:SS

Stores number of seconds passed since the Unix epoch (‘1970-


TIMESTAMP
01-01 00:00:00’ UTC)

Stores year in 2 digit or 4 digit format. Range 1901 to 2155 in


YEAR
4-digit format. Range 70 to 69, representing 1970 to 2069.

SQL Character and String Data Types

Datatype Description

CHAR Fixed length with maximum length of 8,000 characters

VARCHAR Variable length storage with maximum length of 8,000


characters

VARCHAR(max) Variable length storage with provided max characters, not


supported in MySQL

TEXT Variable length storage with maximum size of 2GB data

 Note that all the above data types are for character stream, they should not be used with
unicode data.
Prof. Hitesh Mhatre 2-9
Database Management Systems – 22319 CO-3I

SQL Unicode Character and String Data Types

Datatype Description

NCHAR Fixed length with maximum length of 4,000 characters

NVARCHAR Variable length storage with maximum length of 4,000 characters

NVARCHAR(max) Variable length storage with provided max characters

NTEXT Variable length storage with maximum size of 1GB data

 Note that above data types are not supported in MySQL database.

SQL Binary Data Types

Datatype Description

BINARY Fixed length with maximum length of 8,000 bytes

VARBINARY Variable length storage with maximum length of 8,000 bytes

VARBINARY(max) Variable length storage with provided max bytes

IMAGE Variable length storage with maximum size of 2GB binary data

SQL Miscellaneous Data Types

Datatype Description

CLOB Character large objets that can hold up to 2GB

BLOB For binary large objects

XML for storing xml data

JSON for storing JSON data

Prof. Hitesh Mhatre 2-10


Database Management Systems – 22319 CO-3I

2.10 Components of SQL:


 The Structured Query Language (SQL) is the set of instructions used to interact with a
relational database.
 In fact, SQL is the only language that most databases understand. Whenever you
interact with such a database, the software translates your commands (whether they are
mouse clicks or form entries) into a SQL statement that the database knows how to
interpret.
 SQL has three main components: the Data Manipulation Language (DML), the Data
Definition Language (DDL), and the Data Control Language (DCL).

2.10.1 Data Manipulation Language


 The Data Manipulation Language (DML) contains the subset of SQL commands used
most frequently — those that simply manipulate the contents of a database in some
form.
 The four most common DML commands retrieve information from a database (the
SELECT) command, add new information to a database (the INSERT command),
modify information currently stored in a database (the UPDATE command), and
remove information from a database (the DELETE command).

2.10.2 Data Definition Language


 The Data Definition Language (DDL) contains commands that are less frequently used.
DDL commands modify the actual structure of a database, rather than the database’s
contents.
 Examples of commonly used DDL commands include those used to generate a new
database table (CREATE TABLE), modify the structure of a database table (ALTER
TABLE), and delete a database table (DROP TABLE).

2.10.3 Data Control Language


 The Data Control Language (DCL) is used to manage user access to databases.
 It consists of two commands: the GRANT command, used to add database permissions
for a user, and the REVOKE command, used to remove existing permissions.
 These two commands form the core of the relational database security model.

2.10.4 Data Query Language


 The commands of SQL that are used to retrieve data from the database are collectively
called DQL. So all Select statements come under DQL.

Prof. Hitesh Mhatre 2-11


Database Management Systems – 22319 CO-3I

 The purpose of DQL Command is to get some schema relation based on the query
passed to it.

2.11 DDL Commands:


2.11.1 CREATE
 The CREATE TABLE statement is used to create a new table in a database.
Syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
 The column parameters specify the names of the columns of the table.
 The datatype parameter specifies the type of data the column can hold (e.g. varchar,
integer, date, etc.).

SQL CREATE TABLE Example


 The following example creates a table called "Persons" that contains five columns:
PersonID, LastName, FirstName, Address, and City:
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
 The PersonID column is of type int and will hold an integer.
 The LastName, FirstName, Address, and City columns are of type varchar and will
hold characters, and the maximum length for these fields is 255 characters.
 The empty "Persons" table will now look like this:

Prof. Hitesh Mhatre 2-12


Database Management Systems – 22319 CO-3I

2.11.2 ALTER
 The ALTER TABLE statement is used to add, delete, or modify columns in an existing
table.
 The ALTER TABLE statement is also used to add and drop various constraints on an
existing table.

ALTER TABLE - ADD Column


 To add a column in a table, use the following syntax:
ALTER TABLE table_name
ADD column_name datatype;
 Look at the "Persons" table:

 Now we want to add a column named "DateOfBirth" in the "Persons" table.


 We use the following SQL statement:
ALTER TABLE Persons
ADD DateOfBirth date;
 Notice that the new column, "DateOfBirth", is of type date and is going to hold a date.
 The data type specifies what type of data the column can hold.
 The "Persons" table will now look like this:

ALTER TABLE - DROP COLUMN


 To delete a column in a table, use the following syntax (notice that some database
systems don't allow deleting a column):
ALTER TABLE table_name
DROP COLUMN column_name;
 Next, we want to delete the column named "DateOfBirth" in the "Persons" table. We
use the following SQL statement:
ALTER TABLE Persons
DROP COLUMN DateOfBirth;

Prof. Hitesh Mhatre 2-13


Database Management Systems – 22319 CO-3I

 The "Persons" table will now look like this:

ALTER TABLE - ALTER/MODIFY COLUMN


 To change the data type of a column in a table, use the following syntax:
 SQL Server / MS Access:
ALTER TABLE table_name
ALTER COLUMN column_name datatype;

 My SQL / Oracle (prior version 10G):


ALTER TABLE table_name
MODIFY COLUMN column_name datatype;

 Oracle 10G and later:


ALTER TABLE table_name
MODIFY column_name datatype;

Change Data Type Example


 Now we want to change the data type of the column named "DateOfBirth" in the
"Persons" table. We use the following SQL statement:
ALTER TABLE Persons
ALTER COLUMN DateOfBirth year;
 Notice that the "DateOfBirth" column is now of type year and is going to hold a year
in a two- or four-digit format.

2.11.3 DROP
 The DROP TABLE statement is used to drop an existing table in a database.
Syntax
DROP TABLE table_name;

 Note: Be careful before dropping a table. Deleting a table will result in loss of complete
information stored in the table!

 The following SQL statement drops the existing table "Shippers":


DROP TABLE Shippers;

Prof. Hitesh Mhatre 2-14


Database Management Systems – 22319 CO-3I

2.11.4 TRUNCATE
 The TRUNCATE TABLE statement is used to delete the data inside a table, but not the
table itself.
Syntax
TRUNCATE TABLE table_name;

2.11.5 DESC

 SQL DESC statement use for describe the list of column definitions for specified table.
You can use either DESC or DESCRIBE statement. both are return same result.
 DESCRIBE statement to get following information:
o Column Name
o Column allow NULL or NOT NULL
o Datatype of the Column
o With database size precision and If NUMERIC datatype scale.

Syntax
SQL DESCRIBE Table Column use following syntax,
DESC table_name

Example
DESC users_info;

Name Null? Type


--------------------------------------------------------------------------------------
NO NOT NULL NUMBER(3)
NAME VARCHAR2(30)
ADDRESS VARCHAR2(70)
CONTACT_NO VARCHAR2(12)

2.11.6 RENAME
 RENAME TABLE syntax is used to change the name of a table. Sometimes, we choose
non-meaningful name for the table. So it is required to be changed.
Syntax
RENAME old_table _name TO new_table_name;
Example
RENAME STUDENTS TO ARTISTS;

Prof. Hitesh Mhatre 2-15


Database Management Systems – 22319 CO-3I

2.12 Data Integrity Constraints:

2.12.1 PRIMARY KEY Constraint


 The PRIMARY KEY constraint uniquely identifies each record in a table.
 Primary keys must contain UNIQUE values, and cannot contain NULL values.
 A table can have only ONE primary key; and in the table, this primary key can consist
of single or multiple columns (fields).
 The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons"
table is created:

MySQL:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);

SQL Server / Oracle / MS Access:


CREATE TABLE Persons (
ID int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);

 To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),

Prof. Hitesh Mhatre 2-16


Database Management Systems – 22319 CO-3I

Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);
 Note: In the example above there is only ONE PRIMARY KEY (PK_Person).
However, the VALUE of the primary key is made up of TWO COLUMNS (ID +
LastName).

2.12.2 FOREIGN KEY Constraint


 A FOREIGN KEY is a key used to link two tables together.
 A FOREIGN KEY is a field (or collection of fields) in one table that refers to the
PRIMARY KEY in another table.
 The table containing the foreign key is called the child table, and the table containing
the candidate key is called the referenced or parent table.
 Look at the following two tables:
"Persons" table:

"Orders" table:

 Notice that the "PersonID" column in the "Orders" table points to the "PersonID"
column in the "Persons" table.
 The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons"
table.
 The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders"
table.
 The FOREIGN KEY constraint is used to prevent actions that would destroy links
between tables.
 The FOREIGN KEY constraint also prevents invalid data from being inserted into the
foreign key column, because it has to be one of the values contained in the table it points
to.

Prof. Hitesh Mhatre 2-17


Database Management Systems – 22319 CO-3I

 The following SQL creates a FOREIGN KEY on the "PersonID" column when the
"Orders" table is created:
MySQL:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

SQL Server / Oracle / MS Access:


CREATE TABLE Orders (
OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int FOREIGN KEY REFERENCES Persons(PersonID)
);
 To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY
constraint on multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID)
);

SQL FOREIGN KEY on ALTER TABLE


 To create a FOREIGN KEY constraint on the "PersonID" column when the "Orders"
table is already created, use the following SQL:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Orders
ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

Prof. Hitesh Mhatre 2-18


Database Management Systems – 22319 CO-3I

 To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY
constraint on multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Orders
ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

DROP a FOREIGN KEY Constraint


 To drop a FOREIGN KEY constraint, use the following SQL:
MySQL:
ALTER TABLE Orders
DROP FOREIGN KEY FK_PersonOrder;
SQL Server / Oracle / MS Access:
ALTER TABLE Orders
DROP CONSTRAINT FK_PersonOrder;

2.12.3 UNIQUE Constraint


 The UNIQUE constraint ensures that all values in a column are different.
 Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness
for a column or set of columns.
 A PRIMARY KEY constraint automatically has a UNIQUE constraint.
 However, you can have many UNIQUE constraints per table, but only one PRIMARY
KEY constraint per table.
 The following SQL creates a UNIQUE constraint on the "ID" column when the
"Persons" table is created:
SQL Server / Oracle / MS Access:
CREATE TABLE Persons (
ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
MySQL:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,

Prof. Hitesh Mhatre 2-19


Database Management Systems – 22319 CO-3I

FirstName varchar(255),
Age int,
UNIQUE (ID)
);
 To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple
columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT UC_Person UNIQUE (ID,LastName)
);

UNIQUE Constraint on ALTER TABLE


 To create a UNIQUE constraint on the "ID" column when the table is already created,
use the following SQL:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Persons
ADD UNIQUE (ID);
 To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple
columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Persons
ADD CONSTRAINT UC_Person UNIQUE (ID,LastName);

DROP a UNIQUE Constraint


 To drop a UNIQUE constraint, use the following SQL:
MySQL:
ALTER TABLE Persons
DROP INDEX UC_Person;
SQL Server / Oracle / MS Access:
ALTER TABLE Persons
DROP CONSTRAINT UC_Person;

Prof. Hitesh Mhatre 2-20


Database Management Systems – 22319 CO-3I

2.12.4 NOT NULL Constraint


 By default, a column can hold NULL values.
 The NOT NULL constraint enforces a column to NOT accept NULL values.
 This enforces a field to always contain a value, which means that you cannot insert a
new record, or update a record without adding a value to this field.
 The following SQL ensures that the "ID", "LastName", and "FirstName" columns will
NOT accept NULL values when the "Persons" table is created:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);

NOT NULL on ALTER TABLE


 To create a NOT NULL constraint on the "Age" column when the "Persons" table is
already created, use the following SQL:
ALTER TABLE Persons
MODIFY Age int NOT NULL;

2.12.5 CHECK Constraint


 The CHECK constraint is used to limit the value range that can be placed in a column.
 If you define a CHECK constraint on a single column it allows only certain values for
this column.
 If you define a CHECK constraint on a table it can limit the values in certain columns
based on values in other columns in the row.
 The following SQL creates a CHECK constraint on the "Age" column when the
"Persons" table is created. The CHECK constraint ensures that the age of a person must
be 18, or older:
MySQL:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18));

Prof. Hitesh Mhatre 2-21


Database Management Systems – 22319 CO-3I

SQL Server / Oracle / MS Access:


CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int CHECK (Age>=18)
);
 To allow naming of a CHECK constraint, and for defining a CHECK constraint on
multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255),
CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')
);

CHECK on ALTER TABLE


 To create a CHECK constraint on the "Age" column when the table is already created,
use the following SQL:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Persons
ADD CHECK (Age>=18);
 To allow naming of a CHECK constraint, and for defining a CHECK constraint on
multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Persons
ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sandnes');

DROP a CHECK Constraint


 To drop a CHECK constraint, use the following SQL:

Prof. Hitesh Mhatre 2-22


Database Management Systems – 22319 CO-3I

SQL Server / Oracle / MS Access:


ALTER TABLE Persons
DROP CONSTRAINT CHK_PersonAge;

MySQL:
ALTER TABLE Persons
DROP CHECK CHK_PersonAge;

2.12.6 DEFAULT Constraint


 The DEFAULT constraint is used to provide a default value for a column.
 The default value will be added to all new records IF no other value is specified.
 The following SQL sets a DEFAULT value for the "City" column when the "Persons"
table is created:
My SQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);
 The DEFAULT constraint can also be used to insert system values, by using functions
like GETDATE():
CREATE TABLE Orders (
ID int NOT NULL,
OrderNumber int NOT NULL,
OrderDate date DEFAULT GETDATE()
);

DEFAULT on ALTER TABLE


 To create a DEFAULT constraint on the "City" column when the table is already
created, use the following SQL:
MySQL:
ALTER TABLE Persons
ALTER City SET DEFAULT 'Sandnes';

Prof. Hitesh Mhatre 2-23


Database Management Systems – 22319 CO-3I

SQL Server:
ALTER TABLE Persons
ADD CONSTRAINT df_City
DEFAULT 'Sandnes' FOR City;

MS Access:
ALTER TABLE Persons
ALTER COLUMN City SET DEFAULT 'Sandnes';

Oracle:
ALTER TABLE Persons
MODIFY City DEFAULT 'Sandnes';

DROP a DEFAULT Constraint


 To drop a DEFAULT constraint, use the following SQL:
MySQL:
ALTER TABLE Persons
ALTER City DROP DEFAULT;

SQL Server / Oracle / MS Access:


ALTER TABLE Persons
ALTER COLUMN City DROP DEFAULT;

2.13 DML Commands


2.13.1 INSERT
 The INSERT INTO statement is used to insert new records in a table.
 It is possible to write the INSERT INTO statement in two ways.
 The first way specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

 If you are adding values for all the columns of the table, you do not need to specify the
column names in the SQL query. However, make sure the order of the values is in the
same order as the columns in the table. The INSERT INTO syntax would be as follows:
Prof. Hitesh Mhatre 2-24
Database Management Systems – 22319 CO-3I

INSERT INTO table_name


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

 Below is a selection from the "Customers" table in the sample database:

 The following SQL statement inserts a new record in the "Customers" table:
INSERT INTO Customers (CustomerName, ContactName,
Address, City, PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen',
'Skagen 21', 'Stavanger', '4006', 'Norway');

 The selection from the "Customers" table will now look like this:

 Did you notice that we did not insert any number into the CustomerID field?
The CustomerID column is an auto-increment field and will be generated automatically
when a new record is inserted into the table.

Insert Data Only in Specified Columns


 It is also possible to only insert data in specific columns.
 The following SQL statement will insert a new record, but only insert data in the
"CustomerName", "City", and "Country" columns (CustomerID will be updated
automatically):
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');

Prof. Hitesh Mhatre 2-25


Database Management Systems – 22319 CO-3I

 The selection from the "Customers" table will now look like this:

2.13.2 DELETE
 The DELETE statement is used to delete existing records in a table.
Syntax
DELETE FROM table_name WHERE condition;
 Note: Be careful when deleting records in a table! Notice the WHERE clause in the
DELETE statement. The WHERE clause specifies which record(s) should be deleted.
If you omit the WHERE clause, all records in the table will be deleted!
 Below is a selection from the "Customers" table in the sample database:

Example
 The following SQL statement deletes the customer "Alfreds Futterkiste" from the
"Customers" table:
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';

 The "Customers" table will now look like this:

Prof. Hitesh Mhatre 2-26


Database Management Systems – 22319 CO-3I

Delete All Records


 It is possible to delete all rows in a table without deleting the table. This means that the
table structure, attributes, and indexes will be intact:
DELETE FROM table_name;
 The following SQL statement deletes all rows in the "Customers" table, without
deleting the table:
DELETE FROM Customers;

2.13.2 UPDATE
 The UPDATE statement is used to modify the existing records in a table.
Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
 Note: Be careful when updating records in a table! Notice the WHERE clause in the
UPDATE statement. The WHERE clause specifies which record(s) that should be
updated. If you omit the WHERE clause, all records in the table will be updated!
 Below is a selection from the "Customers" table in the sample database:

Prof. Hitesh Mhatre 2-27


Database Management Systems – 22319 CO-3I

 The following SQL statement updates the first customer (CustomerID = 1) with a new
contact person and a new city.
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
 The selection from the "Customers" table will now look like this:

UPDATE Multiple Records


 It is the WHERE clause that determines how many records will be updated.
 The following SQL statement will update the ContactName to "Juan" for all records
where country is "Mexico":
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';

Prof. Hitesh Mhatre 2-28


Database Management Systems – 22319 CO-3I

Update Warning!
 Be careful when updating records. If you omit the WHERE clause, ALL records will
be updated!
UPDATE Customers
SET ContactName='Juan';
 The selection from the "Customers" table will now look like this:

2.14 DCL Commands:


2.14.1 COMMIT
 COMMIT command is used to permanently save any transaction into the database.
 When we use any DML command like INSERT, UPDATE or DELETE, the changes
made by these commands are not permanent, until the current session is closed, the
changes made by these commands can be rolled back.
 To avoid that, we use the COMMIT command to mark the changes as permanent.
 Following is commit command's syntax,
COMMIT;

2.14.2 SAVEPOINT
 SAVEPOINT command is used to temporarily save a transaction so that you can
rollback to that point whenever required.
 Following is savepoint command's syntax,
SAVEPOINT savepoint_name;
 In short, using this command we can name the different states of our data in any table
and then rollback to that state using the ROLLBACK command whenever required

Prof. Hitesh Mhatre 2-29


Database Management Systems – 22319 CO-3I

2.14.3 ROLLBACK
 This command restores the database to last commited state. It is also used with
SAVEPOINT command to jump to a savepoint in an ongoing transaction.
 If we have used the UPDATE command to make some changes into the database, and
realise that those changes were not required, then we can use the ROLLBACK
command to rollback those changes, if they were not commited using the COMMIT
command.
 Following is rollback command's syntax,
ROLLBACK TO savepoint_name;

2.14.4 GRANT
 You can GRANT and REVOKE privileges on various database objects in SQL Server.
We'll look at how to grant and revoke privileges on tables in SQL Server.
 You can grant users various privileges to tables. These permissions can be any
combination of SELECT, INSERT, UPDATE, DELETE, REFERENCES, ALTER, or
ALL.
 The syntax for granting privileges on a table in SQL Server is:
GRANT privileges ON object TO user;
 For example, if you wanted to grant SELECT, INSERT, UPDATE, and DELETE
privileges on a table called employees to a user name smithj, you would run the
following GRANT statement:
GRANT SELECT, INSERT, UPDATE, DELETE ON employees TO smithj;
 You can also use the ALL keyword to indicate that you wish to grant the ANSI-92
permissions (ie: SELECT, INSERT, UPDATE, DELETE, and REFERENCES) to a
user named smithj.
 For example:
GRANT ALL ON employees TO smithj;
 If you wanted to grant only SELECT access on the employees table to all users, you
could grant the privileges to the public role. For example:
GRANT SELECT ON employees TO public;

2.14.5 REVOKE
 Once you have granted privileges, you may need to revoke some or all of these
privileges. To do this, you can run a revoke command. You can revoke any combination
of SELECT, INSERT, UPDATE, DELETE, REFERENCES, ALTER, or ALL.
 The syntax for revoking privileges on a table in SQL Server is:
REVOKE privileges ON object FROM user;

Prof. Hitesh Mhatre 2-30


Database Management Systems – 22319 CO-3I

 For example, if you wanted to revoke DELETE privileges on a table called employees
from a user named anderson, you would run the following REVOKE statement:
REVOKE DELETE ON employees FROM anderson;
 If you wanted to revoke ALL ANSI-92 permissions (ie: SELECT, INSERT, UPDATE,
DELETE, and REFERENCES) on a table for a user named anderson, you could use the
ALL keyword as follows:
REVOKE ALL ON employees FROM anderson;
 If you had granted SELECT privileges to the public role (ie: all users) on the employees
table and you wanted to revoke these privileges, you could run the following REVOKE
statement:
REVOKE SELECT ON employees FROM public;

2.15 DQL Commands:


2.15.1 SELECT
 The SELECT statement is used to select data from a database.
 The data returned is stored in a result table, called the result-set.
Syntax
SELECT column1, column2, ...
FROM table_name;
 Here, column1, column2, ... are the field names of the table you want to select data
from. If you want to select all the fields available in the table, use the following
syntax:
SELECT * FROM table_name;

 Below is a selection from the "Customers" table in the sample database:

Prof. Hitesh Mhatre 2-31


Database Management Systems – 22319 CO-3I

Example
 The following SQL statement selects the "CustomerName" and "City" columns from
the "Customers" table:
SELECT CustomerName, City FROM Customers;

SELECT * Example
 The following SQL statement selects all the columns from the "Customers" table:
SELECT * FROM Customers;

2.15.2 The SQL WHERE Clause


 The WHERE clause is used to filter records.
 The WHERE clause is used to extract only those records that fulfill a specified
condition.
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
 Note: The WHERE clause is not only used in SELECT statement, it is also used in
UPDATE, DELETE statement, etc.!
 Below is a selection from the "Customers" table in the sample database:

Prof. Hitesh Mhatre 2-32


Database Management Systems – 22319 CO-3I

Example
 The following SQL statement selects all the customers from the country "Mexico", in
the "Customers" table:
SELECT * FROM Customers
WHERE Country='Mexico';

2.15.3 Text Fields vs. Numeric Fields


 SQL requires single quotes around text values (most database systems will also allow
double quotes).
 However, numeric fields should not be enclosed in quotes:
SELECT * FROM Customers
WHERE CustomerID=1;

Prof. Hitesh Mhatre 2-33


Database Management Systems – 22319 CO-3I

2.16 SQL Operations:


2.16.1 Arithmetic
Addition (+):
It is used to perform addition operation on the data items, items include either single column
or multiple columns.
SELECT employee_id, employee_name, salary, salary + 100
AS "salary + 100" FROM addition;

Subtraction (-):
It is use to perform subtraction operation on the data items, items include either single column
or multiple columns.
SELECT employee_id, employee_name, salary, salary - 100
AS "salary - 100" FROM subtraction;

Multiplication (*):
It is use to perform multiplication of data items.
SELECT employee_id, employee_name, salary, salary * 100
AS "salary * 100" FROM addition;

Prof. Hitesh Mhatre 2-34


Database Management Systems – 22319 CO-3I

Modulus ( % ):
It is use to get remainder when one data is divided by another.
SELECT employee_id, employee_name, salary, salary % 25000
AS "salary % 25000" FROM addition;

2.16.2 Comparison
SELECT * FROM Products
WHERE Price = 18;

SELECT * FROM Products


WHERE Price > 30;

SELECT * FROM Products


WHERE Price < 30;

Prof. Hitesh Mhatre 2-35


Database Management Systems – 22319 CO-3I

SELECT * FROM Products


WHERE Price >= 30;

SELECT * FROM Products


WHERE Price <= 30;

SELECT * FROM Products


WHERE Price <> 18;

Prof. Hitesh Mhatre 2-36


Database Management Systems – 22319 CO-3I

2.16.3 Logical Set


 The WHERE clause can be combined with AND, OR, and NOT operators.
 The AND and OR operators are used to filter records based on more than one
condition:
o The AND operator displays a record if all the conditions separated by AND
are TRUE.
o The OR operator displays a record if any of the conditions separated by OR is
TRUE.
 The NOT operator displays a record if the condition(s) is NOT TRUE.
AND Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;

OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;

NOT Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;

The table below shows the complete "Customers" table from the sample database:

Prof. Hitesh Mhatre 2-37


Database Management Systems – 22319 CO-3I

AND Example
The following SQL statement selects all fields from "Customers" where country is "Germany"
AND city is "Berlin":
SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin';

OR Example
The following SQL statement selects all fields from "Customers" where city is "Berlin" OR
"München":
SELECT * FROM Customers
WHERE City='Berlin' OR City='München';

The following SQL statement selects all fields from "Customers" where country is "Germany"
OR "Spain":
SELECT * FROM Customers
WHERE Country='Germany' OR Country='Spain';

Prof. Hitesh Mhatre 2-38


Database Management Systems – 22319 CO-3I

NOT Example
The following SQL statement selects all fields from "Customers" where country is NOT
"Germany":
SELECT * FROM Customers
WHERE NOT Country='Germany';

Combining AND, OR and NOT


 You can also combine the AND, OR and NOT operators.
 The following SQL statement selects all fields from "Customers" where country is
"Germany" AND city must be "Berlin" OR "München" (use parenthesis to form
complex expressions):
SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR City='München');

The following SQL statement selects all fields from "Customers" where country is NOT
"Germany" and NOT "USA":

Prof. Hitesh Mhatre 2-39


Database Management Systems – 22319 CO-3I

SELECT * FROM Customers


WHERE NOT Country='Germany' AND NOT Country='USA';

2.16.4 Range Searching


IN Operator
 The IN operator allows you to specify multiple values in a WHERE clause.
 The IN operator is a shorthand for multiple OR conditions.
IN Syntax
SELECT column_name(s) FROM table_name
WHERE column_name IN (value1, value2, ...);
or:
SELECT column_name(s) FROM table_name
WHERE column_name IN (SELECT STATEMENT);
The table below shows the complete "Customers" table from the sample database:

Prof. Hitesh Mhatre 2-40


Database Management Systems – 22319 CO-3I

IN Operator Examples
The following SQL statement selects all customers that are located in "Germany", "France"
or "UK":
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');

The following SQL statement selects all customers that are NOT located in "Germany",
"France" or "UK":
SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');

The following SQL statement selects all customers that are from the same countries as the
suppliers:
SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);

Prof. Hitesh Mhatre 2-41


Database Management Systems – 22319 CO-3I

2.16.5 Between
 The BETWEEN operator selects values within a given range. The values can be
numbers, text, or dates.
 The BETWEEN operator is inclusive: begin and end values are included.
BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Below is a selection from the "Products" table in the sample database:

Prof. Hitesh Mhatre 2-42


Database Management Systems – 22319 CO-3I

BETWEEN Example
The following SQL statement selects all products with a price BETWEEN 10 and 20:
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;

NOT BETWEEN Example


To display the products outside the range of the previous example, use NOT BETWEEN:
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;

BETWEEN with IN Example


The following SQL statement selects all products with a price BETWEEN 10 and 20. In
addition; do not show products with a CategoryID of 1,2, or 3:

Prof. Hitesh Mhatre 2-43


Database Management Systems – 22319 CO-3I

SELECT * FROM Products


WHERE Price BETWEEN 10 AND 20
AND CategoryID NOT IN (1,2,3);

BETWEEN Text Values Example


The following SQL statement selects all products with a ProductName BETWEEN
Carnarvon Tigers and Mozzarella di Giovanni:
SELECT * FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di
Giovanni'
ORDER BY ProductName;

The following SQL statement selects all products with a ProductName BETWEEN
Carnarvon Tigers and Chef Anton's Cajun Seasoning:
SELECT * FROM Products
WHERE ProductName BETWEEN "Carnarvon Tigers" AND "Chef Anton's Cajun
Seasoning"
ORDER BY ProductName;

Prof. Hitesh Mhatre 2-44


Database Management Systems – 22319 CO-3I

NOT BETWEEN Text Values Example


The following SQL statement selects all products with a ProductName NOT BETWEEN
Carnarvon Tigers and Mozzarella di Giovanni:
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di
Giovanni'
ORDER BY ProductName;

BETWEEN Dates Example


The following SQL statement selects all orders with an OrderDate BETWEEN '01-July-1996'
and '31-July-1996':
SELECT * FROM Orders
WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';

2.16.6 Pattern Matching –LIKE


 The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column.
 There are two wildcards often used in conjunction with the LIKE operator:
Prof. Hitesh Mhatre 2-45
Database Management Systems – 22319 CO-3I

o % - The percent sign represents zero, one, or multiple characters


o _ - The underscore represents a single character
 Note: MS Access uses an asterisk (*) instead of the percent sign (%), and a question
mark (?) instead of the underscore ( _ ).
 The percent sign and the underscore can also be used in combinations!
LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Tip: You can also combine any number of conditions using AND or OR operators.
Here are some examples showing different LIKE operators with '%' and '_' wildcards:

The table below shows the complete "Customers" table from the sample database: 91 entries

SQL LIKE Examples


The following SQL statement selects all customers with a CustomerName starting with "a":
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';

Prof. Hitesh Mhatre 2-46


Database Management Systems – 22319 CO-3I

The following SQL statement selects all customers with a CustomerName ending with "a":
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';

The following SQL statement selects all customers with a CustomerName that have "or" in
any position:
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';

The following SQL statement selects all customers with a CustomerName that have "r" in the
second position:
SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';

Prof. Hitesh Mhatre 2-47


Database Management Systems – 22319 CO-3I

The following SQL statement selects all customers with a CustomerName that starts with "a"
and are at least 3 characters in length:
SELECT * FROM Customers
WHERE CustomerName LIKE 'a__%';

The following SQL statement selects all customers with a ContactName that starts with "a"
and ends with "o":
SELECT * FROM Customers
WHERE ContactName LIKE 'a%o';

The following SQL statement selects all customers with a CustomerName that does NOT
start with "a":
SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'a%';

Prof. Hitesh Mhatre 2-48


Database Management Systems – 22319 CO-3I

Prof. Hitesh Mhatre 2-49


Database Management Systems – 22319 CO-3I

Unit – III: Interactive SQL and Advanced SQL

Course Outcomes (COs):

 Create and manage database using SQL Command.

Unit Outcomes (UOs):

 Write the given queries using relevant functions.


 Write query to combine the given multiple table using JOIN.
 Design SQL queries to implements VIEW on the given tables.
 Apply and drop INDEXES and SYNONYM on the given table

3.1 In-built Functions:


3.1.1 String Functions:
1. BIN(N)
Returns a string representation of the binary value of N, where N is a longlong
(BIGINT) number. This is equivalent to CONV(N,10,2). Returns NULL if N is NULL.
SELECT BIN(12);
BIN(12)
-----------
1100

2. CHAR_LENGTH(str)
Returns the length of the string str measured in characters. A multi-byte character
counts as a single character. This means that for a string containing five two-byte
characters, LENGTH() returns 10, whereas CHAR_LENGTH() returns 5.
SELECT CHAR_LENGTH("Hello");
CHAR_LENGTH("Hello")
--------------------------
5

3. CONCAT(str1,str2,...)
Returns the string that results from concatenating the arguments. May have one or more
arguments. If all arguments are non-binary strings, the result is a non-binary string. If
the arguments include any binary strings, the result is a binary string. A numeric
argument is converted to its equivalent binary string form; if you want to avoid that,
you can use an explicit type cast, as in this example −

Prof. Hitesh Mhatre 3-1


Database Management Systems – 22319 CO-3I

SELECT CONCAT('My', 'S', 'QL');


CONCAT('My', 'S', 'QL')
---------------------------------------------------------
MySQL

4. LCASE(str)
LCASE() is a synonym for LOWER().

5. LEFT(str,len)
Returns the leftmost len characters from the string str, or NULL if any argument is
NULL.
SELECT LEFT('Engineering', 5);
LEFT('Engineering', 5)
---------------------------------------------------------
Engin

6. LENGTH(str)
Returns the length of the string str, measured in bytes. A multi-byte character counts as
multiple bytes. This means that for a string containing five two-byte characters,
LENGTH() returns 10, whereas CHAR_LENGTH() returns 5.
SELECT LENGTH('text');
LENGTH('Hello')
---------------------------------------------------------
5

7. LOWER(str)
Returns the string str with all characters changed to lowercase according to the current
character set mapping.
SELECT LOWER('QUADRATICALLY');
LOWER('QUADRATICALLY')
---------------------------------------------------------
quadratically

8. LPAD(str,len,padstr)
Returns the string str, left-padded with the string padstr to a length of len characters. If
str is longer than len, the return value is shortened to len characters.
SELECT LPAD('hi',4,'??');
LPAD('hi',4,'??')
---------------------------------------------------------
??hi

Prof. Hitesh Mhatre 3-2


Database Management Systems – 22319 CO-3I

9. LTRIM(str)
Returns the string str with leading space characters removed.
SELECT LTRIM(' diploma');
LTRIM(' diploma’)
---------------------------------------------------------
diploma

10. REPLACE(str,from_str,to_str)
Returns the string str with all occurrences of the string from_str replaced by the string
to_str. REPLACE() performs a case-sensitive match when searching for from_str.
SELECT REPLACE('www.mysql.com', 'w', 'Ww');
REPLACE('www.mysql.com', 'w', 'Ww')
---------------------------------------------------------
WwWwWw.mysql.com

11. REVERSE(str)
Returns the string str with the order of the characters reversed.
SELECT REVERSE('Hello');
REVERSE(‘Hello’)
---------------------------------------------------------
olleH

12. RIGHT(str,len)
Returns the rightmost len characters from the string str, or NULL if any argument is
NULL.
SELECT RIGHT('Engineering', 4);
RIGHT('Engineering', 4)
---------------------------------------------------------
ring

13. RPAD(str,len,padstr)
Returns the string str, right-padded with the string padstr to a length of len characters.
If str is longer than len, the return value is shortened to len characters.
SELECT RPAD('hi',5,'?');
RPAD('hi',5,'?')
---------------------------------------------------------
hi???

14. RTRIM(str)
Returns the string str with trailing space characters removed.

Prof. Hitesh Mhatre 3-3


Database Management Systems – 22319 CO-3I

SELECT RTRIM('diploma ');


RTRIM('diploma ')
---------------------------------------------------------
diploma

15. STRCMP(str1, str2)


Compares two strings and returns 0 if both strings are equal, it returns -1 if the first
argument is smaller than the second according to the current sort order otherwise it
returns 1.
SELECT STRCMP('HELLO', 'HELLO');
STRCMP('HELLO', 'HELLO')
---------------------------------------------------------
0
Another example is −
SELECT STRCMP('OHELLO', 'HELLO');
STRCMP('OHELLO', 'HELLO')
---------------------------------------------------------
-1
Let's see one more example −
SELECT STRCMP('HELLO', 'OHELLO');
STRCMP('HELLO', 'OHELLO')
---------------------------------------------------------
1

16. SUBSTRING(str,pos) / SUBSTRING(str FROM pos) / SUBSTRING(str,pos,len)


/ SUBSTRING(str FROM pos FOR len)
The forms without a len argument return a substring from string str starting at position
pos. The forms with a len argument return a substring len characters long from string
str, starting at position pos. The forms that use FROM are standard SQL syntax. It is
also possible to use a negative value for pos. In this case, the beginning of the substring
is pos characters from the end of the string, rather than the beginning. A negative value
may be used for pos in any of the forms of this function.
SELECT SUBSTRING('Quadratically',5);
SSUBSTRING('Quadratically',5)
---------------------------------------------------------
ratically

SELECT SUBSTRING('Engineering' FROM 4);


SUBSTRING('Engineering' FROM 4)
---------------------------------------------------------
ineering

Prof. Hitesh Mhatre 3-4


Database Management Systems – 22319 CO-3I

SELECT SUBSTRING('Quadratically',5,6);
SUBSTRING('Quadratically',5,6)
---------------------------------------------------------
ratica

17. TRIM([{BOTH | LEADING | TRAILING} [remstr] FROM] str) TRIM([remstr


FROM] str)
Returns the string str with all remstr prefixes or suffixes removed. If none of the
specifiers BOTH, LEADING, or TRAILING is given, BOTH is assumed. remstr is
optional and, if not specified, spaces are removed.
SELECT TRIM(' hello ');
TRIM(' hello ')
---------------------------------------------------------
hello

SELECT TRIM(LEADING 'x' FROM 'xxxhelloxxx');


TRIM(LEADING 'x' FROM 'xxxhelloxxx')
---------------------------------------------------------
helloxxx

SELECT TRIM(BOTH 'x' FROM 'xxxhelloxxx');


TRIM(BOTH 'x' FROM 'xxxhelloxxx')
---------------------------------------------------------
hello

SELECT TRIM(TRAILING 'xyz' FROM 'helloxxyz');


TRIM(TRAILING 'xyz' FROM 'helloxxyz')
---------------------------------------------------------
hellox

18. UCASE(str)
UCASE() is a synonym for UPPER().

19. UPPER(str)
Returns the string str with all characters changed to uppercase according to the current
character set mapping.
SELECT UPPER('Database-Management-System');
UPPER('Database-Management-System')
---------------------------------------------------------
DATABASE-MANAGEMENT-SYSTEM

Prof. Hitesh Mhatre 3-5


Database Management Systems – 22319 CO-3I

3.1.2 Arithmetic Functions:


 Mathematical functions are very important in SQL to implement different mathematical
concepts in queries.
 Some of the major mathematical functions in SQL are as follows −
1. ABS(X)
This function returns the absolute value of X. For example
SELECT ABS(-6);
This returns 6.

2. MOD(X,Y)
The variable X is divided by Y and their remainder is returned. For example
SELECT MOD(9,5);
This returns 4.

3. SIGN(X)
This method returns 1 if X is positive, -1 if it is negative and 0 if the value of X is 0.
For example
SELECT SIGN(10);
This returns 1.

4. FLOOR(X)
This returns the largest integer value that is either less than X or equal to it. For example
SELECT FLOOR(5.7);
This returns 5.

5. CEIL(X)
This returns the smallest integer value that is either more than X or equal to it. For
example
SELECT CEIL(5.7);
This returns 6.

6. POWER(X,Y)
This function returns the value of x raised to the power of Y. For example
SELECT POWER(2,5);
This returns 32.

Prof. Hitesh Mhatre 3-6


Database Management Systems – 22319 CO-3I

7. ROUND(X)
This function returns the value of X rounded off to the whole integer that is nearest to
it. For example
SELECT ROUND(5.7);
This returns 6.

8. SQRT(X)
This function returns the square root of X. For example
SELECT SQRT(9);
This returns 3.

9. ASIN(X)
This function accepts a Sin value as the input and returns the angle in radians. For
example
SELECT ASIN(0);
This returns 0.

10. ACOS(X)
This function accepts a Cos value as the input and returns the angle in radians. For
example
SELECT ACOS(1);
This returns 0.

11. ATAN(X)
This function accepts a Tan value as the input and returns the angle in radians. For
example
SELECT ATAN(0);
This returns 0.

12. SIN(X)
This function accepts an angle in radians as its parameter and returns its Sine value. For
example
SELECT SIN(0);
This returns 0.

Prof. Hitesh Mhatre 3-7


Database Management Systems – 22319 CO-3I

13. COS(X)
This function accepts an angle in radians as its parameter and returns its Cosine value.
For example
SELECT COS(0);
This returns 1.

14. TAN(X)
This function accepts an angle in radians as its parameter and returns its Tan value. For
example
SELECT TAN(0);
This returns 0.

3.1.3 DATE and TIME


1. CURDATE()
Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format,
depending on whether the function is used in a string or in a numeric context.

SELECT CURDATE();
CURDATE()
--------------------------------------------------------
1997-12-15

SELECT CURDATE() + 0;
CURDATE() + 0
--------------------------------------------------------
19971215

2. CURTIME()
Returns the current time as a value in 'HH:MM:SS' or HHMMSS format, depending on
whether the function is used in a string or in a numeric context. The value is expressed
in the current time zone.

SELECT CURTIME();
CURTIME()
---------------------------------------------------------
23:50:26
SELECT CURTIME() + 0;
CURTIME() + 0
---------------------------------------------------------
235026

Prof. Hitesh Mhatre 3-8


Database Management Systems – 22319 CO-3I

3. DATE(expr)
Extracts the date part of the date or date time expression expr.
SELECT DATE('2003-12-31 01:02:03');
DATE('2003-12-31 01:02:03')
---------------------------------------------------------
2003-12-31

4. DATEDIFF(expr1,expr2)
DATEDIFF() returns expr1 . expr2 expressed as a value in days from one date to the
other. Both expr1 and expr2 are date or date-and-time expressions. Only the date parts
of the values are used in the calculation.

SELECT DATEDIFF('1997-12-31 23:59:59','1997-12-30');


DATEDIFF('1997-12-31 23:59:59','1997-12-30')
---------------------------------------------------------
1

5. DATE_FORMAT(date,format)
This command formats the date value as per the format string.
The following specifiers may be used in the format string. The '%' character is required
before the format specifier characters.

%a Abbreviated weekday name (Sun..Sat)


%b Abbreviated month name (Jan..Dec)
%c Month, numeric (0..12)
%D Day of the month with English suffix (0th, 1st, 2nd, 3rd, .)
%d Day of the month, numeric (00..31)
%e Day of the month, numeric (0..31)
%f Microseconds (000000..999999)
%H Hour (00..23)
%h Hour (01..12)
%I Hour (01..12)
%i Minutes, numeric (00..59)
%j Day of year (001..366)
%k Hour (0..23)
%l Hour (1..12)

Prof. Hitesh Mhatre 3-9


Database Management Systems – 22319 CO-3I

%M Month name (January..December)


%m Month, numeric (00..12)
%p AM or PM
%r Time, 12-hour (hh:mm:ss followed by AM or PM)
%S Seconds (00..59)
%s Seconds (00..59)
%T Time, 24-hour (hh:mm:ss)
%U Week (00..53), where Sunday is the first day of the week
%u Week (00..53), where Monday is the first day of the week
%V Week (01..53), where Sunday is the first day of the week; used with %X
%v Week (01..53), where Monday is the first day of the week; used with %x
%W Weekday name (Sunday..Saturday)
%w Day of the week (0=Sunday..6=Saturday)
%X Year for the week where Sunday is the first day of the week, numeric, four digits; used
with %V
%x Year for the week, where Monday is the first day of the week, numeric, four digits;
used with %v
%Y Year, numeric, four digits
%y Year, numeric (two digits)
%% A literal .%. character
%x x, for any.x. not listed above

SELECT DATE_FORMAT('1997-10-04 22:23:00', '%W %M %Y');


DATE_FORMAT('1997-10-04 22:23:00', '%W %M %Y')
---------------------------------------------------------
Saturday October 1997
SELECT DATE_FORMAT('1997-10-04 22:23:00'
-> '%H %k %I %r %T %S %w');
DATE_FORMAT('1997-10-04 22:23:00.......
---------------------------------------------------------
22 22 10 10:23:00 PM 22:23:00 00 6

6. DAY(date)
The DAY() is a synonym for the DAYOFMONTH() function.

7. DAYNAME(date)
Returns the name of the weekday for date.
Prof. Hitesh Mhatre 3-10
Database Management Systems – 22319 CO-3I

SELECT DAYNAME('1998-02-05');
| DAYNAME('1998-02-05') |
---------------------------------------------------------
| Thursday |

8. DAYOFMONTH(date)
Returns the day of the month for date, in the range 0 to 31.
SELECT DAYOFMONTH('1998-02-03');
| DAYOFMONTH('1998-02-03') |
---------------------------------------------------------
|3 |

9. DAYOFWEEK(date)
Returns the weekday index for date (1 = Sunday, 2 = Monday, ., 7 = Saturday). These index
values correspond to the ODBC standard.
SELECT DAYOFWEEK('1998-02-03');
|DAYOFWEEK('1998-02-03') |
---------------------------------------------------------
|3 |

10. DAYOFYEAR(date)
Returns the day of the year for date, in the range 1 to 366.
SELECT DAYOFYEAR('1998-02-03');
| DAYOFYEAR('1998-02-03') |
---------------------------------------------------------
| 34 |

11. HOUR(time)
Returns the hour for time. The range of the return value is 0 to 23 for time-of-day values.
However, the range of TIME values actually is much larger, so HOUR can return values greater
than 23.
SELECT HOUR('10:05:03');
| HOUR('10:05:03') |
---------------------------------------------------------
| 10 |

12. LAST_DAY(date)
Takes a date or datetime value and returns the corresponding value for the last day of the month.
Returns NULL if the argument is invalid.

Prof. Hitesh Mhatre 3-11


Database Management Systems – 22319 CO-3I

SELECT LAST_DAY('2003-02-05');
| LAST_DAY('2003-02-05') |
---------------------------------------------------------
| 2003-02-28 |

13. MINUTE(time)
Returns the minute for time, in the range 0 to 59.
SELECT MINUTE('98-02-03 10:05:03');
---------------------------------------------------------
| MINUTE('98-02-03 10:05:03') |
---------------------------------------------------------
|5 |

14. MONTH(date)
Returns the month for date, in the range 0 to 12.
SELECT MONTH('1998-02-03')
| MONTH('1998-02-03') |
---------------------------------------------------------
|2 |

15. MONTHNAME(date)
Returns the full name of the month for a date.

SELECT MONTHNAME('1998-02-05');
| MONTHNAME('1998-02-05') |
---------------------------------------------------------
| February |

16. NOW()
Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or
YYYYMMDDHHMMSS format, depending on whether the function is used in a string or
numeric context. This value is expressed in the current time zone.
SELECT NOW();
| NOW() |
---------------------------------------------------------
| 1997-12-15 23:50:26 |

17. SYSDATE()
Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or
YYYYMMDDHHMMSS format, depending on whether the function is used in a string or in
a numeric context.

Prof. Hitesh Mhatre 3-12


Database Management Systems – 22319 CO-3I

SELECT SYSDATE();
| SYSDATE() |
---------------------------------------------------------
| 2006-04-12 13:47:44 |

18. WEEKDAY(date)
Returns the weekday index for date (0 = Monday, 1 = Tuesday, . 6 = Sunday).
SELECT WEEKDAY('1998-02-03 22:23:00');
| WEEKDAY('1998-02-03 22:23:00') |
---------------------------------------------------------
|1 |

19. WEEKOFYEAR(date)
Returns the calendar week of the date as a number in the range from 1 to 53. WEEKOFYEAR()
is a compatibility function that is equivalent to WEEK(date,3).
SELECT WEEKOFYEAR('1998-02-20');
| WEEKOFYEAR('1998-02-20') |
---------------------------------------------------------
|8 |

20. YEAR(date)
Returns the year for date, in the range 1000 to 9999, or 0 for the .zero. date.
SELECT YEAR('98-02-03');
| YEAR('98-02-03') |
---------------------------------------------------------
| 1998 |

3.2 Aggregate
 The SQL COUNT(), AVG() and SUM() Functions
 The COUNT() function returns the number of rows that matches a specified criterion.
 The AVG() function returns the average value of a numeric column.
 The SUM() function returns the total sum of a numeric column.

COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
AVG() Syntax

Prof. Hitesh Mhatre 3-13


Database Management Systems – 22319 CO-3I

SELECT AVG(column_name)
FROM table_name
WHERE condition;
SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;

Below is a selection from the "Products" table in the sample database:

COUNT() Example
The following SQL statement finds the number of products:
SELECT COUNT(ProductID)
FROM Products;

Note: NULL values are not counted.

AVG() Example
The following SQL statement finds the average price of all products:
SELECT AVG(Price)
FROM Products;

Note: NULL values are ignored.

Prof. Hitesh Mhatre 3-14


Database Management Systems – 22319 CO-3I

SUM() Example
The following SQL statement finds the sum of the "Quantity" fields in the "OrderDetails" table:
SELECT SUM(Price)
FROM Products;

MIN() and MAX() Functions


The MIN() function returns the smallest value of the selected column.
The MAX() function returns the largest value of the selected column.

MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
MIN() Example
The following SQL statement finds the price of the cheapest product:
SELECT MIN(Price) AS SmallestPrice
FROM Products;

MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
MAX() Example
The following SQL statement finds the price of the most expensive product:
SELECT MAX(Price) AS LargestPrice
FROM Products;

Prof. Hitesh Mhatre 3-15


Database Management Systems – 22319 CO-3I

3.3 Group By
 The GROUP BY statement groups’ rows that have the same values into summary rows,
like "find the number of customers in each country".
 The GROUP BY statement is often used with aggregate functions (COUNT, MAX,
MIN, SUM, AVG) to group the result-set by one or more columns.

GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Below is a selection from the "Customers" table in the sample database:

The following SQL statement lists the number of customers in each country:
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;

Prof. Hitesh Mhatre 3-16


Database Management Systems – 22319 CO-3I

3.4 Having

 The HAVING clause was added to SQL because the WHERE keyword could not be
used with aggregate functions.

HAVING Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
Below is a selection from the "Customers" table in the sample database:

Prof. Hitesh Mhatre 3-17


Database Management Systems – 22319 CO-3I

SQL HAVING Examples


The following SQL statement lists the number of customers in each country. Only include
countries with more than 5 customers:
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;

3.5 Order By
 The ORDER BY keyword is used to sort the result-set in ascending or descending order.
 The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in descending order, use the DESC keyword.

ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Below is a selection from the "Customers" table in the sample database:

Prof. Hitesh Mhatre 3-18


Database Management Systems – 22319 CO-3I

ORDER BY Example
The following SQL statement selects all customers from the "Customers" table, sorted by the
"Country" column:
SELECT * FROM Customers
ORDER BY Country;

ORDER BY DESC Example


The following SQL statement selects all customers from the "Customers" table, sorted
DESCENDING by the "Country" column:
SELECT * FROM Customers
ORDER BY Country DESC;

Prof. Hitesh Mhatre 3-19


Database Management Systems – 22319 CO-3I

ORDER BY Several Columns Example


The following SQL statement selects all customers from the "Customers" table, sorted by the
"Country" and the "CustomerName" column. This means that it orders by Country, but if some
rows have the same Country, it orders them by CustomerName:
SELECT * FROM Customers
ORDER BY Country, CustomerName;

3.6 Joins-Inner and Outer Joins


A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.

Let's look at a selection from the "Orders" table:

Then, look at a selection from the "Customers" table:

Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the
"Customers" table. The relationship between the two tables above is the "CustomerID" column.

Prof. Hitesh Mhatre 3-20


Database Management Systems – 22319 CO-3I

Then, we can create the following SQL statement (that contains an INNER JOIN), that selects
records that have matching values in both tables:
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
and it will produce something like this:

Different Types of SQL JOINs


Here are the different types of the JOINs in SQL:
1. (INNER) JOIN: Returns records that have matching values in both tables
2. LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records
from the right table
3. RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched
records from the left table
4. FULL (OUTER) JOIN: Returns all records when there is a match in either left or right
table

1. INNER JOIN
The INNER JOIN keyword selects records that have matching values in both tables.
INNER JOIN Syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;

Prof. Hitesh Mhatre 3-21


Database Management Systems – 22319 CO-3I

Demo Database

SQL INNER JOIN Example


The following SQL statement selects all orders with customer information:
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

Prof. Hitesh Mhatre 3-22


Database Management Systems – 22319 CO-3I

2. LEFT JOIN
The LEFT JOIN keyword returns all records from the left table (table1), and the matched
records from the right table (table2). The result is NULL from the right side, if there is no
match.

LEFT JOIN Syntax


SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
Note: In some databases LEFT JOIN is called LEFT OUTER JOIN.
LEFT JOIN Example
The following SQL statement will select all customers, and any orders they might have:
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;

3. RIGHT JOIN
The RIGHT JOIN keyword returns all records from the right table (table2), and the matched
records from the left table (table1). The result is NULL from the left side, when there is no
match.

RIGHT JOIN Syntax


SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;

Prof. Hitesh Mhatre 3-23


Database Management Systems – 22319 CO-3I

RIGHT JOIN Example


The following SQL statement will return all employees, and any orders they might have placed:
Note: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.

SELECT Orders.OrderID, Employees.LastName, Employees.FirstName


FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;

4. FULL OUTER JOIN


The FULL OUTER JOIN keyword returns all records when there is a match in left (table1) or
right (table2) table records.

Note: FULL OUTER JOIN can potentially return very large result-sets!
Tip: FULL OUTER JOIN and FULL JOIN are the same.

FULL OUTER JOIN Syntax


SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
FULL OUTER JOIN Example
The following SQL statement selects all customers, and all orders:
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

Prof. Hitesh Mhatre 3-24


Database Management Systems – 22319 CO-3I

Note: The FULL OUTER JOIN keyword returns all matching records from both tables whether
the other table matches or not. So, if there are rows in "Customers" that do not have matches
in "Orders", or if there are rows in "Orders" that do not have matches in "Customers", those
rows will be listed as well.

3.7 Sub-queries:
 A Subquery or Inner query or a Nested query is a query within another SQL query and
embedded within the WHERE clause.
 A subquery is used to return data that will be used in the main query as a condition to
further restrict the data to be retrieved.
 Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE
statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
 There are a few rules that subqueries must follow −
o Subqueries must be enclosed within parentheses.
o A subquery can have only one column in the SELECT clause, unless multiple
columns are in the main query for the subquery to compare its selected columns.
o An ORDER BY command cannot be used in a subquery, although the main
query can use an ORDER BY. The GROUP BY command can be used to
perform the same function as the ORDER BY in a subquery.
o Subqueries that return more than one row can only be used with multiple value
operators such as the IN operator.
o The SELECT list cannot include any references to values that evaluate to a
BLOB, ARRAY, CLOB, or NCLOB.
o A subquery cannot be immediately enclosed in a set function.
o The BETWEEN operator cannot be used with a subquery. However, the
BETWEEN operator can be used within the subquery.

1. Subqueries with the SELECT Statement


Subqueries are most frequently used with the SELECT statement. The basic syntax is as
follows −
SELECT column_name [, column_name]
FROM table1 [, table2]
WHERE column_name OPERATOR
(SELECT column_name [, column_name]
FROM table1 [, table2]
[WHERE])

Prof. Hitesh Mhatre 3-25


Database Management Systems – 22319 CO-3I

Example
Consider the CUSTOMERS table having the following records −

Now, let us check the following subquery with a SELECT statement.


SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500);
This would produce the following result.

2. Subqueries with the INSERT Statement


Subqueries also can be used with INSERT statements. The INSERT statement uses the data
returned from the subquery to insert into another table. The selected data in the subquery can
be modified with any of the character, date or number functions.
The basic syntax is as follows.
INSERT INTO table_name [ (column1 [, column2 ]) ]
SELECT [ *|column1 [, column2 ]
FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR ]

Prof. Hitesh Mhatre 3-26


Database Management Systems – 22319 CO-3I

Example
Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Now to
copy the complete CUSTOMERS table into the CUSTOMERS_BKP table, you can use the
following syntax.
INSERT INTO CUSTOMERS_BKP
SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS) ;

3. Subqueries with the UPDATE Statement


The subquery can be used in conjunction with the UPDATE statement. Either single or multiple
columns in a table can be updated when using a subquery with the UPDATE statement.
The basic syntax is as follows.
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Example
Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS
table. The following example updates SALARY by 0.25 times in the CUSTOMERS table for
all the customers whose AGE is greater than or equal to 27.
UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 27 );
This would impact two rows and finally CUSTOMERS table would have the following records.

Prof. Hitesh Mhatre 3-27


Database Management Systems – 22319 CO-3I

4. Subqueries with the DELETE Statement


The subquery can be used in conjunction with the DELETE statement like with any other
statements mentioned above.
The basic syntax is as follows.
DELETE FROM TABLE_NAME
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Example
Assuming, we have a CUSTOMERS_BKP table available which is a backup of the
CUSTOMERS table. The following example deletes the records from the CUSTOMERS table
for all the customers whose AGE is greater than or equal to 27.
DELETE FROM CUSTOMERS
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 27 );
This would impact two rows and finally the CUSTOMERS table would have the following
records.

3.8 Views:
3.8.1 CREATE VIEW Statement
 In SQL, a view is a virtual table based on the result-set of an SQL statement.
 A view contains rows and columns, just like a real table. The fields in a view are fields
from one or more real tables in the database.
 You can add SQL functions, WHERE, and JOIN statements to a view and present the
data as if the data were coming from one single table.

Prof. Hitesh Mhatre 3-28


Database Management Systems – 22319 CO-3I

CREATE VIEW Syntax


CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Note: A view always shows up-to-date data! The database engine recreates the data, using the
view's SQL statement, every time a user queries a view.

SQL CREATE VIEW Examples


The following SQL creates a view that shows all customers from Brazil:
CREATE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = 'Brazil';
We can query the view above as follows:
SELECT * FROM [Brazil Customers];

The following SQL creates a view that selects every product in the "Products" table with a
price higher than the average price:
CREATE VIEW [Products Above Average Price] AS
SELECT ProductName, Price
FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);
We can query the view above as follows:
SELECT * FROM [Products Above Average Price];

Prof. Hitesh Mhatre 3-29


Database Management Systems – 22319 CO-3I

3.8.2 SQL Updating a View


A view can be updated with the CREATE OR REPLACE VIEW command.

SQL CREATE OR REPLACE VIEW Syntax


CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
The following SQL adds the "City" column to the "Brazil Customers" view:
CREATE OR REPLACE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = 'Brazil';

3.8.3 SQL Dropping a View


A view is deleted with the DROP VIEW command.

SQL DROP VIEW Syntax


DROP VIEW view_name;

The following SQL drops the "Brazil Customers" view:


DROP VIEW [Brazil Customers];

Prof. Hitesh Mhatre 3-30


Database Management Systems – 22319 CO-3I

3.9 Sequences:
3.9.1 Creating SEQUENCES
 Sequence is a set of integers 1, 2, 3, … that are generated and supported by some
database systems to produce unique values on demand.
 A sequence is a user defined schema bound object that generates a sequence of numeric
values.
 Sequences are frequently used in many databases because many applications require
each row in a table to contain a unique value and sequences provides an easy way to
generate them.
 The sequence of numeric values is generated in an ascending or descending order at
defined intervals and can be configured to restart when exceeds max_value.
Syntax:
CREATE SEQUENCE sequence_name
START WITH initial_value
INCREMENT BY increment_value
MINVALUE minimum value
MAXVALUE maximum value
CYCLE|NOCYCLE ;
 sequence_name: Name of the sequence.
 initial_value: starting value from where the sequence starts. Initial_value
should be greater than or equal to minimum value and less than equal to
maximum value.

 increment_value: Value by which sequence will increment itself.


Increment_value can be positive or negative.
 minimum_value: Minimum value of the sequence.
 maximum_value: Maximum value of the sequence.
 cycle: When sequence reaches its set_limit it starts from beginning.
 nocycle: An exception will be thrown if sequence exceeds its max_value.

Example
Following is the sequence query creating sequence in ascending order.
CREATE SEQUENCE sequence_1
start with 1
increment by 1

Prof. Hitesh Mhatre 3-31


Database Management Systems – 22319 CO-3I

minvalue 0
maxvalue 100
cycle;
Above query will create a sequence named sequence_1.Sequence will start from 1 and will be
incremented by 1 having maximum value 100. Sequence will repeat itself from start value after
exceeding 100.
CREATE SEQUENCE sequence_2
start with 100
increment by -1
minvalue 1
maxvalue 100
cycle;
Above query will create a sequence named sequence_2.Sequence will start from 100 and
should be less than or equal to maximum value and will be incremented by -1 having minimum
value 1.
Example to use sequence: create a table named students with columns as id and name
CREATE TABLE students
(
ID number(10),
NAME char(20)
);

Now insert values into table


INSERT into students VALUES(sequence_1.nextval,'Ramesh');
INSERT into students VALUES(sequence_1.nextval,'Suresh');
Alternatively, you can create the table and then set the initial sequence value with ALTER
TABLE.
ALTER TABLE t AUTO_INCREMENT = 100;

3.9.2 Drop Sequence


Once you have created your sequence in Oracle, you might find that you need to remove it
from the database.
Syntax
The syntax to a drop a sequence in Oracle is:
DROP SEQUENCE sequence_name;

Prof. Hitesh Mhatre 3-32


Database Management Systems – 22319 CO-3I

 sequence_name: The name of the sequence that you wish to drop.


Example
Let's look at an example of how to drop a sequence in Oracle.
For example:
DROP SEQUENCE supplier_seq;

3.10 Indexes:
 Indexes are special lookup tables that the database search engine can use to speed up
data retrieval. Simply put, an index is a pointer to data in a table. An index in a database
is very similar to an index in the back of a book.
 For example, if you want to reference all pages in a book that discusses a certain topic,
you first refer to the index, which lists all the topics alphabetically and are then referred
to one or more specific page numbers.
 An index helps to speed up SELECT queries and WHERE clauses, but it slows down
data input, with the UPDATE and the INSERT statements. Indexes can be created or
dropped with no effect on the data.
 Creating an index involves the CREATE INDEX statement, which allows you to name
the index, to specify the table and which column or columns to index, and to indicate
whether the index is in an ascending or descending order.
 Indexes can also be unique, like the UNIQUE constraint, in that the index prevents
duplicate entries in the column or combination of columns on which there is an index.

The CREATE INDEX Command


The basic syntax of a CREATE INDEX is as follows.
CREATE INDEX index_name ON table_name;

Single-Column Indexes
A single-column index is created based on only one table column. The basic syntax is as
follows.
CREATE INDEX index_name
ON table_name (column_name);

Unique Indexes
Unique indexes are used not only for performance, but also for data integrity. A unique index
does not allow any duplicate values to be inserted into the table. The basic syntax is as follows.

Prof. Hitesh Mhatre 3-33


Database Management Systems – 22319 CO-3I

CREATE UNIQUE INDEX index_name


on table_name (column_name);

Composite Indexes
A composite index is an index on two or more columns of a table. Its basic syntax is as follows.
CREATE INDEX index_name
on table_name (column1, column2);
Whether to create a single-column index or a composite index, take into consideration the
column(s) that you may use very frequently in a query's WHERE clause as filter conditions.
Should there be only one column used, a single-column index should be the choice. Should
there be two or more columns that are frequently used in the WHERE clause as filters, the
composite index would be the best choice.

Implicit Indexes
Implicit indexes are indexes that are automatically created by the database server when an
object is created. Indexes are automatically created for primary key constraints and unique
constraints.

The DROP INDEX Command


An index can be dropped using SQL DROP command. Care should be taken when dropping
an index because the performance may either slow down or improve.
The basic syntax is as follows −
DROP INDEX index_name;

When should indexes be avoided?


Although indexes are intended to enhance a database's performance, there are times when they
should be avoided.
The following guidelines indicate when the use of an index should be reconsidered.
 Indexes should not be used on small tables.
 Tables that have frequent, large batch updates or insert operations.
 Indexes should not be used on columns that contain a high number of NULL values.
 Columns that are frequently manipulated should not be indexed.

Prof. Hitesh Mhatre 3-34


Database Management Systems – 22319 CO-3I

Prof. Hitesh Mhatre 3-35


Database Management Systems – 22319 CO-3I

Unit – IV: PL/SQL Programming

Course Outcomes (COs):

 Apply PL/SQL code for given database.


 Apply triggers on database also create procedures and functions according to
condition.

Unit Outcomes (UOs):

 Write simple PL/SQL code using control structure and handle various exceptions in
given situation.
 Create cursor for retrieving multiple records in the given situation.
 Create and execute stored procedures and functions in the given situation.
 Create and apply database trigger using PL/SQL in given situation.

4.1 PL/SQL Block 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.

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.

Prof. Hitesh Mhatre 4-1


Database Management Systems – 22319 CO-3I

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.
o This particular section is optional and can be skipped if no declarations are
needed.
o This should be the first section in a PL/SQL block, if present.
o This section starts with the keyword 'DECLARE' for triggers and anonymous
block. For other subprograms, this keyword will not be present. Instead, the part
after the subprogram name definition marks the declaration section.
o This section should always be followed by execution section.

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.
o This can contain both PL/SQL code and SQL code.
o This can contain one or many blocks inside it as a nested block.
o This section starts with the keyword 'BEGIN'.
o This section should be followed either by 'END' or Exception-Handling section
(if present)

Prof. Hitesh Mhatre 4-2


Database Management Systems – 22319 CO-3I

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.
o This is the section where the exception raised in the execution block is handled.
o This section is the last part of the PL/SQL block.
o Control from this section can never return to the execution block.
o This section starts with the keyword 'EXCEPTION'.
o This section should always be followed by the keyword 'END'.
o The Keyword 'END' marks the end of PL/SQL block.

4.2 PL/SQL Data Types, Variables, Constants


4.2.1 PL/SQL Datatypes:
 The PL/SQL variables, constants and parameters must have a valid data type, which
specifies a storage format, constraints, and a valid range of values.

Sr. No Category & Description

Scalar
1 Single values with no internal components, such as a NUMBER,
DATE, or BOOLEAN.

Large Object (LOB)


2 Pointers to large objects that are stored separately from other data items, such as
text, graphic images, video clips, and sound waveforms.

Composite
3 Data items that have internal components that can be accessed individually. For
example, collections and records.

Reference
4
Pointers to other data items.

PL/SQL Scalar Data Types and Subtypes


PL/SQL Scalar Data Types and Subtypes come under the following categories

S.No Date Type & Description

Numeric
1
Numeric values on which arithmetic operations are performed.

Character
2
Alphanumeric values that represent single characters or strings of characters.

Prof. Hitesh Mhatre 4-3


Database Management Systems – 22319 CO-3I

Boolean
3
Logical values on which logical operations are performed.

Datetime
4
Dates and times.

PL/SQL provides subtypes of data types. For example, the data type NUMBER has a subtype
called INTEGER. You can use the subtypes in your PL/SQL program to make the data types
compatible with data types in other programs while embedding the PL/SQL code in another
program, such as a Java program.

PL/SQL Numeric Data Types and Subtypes


Following table lists out the PL/SQL pre-defined numeric data types and their sub-types −

S.No Data Type & Description

PLS_INTEGER
1
Signed integer in range -2,147,483,648 to 2,147,483,647, represented in 32 bits

BINARY_INTEGER
2
Signed integer in range -2,147,483,648 to 2,147,483,647, represented in 32 bits

BINARY_FLOAT
3
Single-precision IEEE 754-format floating-point number

BINARY_DOUBLE
4
Double-precision IEEE 754-format floating-point number

NUMBER(prec, scale)
5 Fixed-point or floating-point number with absolute value in range 1E-130 to (but
not including) 1.0E126. A NUMBER variable can also represent 0

DEC(prec, scale)
6
ANSI specific fixed-point type with maximum precision of 38 decimal digits

DECIMAL(prec, scale)
7
IBM specific fixed-point type with maximum precision of 38 decimal digits

NUMERIC(pre, scale)
8
Floating type with maximum precision of 38 decimal digits

DOUBLE PRECISION
9
ANSI specific floating-point type with maximum precision of 126 binary digits

FLOAT
10 ANSI and IBM specific floating-point type with maximum precision of 126 binary
digits

Prof. Hitesh Mhatre 4-4


Database Management Systems – 22319 CO-3I

INT
11
ANSI specific integer type with maximum precision of 38 decimal digits

INTEGER
12
ANSI and IBM specific integer type with maximum precision of 38 decimal digits

SMALLINT
13
ANSI and IBM specific integer type with maximum precision of 38 decimal digits

REAL
14 Floating-point type with maximum precision of 63 binary digits (approximately 18
decimal digits)

PL/SQL Character Data Types and Subtypes


Following is the detail of PL/SQL pre-defined character data types and their sub-types −

S.No Data Type & Description

CHAR
1
Fixed-length character string with maximum size of 32,767 bytes

VARCHAR2
2
Variable-length character string with maximum size of 32,767 bytes

RAW
3 Variable-length binary or byte string with maximum size of 32,767 bytes, not
interpreted by PL/SQL

NCHAR
4
Fixed-length national character string with maximum size of 32,767 bytes

NVARCHAR2
5
Variable-length national character string with maximum size of 32,767 bytes

LONG
6
Variable-length character string with maximum size of 32,760 bytes

LONG RAW
7 Variable-length binary or byte string with maximum size of 32,760 bytes, not
interpreted by PL/SQL

ROWID
8
Physical row identifier, the address of a row in an ordinary table

UROWID
9
Universal row identifier (physical, logical, or foreign row identifier)

Prof. Hitesh Mhatre 4-5


Database Management Systems – 22319 CO-3I

PL/SQL Boolean Data Types


 The BOOLEAN data type stores logical values that are used in logical operations. The
logical values are the Boolean values TRUE and FALSE and the value NULL.
 However, SQL has no data type equivalent to BOOLEAN. Therefore, Boolean values
cannot be used in −
o SQL statements
o Built-in SQL functions (such as TO_CHAR)
o PL/SQL functions invoked from SQL statements

PL/SQL Datetime and Interval Types


 The DATE datatype is used to store fixed-length datetimes, which include the time of
day in seconds since midnight. Valid dates range from January 1, 4712 BC to December
31, 9999 AD.
 The default date format is set by the Oracle initialization parameter
NLS_DATE_FORMAT. For example, the default might be 'DD-MON-YY', which
includes a two-digit number for the day of the month, an abbreviation of the month
name, and the last two digits of the year. For example, 01-OCT-12.
 Each DATE includes the century, year, month, day, hour, minute, and second. The
following table shows the valid values for each field −

Field Name Valid Datetime Values Valid Interval Values

YEAR -4712 to 9999 (excluding year 0) Any nonzero integer

MONTH 01 to 12 0 to 11

01 to 31 (limited by the values of


DAY MONTH and YEAR, according to the Any nonzero integer
rules of the calendar for the locale)

HOUR 00 to 23 0 to 23

MINUTE 00 to 59 0 to 59

0 to 59.9(n), where 9(n)


00 to 59.9(n), where 9(n) is the is the precision of
SECOND
precision of time fractional seconds interval fractional
seconds

-12 to 14 (range accommodates


TIMEZONE_HOUR Not applicable
daylight savings time changes)

TIMEZONE_MINUTE 00 to 59 Not applicable

Prof. Hitesh Mhatre 4-6


Database Management Systems – 22319 CO-3I

Found in the dynamic performance


TIMEZONE_REGION Not applicable
view V$TIMEZONE_NAMES

Found in the dynamic performance


TIMEZONE_ABBR Not applicable
view V$TIMEZONE_NAMES

NULLs in PL/SQL
 PL/SQL NULL values represent missing or unknown data and they are not an integer,
a character, or any other specific data type. Note that NULL is not the same as an empty
data string or the null character value '\0'. A null can be assigned but it cannot be equated
with anything, including itself.

4.2.2 Variable Declaration in PL/SQL


 PL/SQL variables must be declared in the declaration section or in a package as a global
variable. When you declare a variable, PL/SQL allocates memory for the variable's
value and the storage location is identified by the variable name.
 The syntax for declaring a variable is −
variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT
initial_value]

 Where, variable_name is a valid identifier in PL/SQL, datatype must be a valid PL/SQL


data type or any user defined data type which we already have discussed in the last
chapter. Some valid variable declarations along with their definition are shown below
sales number(10, 2);
pi CONSTANT double precision := 3.1415;
name varchar2(25);
address varchar2(100);
 When you provide a size, scale or precision limit with the data type, it is called a
constrained declaration. Constrained declarations require less memory than
unconstrained declarations. For example −
sales number(10, 2);
name varchar2(25);
address varchar2(100);

Initializing Variables in PL/SQL


 Whenever you declare a variable, PL/SQL assigns it a default value of NULL. If you
want to initialize a variable with a value other than the NULL value, you can do so
during the declaration, using either of the following −

Prof. Hitesh Mhatre 4-7


Database Management Systems – 22319 CO-3I

o The DEFAULT keyword


o The assignment operator
 For example −
counter binary_integer := 0;
greetings varchar2(20) DEFAULT 'Have a Good Day';
 You can also specify that a variable should not have a NULL value using the NOT
NULL constraint. If you use the NOT NULL constraint, you must explicitly assign an
initial value for that variable.
 It is a good programming practice to initialize variables properly otherwise, sometimes
programs would produce unexpected results. Try the following example which makes
use of various types of variables −
DECLARE
a integer := 10;
b integer := 20;
c integer;
f real;
BEGIN
c := a + b;
dbms_output.put_line('Value of c: ' || c);
f := 70.0/3.0;
dbms_output.put_line('Value of f: ' || f);
END;
/
When the above code is executed, it produces the following result −
Value of c: 30
Value of f: 23.333333333333333333

PL/SQL procedure successfully completed.

Variable Scope in PL/SQL


 PL/SQL allows the nesting of blocks, i.e., each program block may contain another
inner block. If a variable is declared within an inner block, it is not accessible to the
outer block. However, if a variable is declared and accessible to an outer block, it is
also accessible to all nested inner blocks. There are two types of variable scope −
o Local variables − Variables declared in an inner block and not accessible to
outer blocks.

Prof. Hitesh Mhatre 4-8


Database Management Systems – 22319 CO-3I

o Global variables − Variables declared in the outermost block or a package.


 Following example shows the usage of Local and Global variables in its simple form −
DECLARE
-- Global variables
num1 number := 95;
num2 number := 85;
BEGIN
dbms_output.put_line('Outer Variable num1: ' || num1);
dbms_output.put_line('Outer Variable num2: ' || num2);
DECLARE
-- Local variables
num1 number := 195;
num2 number := 185;
BEGIN
dbms_output.put_line('Inner Variable num1: ' || num1);
dbms_output.put_line('Inner Variable num2: ' || num2);
END;
END;
/
When the above code is executed, it produces the following result −
Outer Variable num1: 95
Outer Variable num2: 85
Inner Variable num1: 195
Inner Variable num2: 185

PL/SQL procedure successfully completed.

Assigning SQL Query Results to PL/SQL Variables


You can use the SELECT INTO statement of SQL to assign values to PL/SQL variables. For
each item in the SELECT list, there must be a corresponding, type-compatible variable in the
INTO list. The following example illustrates the concept. Let us create a table named
CUSTOMERS −
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,

Prof. Hitesh Mhatre 4-9


Database Management Systems – 22319 CO-3I

ADDRESS CHAR (25),


SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Table Created
Let us now insert some values in the table −
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (6, 'Komal', 22, 'MP', 4500.00 );
The following program assigns values from the above table to PL/SQL variables using the
SELECT INTO clause of SQL −
DECLARE
c_id customers.id%type := 1;
c_name customers.name%type;
c_addr customers.address%type;
c_sal customers.salary%type;
BEGIN
SELECT name, address, salary INTO c_name, c_addr, c_sal
FROM customers
WHERE id = c_id;
dbms_output.put_line
('Customer'||c_name|| ' from ' || c_addr || ' earns ' || c_sal);
Prof. Hitesh Mhatre 4-10
Database Management Systems – 22319 CO-3I

END;
/
When the above code is executed, it produces the following result −
Customer Ramesh from Ahmedabad earns 2000
PL/SQL procedure completed successfully

4.2.3 Declaring a Constant


A constant is declared using the CONSTANT keyword. It requires an initial value and does
not allow that value to be changed. For example −
PI CONSTANT NUMBER := 3.141592654;

4.3 Control Structure-Conditional, Iterative, Sequential


4.3.1 Conditional Structure:
 Decision-making structures require that the programmer specify one or more conditions
to be evaluated or tested by the program, along with a statement or statements to be
executed if the condition is determined to be true, and optionally, other statements to
be executed if the condition is determined to be false.
 Following is the general form of a typical conditional (i.e., decision making) structure
found in most of the programming languages −

PL/SQL programming language provides following types of decision-making statements.

Prof. Hitesh Mhatre 4-11


Database Management Systems – 22319 CO-3I

S.No Statement & Description

IF - THEN statement
The IF statement associates a condition with a sequence of statements enclosed by the
1
keywords THEN and END IF. If the condition is true, the statements get executed and if
the condition is false or NULL then the IF statement does nothing.

IF-THEN-ELSE statement
IF statement adds the keyword ELSE followed by an alternative sequence of statement. If
2
the condition is false or NULL, then only the alternative sequence of statements get
executed. It ensures that either of the sequence of statements is executed.

IF-THEN-ELSIF statement
3
It allows you to choose between several alternatives.

Case statement
Like the IF statement, the CASE statement selects one sequence of statements to execute.
4 However, to select the sequence, the CASE statement uses a selector rather than multiple
Boolean expressions. A selector is an expression whose value is used to select one of
several alternatives.

Searched CASE statement


5 The searched CASE statement has no selector, and it's WHEN clauses contain search
conditions that yield Boolean values.

nested IF-THEN-ELSE
6 You can use one IF-THEN or IF-THEN-ELSIF statement inside another IF-THEN or IF-
THEN-ELSIF statement(s).

4.3.1.1 IF Statement
The IF statement associates a condition with a sequence of statements enclosed by the
keywords THEN and END IF. If the condition is TRUE, the statements get executed, and if
the condition is FALSE or NULL, then the IF statement does nothing.
Syntax for IF-THEN statement is −
IF condition THEN
S;
END IF;
Where condition is a Boolean or relational condition and S is a simple or compound statement.
DECLARE
a number(2) := 10;
BEGIN
a:= 10;
-- check the boolean condition using if statement
IF( a < 20 ) THEN
-- if condition is true then print the following

Prof. Hitesh Mhatre 4-12


Database Management Systems – 22319 CO-3I

dbms_output.put_line('a is less than 20 ' );


END IF;
dbms_output.put_line('value of a is : ' || a);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
a is less than 20
value of a is : 10
PL/SQL procedure successfully completed.

4.3.1.2 IF-THEN_ELSE
 A sequence of IF-THEN statements can be followed by an optional sequence of ELSE
statements, which execute when the condition is FALSE.
 Syntax for the IF-THEN-ELSE statement is −
IF condition THEN
S1;
ELSE
S2;
END IF;
Where, S1 and S2 are different sequence of statements. In the IF-THEN-ELSE statements,
when the test condition is TRUE, the statement S1 is executed and S2 is skipped; when the test
condition is FALSE, then S1 is bypassed and statement S2 is executed.
DECLARE
a number(3) := 100;
BEGIN
-- check the boolean condition using if statement
IF( a < 20 ) THEN
-- if condition is true then print the following
dbms_output.put_line('a is less than 20 ' );
ELSE
dbms_output.put_line('a is not less than 20 ' );
END IF;
dbms_output.put_line('value of a is : ' || a);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −

Prof. Hitesh Mhatre 4-13


Database Management Systems – 22319 CO-3I

a is not less than 20


value of a is : 100
PL/SQL procedure successfully completed.

4.3.1.3 IF-THEN-ELSEIF:
 The IF-THEN-ELSIF statement allows you to choose between several alternatives. An
IF-THEN statement can be followed by an optional ELSIF...ELSE statement. The
ELSIF clause lets you add additional conditions.
 When using IF-THEN-ELSIF statements there are a few points to keep in mind.
o It's ELSEIF, not ELSEIF.
o An IF-THEN statement can have zero or one ELSE's and it must come after any
ELSEIF's.
o An IF-THEN statement can have zero to many ELSEIF's and they must come
before the ELSE.
o Once an ELSEIF succeeds, none of the remaining ELSEIF's or ELSE's will be
tested.
 The syntax of an IF-THEN-ELSIF Statement in PL/SQL programming language is −
IF(boolean_expression 1)THEN
S1; -- Executes when the boolean expression 1 is true
ELSIF( boolean_expression 2) THEN
S2; -- Executes when the boolean expression 2 is true
ELSIF( boolean_expression 3) THEN
S3; -- Executes when the boolean expression 3 is true
ELSE
S4; -- executes when the none of the above condition is true
END IF;
Example:
DECLARE
a number(3) := 100;
BEGIN
IF ( a = 10 ) THEN
dbms_output.put_line('Value of a is 10' );
ELSIF ( a = 20 ) THEN
dbms_output.put_line('Value of a is 20' );
ELSIF ( a = 30 ) THEN
dbms_output.put_line('Value of a is 30' );

Prof. Hitesh Mhatre 4-14


Database Management Systems – 22319 CO-3I

ELSE
dbms_output.put_line('None of the values is matching');
END IF;
dbms_output.put_line('Exact value of a is: '|| a );
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
None of the values is matching
Exact value of a is: 100
PL/SQL procedure successfully completed.

4.3.1.4 CASE Statement:


 Like the IF statement, the CASE statement selects one sequence of statements to
execute. However, to select the sequence, the CASE statement uses a selector rather
than multiple Boolean expressions. A selector is an expression, the value of which is
used to select one of several alternatives.
 The syntax for the case statement in PL/SQL is −
CASE selector
WHEN 'value1' THEN S1;
WHEN 'value2' THEN S2;
WHEN 'value3' THEN S3;
...
ELSE Sn; -- default case
END CASE;
Example
DECLARE
grade char(1) := 'A';
BEGIN
CASE grade
when 'A' then dbms_output.put_line('Excellent');
when 'B' then dbms_output.put_line('Very good');
when 'C' then dbms_output.put_line('Well done');
when 'D' then dbms_output.put_line('You passed');
when 'F' then dbms_output.put_line('Better try again');
else dbms_output.put_line('No such grade');
END CASE;

Prof. Hitesh Mhatre 4-15


Database Management Systems – 22319 CO-3I

END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Excellent
PL/SQL procedure successfully completed.

4.3.1.5 Searched CASE


 The searched CASE statement has no selector and the WHEN clauses of the statement
contain search conditions that give Boolean values.
 The syntax for the searched case statement in PL/SQL is −
CASE
WHEN selector = 'value1' THEN S1;
WHEN selector = 'value2' THEN S2;
WHEN selector = 'value3' THEN S3;
...
ELSE Sn; -- default case
END CASE;
Example
DECLARE
grade char(1) := 'B';
BEGIN
case
when grade = 'A' then dbms_output.put_line('Excellent');
when grade = 'B' then dbms_output.put_line('Very good');
when grade = 'C' then dbms_output.put_line('Well done');
when grade = 'D' then dbms_output.put_line('You passed');
when grade = 'F' then dbms_output.put_line('Better try
again');
else dbms_output.put_line('No such grade');
end case;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Very good
PL/SQL procedure successfully completed.

Prof. Hitesh Mhatre 4-16


Database Management Systems – 22319 CO-3I

4.1.3.6 NESTED IF-THEN-ELSE:


 It is always legal in PL/SQL programming to nest the IF-ELSE statements, which
means you can use one IF or ELSE IF statement inside another IF or ELSE IF
statement(s).
IF( boolean_expression 1)THEN
-- executes when the boolean expression 1 is true
IF(boolean_expression 2) THEN
-- executes when the boolean expression 2 is true
sequence-of-statements;
END IF;
ELSE
-- executes when the boolean expression 1 is not true
else-statements;
END IF;
Example
DECLARE
a number(3) := 100;
b number(3) := 200;
BEGIN
-- check the boolean condition
IF( a = 100 ) THEN
-- if condition is true then check the following
IF( b = 200 ) THEN
-- if condition is true then print the following
dbms_output.put_line('Value of a is 100 and b is 200' );
END IF;
END IF;
dbms_output.put_line('Exact value of a is : ' || a );
dbms_output.put_line('Exact value of b is : ' || b );
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
PL/SQL procedure successfully completed.

Prof. Hitesh Mhatre 4-17


Database Management Systems – 22319 CO-3I

4.3.2 LOOPS
 There may be a situation when you need to execute a block of code several number of
times.
 In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on.
 Programming languages provide various control structures that allow for more
complicated execution paths.
 A loop statement allows us to execute a statement or group of statements multiple times
and following is the general form of a loop statement in most of the programming
languages

 PL/SQL provides the following types of loop to handle the looping requirements. Click
the following links to check their detail

S.No Loop Type & Description

PL/SQL Basic LOOP


In this loop structure, sequence of statements is enclosed between the LOOP and the END
1
LOOP statements. At each iteration, the sequence of statements is executed and then
control resumes at the top of the loop.

PL/SQL WHILE LOOP


2 Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.

PL/SQL FOR LOOP


3 Execute a sequence of statements multiple times and abbreviates the code that manages the
loop variable.

Nested loops in PL/SQL


4
You can use one or more loop inside any another basic loop, while, or for loop.

Prof. Hitesh Mhatre 4-18


Database Management Systems – 22319 CO-3I

4.3.2.2 BASIC LOOP


Basic loop structure encloses sequence of statements in between the LOOP and END LOOP
statements. With each iteration, the sequence of statements is executed and then control
resumes at the top of the loop.
The syntax of a basic loop in PL/SQL programming language is −
LOOP
Sequence of statements;
END LOOP;
Here, the sequence of statement(s) may be a single statement or a block of statements. An EXIT
statement or an EXIT WHEN statement is required to break the loop.
Example
DECLARE
x number := 10;
BEGIN
LOOP
dbms_output.put_line(x);
x := x + 10;
IF x > 50 THEN
exit;
END IF;
END LOOP;
-- after exit, control resumes here
dbms_output.put_line('After Exit x is: ' || x);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
10
20
30
40
50
After Exit x is: 60
PL/SQL procedure successfully completed.

Prof. Hitesh Mhatre 4-19


Database Management Systems – 22319 CO-3I

4.3.2.2 WHILE LOOP:


 A WHILE LOOP statement in PL/SQL programming language repeatedly executes a
target statement as long as a given condition is true.
WHILE condition LOOP
sequence_of_statements
END LOOP;
Example
DECLARE
a number(2) := 10;
BEGIN
WHILE a < 20 LOOP
dbms_output.put_line('value of a: ' || a);
a := a + 1;
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
PL/SQL procedure successfully completed.

4.3.2.3 FOR LOOP:


 A FOR LOOP is a repetition control structure that allows you to efficiently write a loop
that needs to execute a specific number of times.
FOR counter IN initial_value .. final_value LOOP
sequence_of_statements;
END LOOP;

Prof. Hitesh Mhatre 4-20


Database Management Systems – 22319 CO-3I

 Following is the flow of control in a For Loop −


o The initial step is executed first, and only once. This step allows you to declare
and initialize any loop control variables.
o Next, the condition, i.e., initial_value .. final_value is evaluated. If it is TRUE,
the body of the loop is executed. If it is FALSE, the body of the loop does not
execute and the flow of control jumps to the next statement just after the for
loop.
o After the body of the for loop executes, the value of the counter variable is
increased or decreased.
o The condition is now evaluated again. If it is TRUE, the loop executes and the
process repeats itself (body of loop, then increment step, and then again
condition). After the condition becomes FALSE, the FOR-LOOP terminates.
 Following are some special characteristics of PL/SQL for loop −
o The initial_value and final_value of the loop variable or counter can be literals,
variables, or expressions but must evaluate to numbers. Otherwise, PL/SQL
raises the predefined exception VALUE_ERROR.
o The initial_value need not be 1; however, the loop counter increment (or
decrement) must be 1.
o PL/SQL allows the determination of the loop range dynamically at run time.
Example
DECLARE
a number(2);
BEGIN
FOR a in 10 .. 20 LOOP
dbms_output.put_line('value of a: ' || a);
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17

Prof. Hitesh Mhatre 4-21


Database Management Systems – 22319 CO-3I

value of a: 18
value of a: 19
value of a: 20
PL/SQL procedure successfully completed.

Reverse FOR LOOP Statement


 By default, iteration proceeds from the initial value to the final value, generally upward
from the lower bound to the higher bound. You can reverse this order by using the
REVERSE keyword. In such case, iteration proceeds the other way. After each
iteration, the loop counter is decremented.
 However, you must write the range bounds in ascending (not descending) order. The
following program illustrates this −
DECLARE
a number(2) ;
BEGIN
FOR a IN REVERSE 10 .. 20 LOOP
dbms_output.put_line('value of a: ' || a);
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 20
value of a: 19
value of a: 18
value of a: 17
value of a: 16
value of a: 15
value of a: 14
value of a: 13
value of a: 12
value of a: 11
value of a: 10
PL/SQL procedure successfully completed.

Prof. Hitesh Mhatre 4-22


Database Management Systems – 22319 CO-3I

4.4 Exception Handling-Predefined, User defined


 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
o System-defined exceptions
o User-defined exceptions
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
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;

Prof. Hitesh Mhatre 4-23


Database Management Systems – 22319 CO-3I

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;
/
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.

Prof. Hitesh Mhatre 4-24


Database Management Systems – 22319 CO-3I

4.4.1 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 −
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;
/

Prof. Hitesh Mhatre 4-25


Database Management Systems – 22319 CO-3I

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.

4.4.2 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


ACCESS_INTO_NULL 06530 -6530
automatically 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
COLLECTION_IS_NULL 06531 -6531
the program attempts to assign values to the
elements of an uninitialized nested table or
varray.

It is raised when duplicate values are


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

It is raised when attempts are made to make


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

It is raised when the conversion of a


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

It is raised when a program attempts to log


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

It is raised when a SELECT INTO statement


NO_DATA_FOUND 01403 +100
returns no rows.

Prof. Hitesh Mhatre 4-26


Database Management Systems – 22319 CO-3I

It is raised when a database call is issued


NOT_LOGGED_ON 01012 -1012
without 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


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

It is raised when PL/SQL ran out of memory


STORAGE_ERROR 06500 -6500
or 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


ZERO_DIVIDE 01476 1476
divide a number by zero.

4.5 Cursors
 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.
 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
o Implicit cursors
o Explicit cursors

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

Prof. Hitesh Mhatre 4-27


Database Management Systems – 22319 CO-3I

 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 −

%FOUND - 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 - 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.
%ISOPEN - Always returns FALSE for implicit cursors, because Oracle closes the SQL
cursor automatically after executing its associated SQL statement.
%ROWCOUNT - 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.
Select * from customers;

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

Prof. Hitesh Mhatre 4-28


Database Management Systems – 22319 CO-3I

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;
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;

4.5.2 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 −
o Declaring the cursor for initializing the memory
o Opening the cursor for allocating the memory
o Fetching the cursor for retrieving the data
o Closing the cursor to release the allocated memory

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;
Prof. Hitesh Mhatre 4-29
Database Management Systems – 22319 CO-3I

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 customer.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);
END LOOP;
CLOSE c_customers;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −

Prof. Hitesh Mhatre 4-30


Database Management Systems – 22319 CO-3I

1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP
PL/SQL procedure successfully completed.

4.6 Procedures
 A subprogram is a program unit/module that performs a particular task. These
subprograms are combined to form larger programs. This is basically called the
'Modular design'. A subprogram can be invoked by another subprogram or program
which is called the calling program.
 A subprogram can be created −
o At the schema level
o Inside a package
o Inside a PL/SQL block
 At the schema level, subprogram is a standalone subprogram. It is created with the
CREATE PROCEDURE or the CREATE FUNCTION statement. It is stored in the
database and can be deleted with the DROP PROCEDURE or DROP FUNCTION
statement.

Creating a Procedure
A procedure is created with the CREATE OR REPLACE PROCEDURE statement. The
simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
BEGIN
< procedure_body >
END procedure_name;
Where,
 procedure-name specifies the name of the procedure.
 [OR REPLACE] option allows the modification of an existing procedure.

Prof. Hitesh Mhatre 4-31


Database Management Systems – 22319 CO-3I

 The optional parameter list contains name, mode and types of the parameters. IN
represents the value that will be passed from outside and OUT represents the parameter
that will be used to return a value outside of the procedure.
 procedure-body contains the executable part.
 The AS keyword is used instead of the IS keyword for creating a standalone procedure.
Example
The following example creates a simple procedure that displays the string 'Hello World!' on
the screen when executed.
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/
When the above code is executed using the SQL prompt, it will produce the following result −
Procedure created.

Executing a Standalone Procedure


A standalone procedure can be called in two ways −
 Using the EXECUTE keyword
 Calling the name of the procedure from a PL/SQL block
The above procedure named 'greetings' can be called with the EXECUTE keyword as −
EXECUTE greetings;
The above call will display −
Hello World
PL/SQL procedure successfully completed.
The procedure can also be called from another PL/SQL block −
BEGIN
greetings;
END;
/
The above call will display −
Hello World
PL/SQL procedure successfully completed.

Prof. Hitesh Mhatre 4-32


Database Management Systems – 22319 CO-3I

Deleting a Standalone Procedure


A standalone procedure is deleted with the DROP PROCEDURE statement. Syntax for
deleting a procedure is −
DROP PROCEDURE procedure-name;
You can drop the greetings procedure by using the following statement −
DROP PROCEDURE greetings;

Parameter Modes in PL/SQL Subprograms


The following table lists out the parameter modes in PL/SQL subprograms

Sr .No Parameter Mode & Description

IN
An IN parameter lets you pass a value to the subprogram. It is a read-only parameter.
Inside the subprogram, an IN parameter acts like a constant. It cannot be assigned a
1 value. You can pass a constant, literal, initialized variable, or expression as an IN
parameter. You can also initialize it to a default value; however, in that case, it is omitted
from the subprogram call. It is the default mode of parameter passing. Parameters are
passed by reference.

OUT
An OUT parameter returns a value to the calling program. Inside the subprogram, an
2
OUT parameter acts like a variable. You can change its value and reference the value
after assigning it. The actual parameter must be variable and it is passed by value.

IN OUT
An IN OUT parameter passes an initial value to a subprogram and returns an updated
value to the caller. It can be assigned a value and the value can be read.
3
The actual parameter corresponding to an IN OUT formal parameter must be a variable,
not a constant or an expression. Formal parameter must be assigned a value. Actual
parameter is passed by value.

IN & OUT Mode Example


This program finds the minimum of two values. Here, the procedure takes two numbers using
the IN mode and returns their minimum using the OUT parameters.
DECLARE
a number;
b number;
c number;
PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
BEGIN
IF x < y THEN
z:= x;

Prof. Hitesh Mhatre 4-33


Database Management Systems – 22319 CO-3I

ELSE
z:= y;
END IF;
END;
BEGIN
a:= 23;
b:= 45;
findMin(a, b, c);
dbms_output.put_line(' Minimum of (23, 45) : ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Minimum of (23, 45) : 23
PL/SQL procedure successfully completed.

4.7 Functions
4.7.1 Creating a Function
 A standalone function is created using the CREATE FUNCTION statement. The
simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as
follows
CREATE [OR REPLACE] FUNCTION function_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];
Where,
 function-name specifies the name of the function.
 [OR REPLACE] option allows the modification of an existing function.
 The optional parameter list contains name, mode and types of the parameters. IN
represents the value that will be passed from outside and OUT represents the parameter
that will be used to return a value outside of the procedure.
 The function must contain a return statement.
 The RETURN clause specifies the data type you are going to return from the function.

Prof. Hitesh Mhatre 4-34


Database Management Systems – 22319 CO-3I

 function-body contains the executable part.


 The AS keyword is used instead of the IS keyword for creating a standalone function.

Example
The following example illustrates how to create and call a standalone function. This function
returns the total number of CUSTOMERS in the customers table.
We will use the CUSTOMERS table
Select * from customers;

CREATE OR REPLACE FUNCTION totalCustomers


RETURN number IS
total number(2) := 0;
BEGIN
SELECT count(*) into total
FROM customers;

RETURN total;
END;
/
When the above code is executed using the SQL prompt, it will produce the following result −
Function created.

4.7.2 Calling a Function


 While creating a function, you 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. When a
program calls a function, the program control is transferred to the called function.
 A called function performs the defined task and when its return statement is executed
or when the last end statement is reached, it returns the program control back to the
main program.

Prof. Hitesh Mhatre 4-35


Database Management Systems – 22319 CO-3I

 To call a function, you simply need to pass the required parameters along with the
function name and if the function returns a value, then you can store the returned value.
Following program calls the function totalCustomers from an anonymous block −
DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Total no. of Customers: 6
PL/SQL procedure successfully completed.
Example
The following example demonstrates Declaring, Defining, and Invoking a Simple PL/SQL
Function that computes and returns the maximum of two values.
DECLARE
a number;
b number;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;
RETURN z;
END;
BEGIN
a:= 23;
b:= 45;
c := findMax(a, b);

Prof. Hitesh Mhatre 4-36


Database Management Systems – 22319 CO-3I

dbms_output.put_line(' Maximum of (23,45): ' || c);


END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Maximum of (23,45): 45
PL/SQL procedure successfully completed.

4.7.3 PL/SQL Recursive Functions


 We have seen that a program or subprogram may call another subprogram. When a
subprogram calls itself, it is referred to as a recursive call and the process is known as
recursion.
 To illustrate the concept, let us calculate the factorial of a number. Factorial of a number
n is defined as −
n! = n*(n-1)!
= n*(n-1)*(n-2)!
...
= n*(n-1)*(n-2)*(n-3)... 1
The following program calculates the factorial of a given number by calling itself recursively
DECLARE
num number;
factorial number;

FUNCTION fact(x number)


RETURN number
IS
f number;
BEGIN
IF x=0 THEN
f := 1;
ELSE
f := x * fact(x-1);
END IF;
RETURN f;
END;

BEGIN

Prof. Hitesh Mhatre 4-37


Database Management Systems – 22319 CO-3I

num:= 6;
factorial := fact(num);
dbms_output.put_line(' Factorial '|| num || ' is ' ||
factorial);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Factorial 6 is 720
PL/SQL procedure successfully completed.

4.8 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 −
o A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
o A database definition (DDL) statement (CREATE, ALTER, or DROP).
o A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
o Triggers can be defined on the table, view, schema, or database with which the
event is associated.

4.8.1 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

4.8.2 Creating Triggers


The syntax for creating a trigger is −
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }

Prof. Hitesh Mhatre 4-38


Database Management Systems – 22319 CO-3I

{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
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
Select * from customers;

Prof. Hitesh Mhatre 4-39


Database Management Systems – 22319 CO-3I

 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
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.
Prof. Hitesh Mhatre 4-40
Database Management Systems – 22319 CO-3I

4.8.3 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:
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

Prof. Hitesh Mhatre 4-41


Database Management Systems – 22319 CO-3I

Unit – V: Database Security and Transaction Processing

Course Outcomes (COs):

 Apply security and confidentiality on given database.

Unit Outcomes (UOs):

 Provide security to the given database by assigning various privileges to the user.
 Create and manage the given database users.
 Explain the importance of transaction in the given situation.
 Explain advantages of database backup and recovery in the given situation.

5.1 Database Security:


 Database security concerns the use of a broad range of information security controls to
protect databases (potentially including the data, the database applications or stored
functions, the database systems, the database servers and the associated network links)
against compromises of their confidentiality, integrity and availability.
 It involves various types or categories of controls, such as technical,
procedural/administrative and physical.
 Security risks to database systems include, for example:
o Unauthorized or unintended activity or misuse by authorized database users,
database administrators, or network/systems managers, or by unauthorized
users or hackers (e.g. inappropriate access to sensitive data, metadata or
functions within databases, or inappropriate changes to the database programs,
structures or security configurations);
o Malware infections causing incidents such as unauthorized access, leakage or
disclosure of personal or proprietary data, deletion of or damage to the data or
programs, interruption or denial of authorized access to the database, attacks on
other systems and the unanticipated failure of database services;
o Overloads, performance constraints and capacity issues resulting in the inability
of authorized users to use databases as intended;
o Physical damage to database servers caused by computer room fires or floods,
overheating, lightning, accidental liquid spills, static discharge, electronic
breakdowns/equipment failures and obsolescence;
o Design flaws and programming bugs in databases and the associated programs
and systems, creating various security vulnerabilities (e.g. unauthorized
privilege escalation), data loss/corruption, performance degradation etc.;

Prof. Hitesh Mhatre 5-1


Database Management Systems – 22319 CO-3I

o Data corruption and/or loss caused by the entry of invalid data or commands,
mistakes in database or system administration processes, sabotage/criminal
damage etc.

Privileges
 Two types of privileges are important relating to database security within the database
environment: system privileges and object privileges.
o System privileges allow a user to perform administrative actions in a database.
o Object privileges allow for the use of certain operations on database objects as
authorized by another user. Examples include: usage, select, insert, update, and
references.

5.2 Transactions
 The transaction is a set of logically related operation. It contains a group of tasks.
 A transaction is an action or series of actions. It is performed by a single user to perform
operations for accessing the contents of the database.
 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
Open_Account(X)
Old_Balance = X.balance
New_Balance = Old_Balance - 800
X.balance = New_Balance
Close_Account(X)

Y's Account
Open_Account(Y)
Old_Balance = Y.balance
New_Balance = Old_Balance + 800
Y.balance = New_Balance
Close_Account(Y)
Operations of Transaction:
Following are the main operations of transaction:

Prof. Hitesh Mhatre 5-2


Database Management Systems – 22319 CO-3I

Read(X): Read operation is used to read the value of X from the database and stores it in a
buffer in main memory.
Write(X): Write operation is used to write the value back to the database from the buffer.
Let's take an example to debit transaction from an account which consists of following
operations:
1. R(X);
2. X = X - 500;
3. W(X);
Let's assume the value of X before starting of the transaction is 4000.
 The first operation reads X's value from database and stores it in a buffer.
 The second operation will decrease the value of X by 500. So buffer will contain 3500.
 The third operation will write the buffer's value to the database. So X's final value will
be 3500.
 But it may be possible that because of the failure of hardware, software or power, etc.
that transaction may fail before finished all the operations in the set.
 For example: If in the above transaction, the debit transaction fails after executing
operation 2 then X's value will remain 4000 in the database which is not acceptable by
the bank.
 To solve this problem, we have two important operations:
 Commit: It is used to save the work done permanently.
 Rollback: It is used to undo the work done.

5.2.1 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
o Atomicity
o Consistency
o Isolation
o Durability

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

Prof. Hitesh Mhatre 5-3


Database Management Systems – 22319 CO-3I

 Atomicity involves the following two operations:


o Abort: If a transaction aborts then all the changes made are not visible.
o 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.

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


 If the transaction T fails after the completion of transaction T1 but before completion
of transaction T2, then the amount will be deducted from A but not added to B. This
shows the inconsistent database state. In order to ensure correctness of database state,
the transaction must be executed in entirety.

Consistency
 The integrity constraints are maintained so that the database is consistent before and
after the transaction.
 The execution of a transaction will leave a database in either its prior stable state or a
new stable state.
 The consistent property of database states that every transaction sees a consistent
database instance.
 The transaction is used to transform the database from one consistent state to another
consistent state.
 For example: The total amount must be maintained before or after the transaction.
Total before T occurs = 600+300=900
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
 It shows that the data which is used at the time of execution of a transaction cannot be
used by the second transaction until the first one is completed.
 In isolation, if the transaction T1 is being executed and using the data item X, then that
data item can't be accessed by any other transaction T2 until the transaction T1 ends.
 The concurrency control subsystem of the DBMS enforced the isolation property.

Prof. Hitesh Mhatre 5-4


Database Management Systems – 22319 CO-3I

Durability
 The durability property is used to indicate the performance of the database's consistent
state. It states that the transaction made the permanent changes.
 They cannot be lost by the erroneous operation of a faulty transaction or by the system
failure. When a transaction is completed, then the database reaches a state known as the
consistent state. That consistent state cannot be lost, even in the event of a system's
failure.
 The recovery subsystem of the DBMS has the responsibility of Durability property.

5.2.2 States of Transaction


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

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

Partially committed
 In the partially committed state, a transaction executes its final operation, but the data
is still not saved to the database.
 In the total mark calculation example, a final display of the total marks step is executed
in this state.

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.

Prof. Hitesh Mhatre 5-5


Database Management Systems – 22319 CO-3I

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

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

5.3 Database Backup


 It is imperative to have a backup of the database in case the original is corrupted or lost
because of any reason. Using this backup, the database can be recovered as it was before
the failure.
 Database backup basically means that a duplicate of the database information and data
is created and stored in backup server just to be on the safe side. Transaction logs are
also stored in the backup along with the database data because without them, the data
would be useless.

5.3.1 Reasons of Failure in a Database


 There can be multiple reasons of failure in a database because of which a database
backup and recovery plan is required. Some of these reasons are:
o User Error: Normally, user error is the biggest reason of data destruction or
corruption in a database. To rectify the error, the database needs to be restored
to the point in time before the error occurred.
o Hardware Failure: This can also lead to loss of data in a database. The database
is stored on multiple hard drives across various locations. These hard drives may
sometimes malfunction leading to database corruption. So, it is important to
periodically change them.

Prof. Hitesh Mhatre 5-6


Database Management Systems – 22319 CO-3I

o Catastrophic Event: A catastrophic event can be a natural calamity like a flood


or earthquake or deliberate sabotage such as hacking of the database. Either
way, the database data may be corrupted or backup may be required.

5.3.2 Methods of Backup


 The different methods of backup in a database are:
o Full Backup: This method takes a lot of time as the full copy of the database is
made including the data and the transaction records.
o Transaction Log: Only the transaction logs are saved as the backup in this
method. To keep the backup file as small as possible, the previous transaction
log details are deleted once a new backup record is made.
o Differential Backup: This is similar to full backup in that it stores both the data
and the transaction records. However only that information is saved in the
backup that has changed since the last full backup. Because of this, differential
backup leads to smaller files.

5.4 Database Recovery


 When a system crashes, it may have several transactions being executed and various
files opened for them to modify the data items. Transactions are made of various
operations, which are atomic in nature. But according to ACID properties of DBMS,
atomicity of transactions as a whole must be maintained, that is, either all the operations
are executed or none.
 When a DBMS recovers from a crash, it should maintain the following −
o It should check the states of all the transactions, which were being executed.
o A transaction may be in the middle of some operation; the DBMS must ensure
the atomicity of the transaction in this case.
o It should check whether the transaction can be completed now or it needs to be
rolled back.
o No transactions would be allowed to leave the DBMS in an inconsistent state.
 There are two types of techniques, which can help a DBMS in recovering as well as
maintaining the atomicity of a transaction –
o Maintaining the logs of each transaction, and writing them onto some stable
storage before actually modifying the database.
o Maintaining shadow paging, where the changes are done on a volatile memory,
and later, the actual database is updated.

Prof. Hitesh Mhatre 5-7


Database Management Systems – 22319 CO-3I

5.4.1 Log-based Recovery


 Log is a sequence of records, which maintains the records of actions performed by a
transaction. It is important that the logs are written prior to the actual modification and
stored on a stable storage media, which is failsafe.
 Log-based recovery works as follows −
o The log file is kept on a stable storage media.
o When a transaction enters the system and starts execution, it writes a log about
it.
<Tn, Start>
 When the transaction modifies an item X, it write logs as follows −
<Tn, X, V1, V2>
 It reads Tn has changed the value of X, from V1 to V2.
 When the transaction finishes, it logs −
<Tn, commit>

 The database can be modified using two approaches −


o Deferred database modification − All logs are written on to the stable storage
and the database is updated when a transaction commits.
o Immediate database modification − Each log follows an actual database
modification. That is, the database is modified immediately after every
operation.

5.4.2 Recovery with Concurrent Transactions


 When more than one transaction are being executed in parallel, the logs are interleaved.
At the time of recovery, it would become hard for the recovery system to backtrack all
logs, and then start recovering. To ease this situation, most modern DBMS use the
concept of 'checkpoints'.
Checkpoint
Keeping and maintaining logs in real time and in real environment may fill out all the memory
space available in the system. As time passes, the log file may grow too big to be handled at
all. Checkpoint is a mechanism where all the previous logs are removed from the system and
stored permanently in a storage disk. Checkpoint declares a point before which the DBMS was
in consistent state, and all the transactions were committed.
Recovery
When a system with concurrent transactions crashes and recovers, it behaves in the following
manner −

Prof. Hitesh Mhatre 5-8


Database Management Systems – 22319 CO-3I

o The recovery system reads the logs backwards from the end to the last
checkpoint.
o It maintains two lists, an undo-list and a redo-list.
o If the recovery system sees a log with <Tn, Start> and <Tn, Commit> or just
<Tn, Commit>, it puts the transaction in the redo-list.
o If the recovery system sees a log with <Tn, Start> but no commit or abort log
found, it puts the transaction in undo-list.
 All the transactions in the undo-list are then undone and their logs are removed. All the
transactions in the redo-list and their previous logs are removed and then redone before
saving their logs.

Prof. Hitesh Mhatre 5-9

You might also like