Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

DBMS Complete Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 47

Database Management System

UNIT-1
Overview Of Database Management System
INTRODUCTION:

Data:
Data is defined as a collection of raw facts or data items placed in a file.
Example: Student marks details (rno,name,marks), employee details(empno, name, salary) .

Information:
Information is the result of processing raw data to reveal its meaning. Processed data is called
information or result of data processing.
Example: students who get 70 marks in computers.

Field:
A character or group of characters that has a specific meaning. A field is used to define and store
data. It is also called attribute.
Example:

Record:
A record can be defined as collection of fields or attributes.
Example:

File:
A File can be defined as collection of records.

End Users:
The users who should process daily operations of an organization using database application
program.
1|Page
Database Management System
Meta Data:
Meta Data is nothing but Data about Data. It helps fastest data accessing mechanism.
It provides a description of data characteristics and set of relationships that link the data found within
the database (self describing data called meta data)
Example: Index of the text book.

Database:
a. A Database can be defined as collection of inter related files.
b. It is a shared-integrated computer structure that stores both end users data and meta data.
c. In database the data is independent of programs. In database data sharing refers multi users and
programs processing done simultaneously.
Example: Student marks system, Employee salary System

DBMS:

a. DBMS is a collection of programs that are used to manage the database structure and controls the
access of information stored in the Database.
b. A DBMS is a collection of database, database utilities ( DBMS software ) operated by end users or
application programmers and finally administered by DBA.
c. A DBMS works as an interface between end-users and database.
d. DBMS is a software package that can be used to define, construct, manipulating the database using
efficient query language.

FUNCTIONS OF DBMS (or) SERVICES OF DBMS (or) RESPONSIBILITIES OF DBMS (or)


OBJECTIVES OF DBMS:

DBMS performs several important functions that guarantee the integrity and consistency of data in the
Database.

1. Data Dictionary Management


2. Data Storage Management
3. Data Security Management
4. Data Integrity Management
5. Backup & Recovery Management
6. Performs functioning of Multiple Users
7. Data Transformation & Presentation
8. Data Communication Interface
9. Data Access & Program Interface

Data Dictionary Management

 The word data dictionary refers data standards, relationships defined in between Database and the
Database constraints.
 The responsibility of DBMS the data dictionary should functioning in efficient manner.
 The functioning of the data dictionary is under the control of DBA.

2|Page
Database Management System
Data Storage Management

 The DBMS create and manages complex structure for the data storage with desired memory address.
 Whenever the memory address is sufficient the end users access files randomly at any time.

Data Security Management

 The database application programs support strong passwords and syntactical rules.
 The database stores not only database tables but also data entry forms, reports, the DBMS provides
security.
 DBMS provides security to user programs, system programs.
 It is important in multi-user database systems where many users can access the database
simultaneously.

Data Integrity Management

 The word integrity refers joining database tables.


 DBMS supports the data integrity without loss of data by establishing relation between database
tables.

Backup & Recovery Management

 DBMS supports data backups and recovery with the help of replicated server and DBA.
 Recovery of data from bad sector (or) power failures.

Performs Functioning of Multi-User

 In DBMS more than one user can access and update more than one file at a time that is called
concurrent access.
 DBMS supports multiple users simultaneously access files without loss of any data.

Data Transformation & Presentation

 The DBMS transforms the entered data to the data structures that are required to store the data.
 Based on the query processing the data will be communicated i.e., transfer, displaying, returned data
efficiently in between user and database server.

Data Communication Interface

 The DBMS accepts request from the end users by using user interface.
 This request will be processed and then results will be displayed to the user in a understandable
format.

Data Access and Program Interface

 DBMS supports well defined program languages like Structured Query Language (SQL) , PL/SQL.
 These are used to access and process queries with the help of query processor.

3|Page
Database Management System
EVOLUTION OF DBMS:

1. In early 1960s Charles Bachman created the first general purpose DBMS that uses network data
model.
2. In late 1960s IBM developed Information Management System that uses hierarchical data model.
3. In 1970s EF Codd from IBM created Relational Data Model.
4. In 1976 Peter Chen presented Entity-Relationship Model that is used in database design.
5. In 1980s SQL was developed by IBM and became the standard query language for database.
6. In 1990s IBM, Oracle and others developed powerful DBMS.

CLASSIFICATION OF DBMS:

A Database can be classified in many ways.

1. Classification according to the number of users.


2. Classification according to the location.
3. Classification based on the data model.

CLASSIFICATION ACCORDING TO THE NUMBER OF USERS:

a. SINGLE USER:
Single user database supports only one user at a time.
b. MULTI USER:
It supports multiple users at the same time. When the database is used by the entire organization and
supports many users across many departments, these database is known as enterprise database.

CLASSIFICATION ACCORDING TO STORAGE LOCATION:

a. CENTRALIZED DATABASE:
A Database that supports data located at a single site is called as Centralized Database.

b. DISTRIBUTED DATABASE:
A Database that supports data distributed across several different sites is called as Distributed
Database.

CLASSIFICATION ACCORDING TO THE DATA MODEL:

According to the Data Model databases are classified into three categories.

a. Hierarchical Data Model:


In this data model the structure of database is in the form of inverse tree.
This data model supports only one-to-one and one-to-many associations.
In this data model the data is placed in nodes. Nodes are basically two types.
1. Parent / Super Node
2. Child / Sub Node
The parent node / child node placed at one position represents levels.
Different number of levels placed in hierarchical data model are named as segments.
b. Network Data Model:
The network data model was developed to overcome the limited scope of hierarchical model.
4|Page
Database Management System
Network data model can be used to design complex database structure.
In network data model, multiple parent-child relationships are used.
The network data model uses a network structure, which is a data structure consisting of nodes and
branches.
In network data model the database files can be divided into two parts.
1. Owner part
2. Member part
A relationship defined between any two files is named as SET.
c. Relational Data Model:
It is one of the most popular data model implemented by E.F.Codd.
Relational data model supports all kinds of associations.
The structure of the database in relational data model is in the form of table.
A table can be defined as collection of rows and columns.
The rows are called records or tuple and columns are called fields or attributes.
Relational data model could not support data redundancy. So two tables or two fields could not have
the same name.
There is no restriction for creating tables.

5|Page
Database Management System
UNIT-II

FILE BASED SYSTEM:

 In the conventional file processing system each and every subsystem maintains same files.
 These will be duplication (redundancy) of data between various subsystems of the information
system.
 The concept of the conventional file processing system is shown below, which consists of the 3
applications namely App1, App2, App3.

 The different inputs and outputs of these applications are summarized below. Some files are
duplicated in different subsystems in conventional file processing System.

Name of the
Input Output
Application
Application-1 File1 and File2 Report1, Report2, Report3
Application-2 File1 , File3 and File2 Report4, Report5
Application-3 File 2 and File 5 Report6

PROBLEMS WITH FILE MANAGEMENT SYSTEM:

 In File Processing System, there is the possibility to place the common files on different sub systems.
 It causes the problem of data redundancy.
 The following are the drawbacks of File management System.

1. Uncontrolled redundancy of data


2. Inconsistency of data
3. Inflexibility of data processing
4. Poor enforcement standards
5. Low programming productivity
6. Limited data sharing
7. Low data security
8. Excessive program maintenance
9. Doesn’t support adhoc queries
10. Concurrent problem

1. Uncontrolled Redundancy of Data:


a. In conventional file processing system each and every department has its individual data without
coordination.
6|Page
Database Management System
b. The word redundancy refers to repetition (duplication) of data.
c. In File processing system same data will be available in more than one subsystem.
d. This will result in increased disk-space, increased time of entry and inconsistency of data.

2. Inconsistency of data:
a. The uncontrolled redundancy of data will permit same data available in many different
subsystems across the organization, so the inconsistency of data increased.
b. While performing basic data processing operations like deletion, updating, retrieve etc this
inconsistency will give misleading results.

3. Inflexibility of data processing


a. Conventional File Processing System follows top-down approach.
b. Entities and attributes/fields must be decided while designing the system in the beginning.
c. As a result system may not be flexible to modify in future.

4. Poor Enforcement of Standards


a. In CFPS, every subsystem will follow its own standards while finalizing the name of the field,
field width, type etc.
b. If any user made any modifications on the data standards of a file it effect the other users who
works on the same file.
c. There will be serious error due to mismatch of fields while integrating the files.
d. It refers to poor enforcement of data standard.
5. Low Programming Productivity
a. Programming productivity is a measure of time taken to develop an application.
b. Whenever the program maintenance is high and takes more time to implement then automatically
reduced the productivity.
c. Inflexibility and Poor enforcement of standards causes low programming productivity in file
management system.
6. Limited Data Sharing
a. In File Management System various departments of the system managing the files without
coordination.
b. Each and every user has the right to access all files but he can able to access limited files only.
c. File Management system is not centralized so it has limited data sharing.
7. Low Data security
a. In Conventional File Processing System each subsystem will perform its own tasks individually.
b. It is not fully secured because there is no private rules and passwords defined on each subsystem.
8. Excessive Program Maintenance
a. In File Processing System data is not centralized.
b. Every subsystem contains different files. It is not possible to modify the system software because
we have to perform modifications to all the system individually.
c. Because of this the maintenance of program in high.
9. Doesn’t Support Adhoc Queries
a. Adhoc query refers the queries which were designed by using a strong syntactical rules of query
language.
b. In File Management System there is no Adhoc queries to access the records.
7|Page
Database Management System
10. Concurrent Access Problem
a. File Management System doesn’t support multi-user environment.
b. It doesn’t support multiple users to access the records and manipulations at the same time.

ADVANTAGES OF DATABASE MANAGEMENT SYSTEM:

 DBMS receives all the application requests and translate them into Database understandable format
to fulfill the user request.
 The following are the benefits/advantages of DBMS.
1. Reduced Data Redundancy
2. Consistency of Data
3. Flexibility of Data Processing
4. Better enforcement of standards
5. High Programming Productivity
6. Enhanced Data sharing
7. Improved Data Security
8. Reduced Program maintenance
9. Supports Adhoc queries
10. Supports Concurrent access

1. Reduced Data Redundancy


a. The data of database is maintained at centralized location.
b. As a result of centralization, repetition of data can be avoided.
c. In DBMS we have key constraints which reduce the redundancy of data.
2. Consistency of Data
a. In DBMS we can use key constraints to eliminate data redundancy.
b. Hence there is no redundancy in DBMS, so the data is not mixed.
c. The data is very consist for both end users and database server.
3. Flexibility of Data Processing
a. Database System follows bottom-up approach.
b. If any error occur at any level of the project it could not affect the other level.
c. Each level has individual error detection and correction principles.
d. So data is flexible for data processing.
4. Better Enforcement of Standards
a. Database system follows bottom-up approach.
b. Therefore various departments of the organization will follow a common notation while
designing the attributes.
c. It is very easy to integrate different files and generate required reports whenever required.
5. High Programming Productivity
a. Since the database system free from redundancy of data, inconsistency of data and limited data
sharing we can easily write programs on database in less time.
b. So to implement the projects productivity is increased.
6. Enhanced Data Sharing
a. In DBMS data will be stored in a centralized location.
b. It provides an environment for end users to access and share more data easily.

8|Page
Database Management System
c. The end users have the rights to share and access any file at any time. There is no limitation of
data access and sharing in DBMS.
7. Improved Data Security
a. DBMS provides high security for files by using usernames and strong passwords.
b. All files are under the control of DBA (Database Administrator).
c. DBA should provide different access permissions to different types of users.
d. Unauthorized persons cannot access data.
8. Reduced program maintenance
a. DBMS follows both graphical and virtual representation of data.
b. It needs a less number of programs for maintaining the files in DBMS.
c. Different applications are developed under the coordination of the DBA.
9. Support Adhoc Queries
a. DBMS follows strong syntactical query language.
b. So it is easy for data accessing, retrieving and data modifications.
c. So DBMS follows Adhoc query language rules.
10. Supports Concurrent Access
a. Concurrent access means multiple users can access their information at the same time.
b. DBMS supports parallel accessing as well as concurrent access.

DATA MODELS

 A Data Model represents data structures and their characteristics, relations, constraints,
transformations, and other constructs with the purpose of supporting a specific problem domain.
 A Data Model can be defined as the blueprint of the database structure.

HIERARCHICAL DATA MODEL


a. In this data model the structure of database is in the form of inverse tree.
b. This data model supports only one-to-one and one-to-many associations.
c. In this data model the data is placed in nodes. Nodes are basically two types.
3. Parent / Super Node
4. Child / Sub Node
d. The parent node / child node placed at one position represents levels.
e. Different number of levels placed in hierarchical data model are named as segments.

Disadvantages (or) Limitations


a. This model could not support many-to-many and many-to-one associations.
b. It is very difficult to maintain very complex relationship between application programs and end
users.
c. This data model could not support Data Independency that is if any modification is done at any level
it may effect another level.
d. The first implemented hierarchical database application program is “SYBASE”.

9|Page
Database Management System

NETWORK DATAMODEL:
The network data model was developed to overcome the limited scope of hierarchical model.
Network data model can be used to design complex database structure.
In network data model, multiple parent-child relationships are used.
The network data model uses a network structure, which is a data structure consisting of nodes and
branches.
In network data model the database files can be divided into two parts.
3. Owner part
4. Member part
A relationship defined between any two files is named as SET.
The first implemented network database application program is IBM mainframe computers.
Network data model includes DDL (Data Definition Language) and DML (Data Manipulation
Language) in DBMS.
The main difference of network model with hierarchical model is that a network model permits a
child to have more than one parent, where as hierarchical model not allows a child to have multiple
parents.
In network data model data access is more flexible.

ADVANTAGES:
Network data model is simple and easy to implement.
Network data model can handle one-to-one and many-to-many associations.
There is always a link between the parent and child segments in this data model.
DISADVANTAGES:
Since all the records use pointers, database structure becomes more complex.
10 | P a g e
Database Management System
Insertion, updating and deletion operations more complex in this model.
In this data model structural independence is not present.

RELATIONAL DATAMODEL:
It is one of the most popular data model implemented by E.F.Codd.
Relational data model supports all kinds of associations.
The structure of the database in relational data model is in the form of table.
A table can be defined as collection of rows and columns.
The rows are called records or tuple and columns are called fields or attributes.
Relational data model could not support data redundancy. So two tables or two fields could not have
the same name.
There is no restriction for creating tables.
Every relational database table having at least one unique field called “key field”.
In relational data model the data is fully independent that is the modifications applied on one data
item/value/table/field could not affect other data item/value/field/table.
It supports all kinds of database constraints.
The first implemented relational database application program is “ORACLE”. It is the combination
of both SQL and PL/SQL.

ADVANTAGES:
Relational data model is simpler than hierarchical and network data models.
Changes in the structure do not affect the data access.
Relational data model achieves both data independence and structural independence.
Ad hoc query capability is based on SQL.
DISADVANTAGES:
Relational database system need more powerful hardware computers and data storage devices.
Setting up and maintaining the relational database is more expensive. To set up a relational database,
you need to purchase special software.
Ease of design can lead to bad design.

COMPONENTS OF Database SYSTEM:

The components of information system are given as below.

1. Data
2. Procedures
3. People
4. Computer ( Software + Hardware )

11 | P a g e
Database Management System
DATA:

Data is a collection of interrelated files specific to an organization. Data is the root entity of any
database system. In database terminology data is raw facts. Depending on access mechanism data is
available in two modes.

1. Shared Mode
2. Integrated Mode

SHARED MODE:

If a single piece of information is accessed by multiple application users then we say that data is in
the shared mode.

In railway database system information regarding the trains may be accessed by multiple counter clerks
from various locations.

INTEGRATED MODE:

If multiple pieces of information is accessed by single application user then we say that the data is in
integrated mode.

In a school database system a senior clerk preparing progress report by combining the various files such as
personal details, marks details, attendance details and etc.

PROCEDURES:

 A Program is a collection of well defined instructions. Database utilities like Oracle, Sybase, IDMS,
IMS used as database languages.
 Procedures are the instructions and rules that govern the design and use of the database system.
 It gives the information about the data standards assigned to the database fields, storage structure and
also specifies the data entry screens and reports.

COMPUTER:

A Computer is a collection of physical components of the system which are integrated together.

Hardware includes secondary storage devices, communication channels (data cables), power cables,
processor, mother board and other devices.

Software is a collection of application programs includes strategies like inserting data, retrieving data,
updating data, deleting data. Usually application programs developed by application programmers to help
end users to perform their data manipulations.

PEOPLE:

This is the last component of the information system. People are classified into three categories.

End Users
Application Programmers
DBA (Database Administrator)
System Administrator
12 | P a g e
Database Management System
Database Designer
END USER:

He is the third class user of database system to perform tail-end operations. He is the responsible user
for various data manipulations such as insertion, updating, deletion and etc. With the help of application
programs, end user will access data from the database system.

APPLICATION PROGRAMMER:

He is the intermediate user responsible to develop variety of application programs which always
helps the end user to interact with the database, to perform various operations.

Application programs develop utility programs with the help of components in the database system.

DBA ( Database Administrator )

He is the apex body of the database system. Being a supervisor of an organization, he has several
responsibilities.

1. Deciding information content of the database.


2. Defining storage structure and access strategies.
3. Liaising with the users.
4. Providing proper security to the database system.
5. Authorization checks and validation procedures.
6. Providing backups on data loss.

SYSTEM ADMINISTRATOR

The system administrator controls and coordinates the functioning in between the hardware
component and the system programs of DBMS. He is responsible to oversee the database system is general
operations.

DATABASE DESIGNER

These people design the database structure. The database designer gives the information about the
growing new dimensions and the responsibilities of newly implemented database application programs.

DATA BASTRACTION (or) DATA BASE ARCHITECTURE

↪ The degree of data abstraction specifies the frame work of Data model.
↪ The database can also be viewed from different levels of abstraction to reveal different levels of
details.
13 | P a g e
Database Management System
↪ From a bottom-up manner, we may find that there are three levels of abstraction in the database.

EXTERNAL LEVEL:
1. In this database view, maximum details about the database will be hidden from the user.
2. Only the restricted portion of the database is available to end users, because an end user does not
need to know everything about the structure of the entire database.
3. This model purely related to end user only.
4. It implements highest level of data abstraction.
5. E-R Diagrams will be used to represent the external views.

CONCEPTUAL LEVEL:
1. This view will provide some more details about the database to the user like structure or schema
details of the database.
2. Conceptual level describes what type of data is stored in the database and what relationships exist
among those data.
3. In this level a user know the information about the attributes of each table, the common attributes in
the different tables.
4. It implements middle level of data abstraction.

INTERNAL LEVEL:
1. This level is concerned with the physical storage of the data.
2. It also describes what data is stored in tables.
3. It implements lowest level of data abstraction.
4. Both internal level and physical level is considered as a single level, but the difference is physical
level is managed by operating system under the direction of DBMS, while the internal level is
managed by DBMS.

14 | P a g e
Database Management System
UNIT-III
Entity – Relationship Model
INTRODUCTION:

1. Entity – Relationship model is a high level conceptual model developed by Peter Chen in 1976 to
facilitate database design.
2. The E-R Model is the generalization of the earlier available models like hierarchical and the network
model.
3. Entity-Relationship model consists of set of objects called entities and relationships among the entity
sets.
4. A basic component of the E-R model is the Entity-Relationship diagram which is used to visually
represent data objects and the relationships between them.
5. The E-R Diagram used for representing E-R model can be easily converted into relations (tables) in
relational model.
6. It is a top-down approach to database design.
7. It is very simple and easy to understand by various types of users and designers.
8. It provides an easily understood pictorial map for the database design.

BUILDING BLOCKS OF ENTITY-RELATIONSHIP MODEL:


1. The E-R model can be carried out with the help of pictorial representation of entities, attributes and
relationships.
2. The basic building blocks of Entity-Relationship diagram are Entity, Attribute and Relationship.
3. The following are the representations.

Entity Data objects about which


information can be collected Entity Name
and stored. Entities are
represented by Rectangles.
Attribute Characteristics or properties of
an entity. Attributes are
represented by ellipses and is Attribute Name
directly connected to entity.
Relationship An association among entities.
Relationships are represented
by diamond shaped box and Relationship
name of the relationship is
written inside it.

TYPES OF ENTITIES:
Entities are classified into two types.
1. WEAK ENTITY:
If the existence of an entity is depends upon another entity such an entity is said to be weak entity. In
other words an entity that does not has an attribute that act as a primary key is called as weak entity.
It is represented by using double rectangle.

15 | P a g e
Database Management System
2. STRONG ENTITY:
If the existence of an entity does not depend up on another entities such an entity is said to be strong
entity. In other words an entity that has an attribute that act as a primary key is called as strong
entity. It is represented by using single rectangle.

TYPES OF ATTRIBUTES:
The following are the various types of attributes.
1. Simple attribute
2. Composite attribute
3. Multi valued attribute
4. Derived attribute
SIMPLE ATTRIBUTE:
An attribute that consist of a single atomic value is called simple attribute and it cannot be sub
divided.

For example age of an employee or student.


COMPOSITE ATTRIBUTE:
An attribute that can be divided into sub parts or components is called composite attribute.

For example the field name in a STUDENT or EMPLOYEE entity can be divided into First-Name, Middle-
Name and Last-Name.
MULTI VALUED ATTRIBUTE:
An attribute that consists of multiple values is called as multi valued attribute. For example a
STUDENT may have multiple phone numbers or email IDs.

DERIVED ATTRIBUTE:
An attribute that’s value is derived form a stored attribute is called as derived attribute. For example
the attribute age, its value is derived from the stored attribute Date_of_Birth.
16 | P a g e
Database Management System

DEGREE PF REALTIONSHIP:
The degree of a relationship is the number of entities associated with the relationship. The degree of
relationship is also called as “cardinality”.
ONE-TO-ONE RELATIONSHIP:
Only one entity of the first set is related to only one entity of the second set, such a relationship is
called one-to-one relationship.
For example a teacher teaches student. Only one teacher is teaching to only one student.

TEACHER Teaches STUDENT


1 1
ONE-TO-MANY RELATIONSHIP:
Only one entity of the first set is related to multiple entities of the second set, such a relationship is
called one-to-many relationship.
For example a teacher teaches students. Only teacher is teaching multiple students.

TEACHER Teaches STUDENT


1 M
MANY-TO-ONE RELATIONSHIP:
Multiple entities of the first set are related to only one entity in the second set, such a relationship is
called many-to-one relationship.
For example teachers teach a student. Many teachers are teaching only to one student.

TEACHER Teaches STUDENT


M 1
MANY-TO-MANY RELATIONSHIP:
Multiple entities of the first set are related to multiple entities of the second set, such a relationship is
called many-to-many relationship.
For example teachers teach students. Many teachers teaching many students.

TEACHER Teaches STUDENT


M M

17 | P a g e
Database Management System
DEVELOPING E-R DIAGRAMS:
1. The name of the entity must be in upper case characters.
2. The relationship must and should have an identification ( name of relation ).
3. The relationship identification may be either in active voice or passive voice.
4. The relationship in the diagram either may be in single or double direction and this direction
represents relationship type.
Let us consider 3 entities with fields as follows:
Entity – 1 : STUDENT ( StdNum , SName , Branch )
Entity – 2 : SUBJECT ( SubCode, SubName, BookName )
Entity – 3 : FACULTY ( FacCode, FacName, SubName )

GENERALIZATION AND SPECIALIZATION:


Generalization:
1. A number of entities are brought together into one generalized entity based on their similar
characteristics is called as generalization.
2. In entity-relationship model we can express database entities in a hierarchical manner.
3. If we goes up into the hierarchy it generalizes the view of entity and if we go down into the hierarchy
it gives the details of every entity.
4. This structure is called generalization in which entities are clubbed together to represent a
generalized view.

18 | P a g e
Database Management System
Specialization:
1. A group of entities are divided into sub-groups based on their characteristics is called as
specialization.
2. IS A relationship supports attribute inheritance and relationship participation.
3. The sub class relationship is represented by IS A relationship.
4. Attribute inheritance is the property by which sub class entities inherit values for all attributes of
super class.
5. Specialization is the top-down process of identifying lower level entity subtypes from a higher level
entity supertype.

AGGREGATION AND COMPOSITION


Aggregation:
Aggregation is a process where relation between two entities is treated as a single entity.

The relation between CENTER and COURSE entities is acting as a single entity in relation with entity
VISITOR.
Composition:
Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is
called as composition.
When an object contains the other object, if the contained object cannot exist without the existence
of container object, then it is called composition.
For example
1. A class contains students. A student cannot exist without a class. There exists composition
between class and student.
2. A room does not exist separate to a house.

19 | P a g e
Database Management System
CODD’s RULES:
1. In 1985, Dr. E.F.Codd published a list of 12 rules to define a relational database system.
2. An RDBMS product has to satisfy at least 6 of the 12 rules to be accepted as a full-fledged RDBMS.
3. There is no RDBMS package available that satisfies all the 12 rules.
4. The following are the Codd’s rules.
a. INFORMATION RULE: All information in a relational database must be logically represented as
column values in rows within tables.
b. GUARANTEED ACCESS: Every value in a table is guaranteed to be accessible through a
combination of table name, primary key and column name.
c. SYSTEMATIC TREATMENT OF NULL VALUES: Null values must be represented and treated
in a systematic way, independent of data type.
d. DYNAMIC ONLINE CATALOG BASED ON THE RELATIONAL MODEL: The meta data
must be stored and managed as ordinary data, that is in tables within database. Such data must be
available to authorized users using the standard database relational language.
e. COMPREHENSIVE DATA SUBLANGUAGE: The relational database must support one well
defined, declarative language for data definition, view definition, data manipulation, integrity
constraints, authorization and transaction management.
f. VIEW UPDATING: Any view that is theoretically updatable must be updatable through system.
g. HIGH LEVEL INSERT, UPDATE AND DELETE: The database must support set-level insert,
update and delete.
h. PHYSICAL DATA INDEPENDENCE: Application programs and ad hoc facilities are logically
unaffected when physical access methods or storage structure are changed.
i. LOGICAL DATA INDEPENDENCE: Application programs and ad hoc facilities are logically
unaffected when changes are made to the table structure that is changing order of columns and
inserting new columns.
j. INTEGRITY INDEPENDENCE: All relational integrity constraints must be definable in the
relational language and stored in the system catalog, not at the application level.
k. DISTRIBUTION INDEPENDENCE: The end users and application programs are unaware and
unaffected by the data location.
l. NO-SUBVERSIONS: If the system supports low-level access to the data, users must not be allowed
to bypass the integrity rules of the database.

RELATIONAL INTEGRITY:
1. The responsibility of Database Administrator is to maintain the integrity of the database and prevent
it from becoming corrupted.
2. Database integrity means the completeness, correctness and consistency of data.
3. In relational data model data integrity can be achieved using integrity rules or constraints.
4. Integrity constraints are divided into three main categories.
a. Domain integrity
b. Entity integrity
c. Referential integrity

DOMAIN INTEGRITY
1. Domain integrity rules are associated with maintaining the correctness of attribute values.
2. It deals with the entries of the data values.
3. We can achieve domain integrity by using data type, NOT NULL and CHECK constraints.
20 | P a g e
Database Management System
4. NOT NULL constraint is used to verify the data value of field is not null.
5. CHECK constraint is used to verify the range and data types of data values.

ENTITY INTEGRITY
1. Entity integrity rule specifies that each entity should be identified uniquely.
2. Entity integrity is a constraint on primary key value.
3. PRIMARY KEY doesn’t have repeated data and null values and used to identify an entity uniquely.

REFERENTIAL INTEGRITY:
1. Referential integrity is achieved through FOREIGN KEY CONSTRAINT.
2. A Foreign Key is an attribute within one relation that matches the primary key in another relation.
3. In relational database sometimes it requires to ensure that a value that appears in one relation field is
also available for some other field in another relation. This is known as referential integrity and is
expressed in terms of foreign key.

21 | P a g e
UNIT-IV
STRUCTURED QUERY LANGUAGE
Introduction to SQL:
1. SQL stands for Structured Query Language. It is a special purpose language used to define, access and
manipulate data in RDBMS.
2. SQL provides a set of statements for storing and retrieving data to and from a relational database.
3. All modern RDBMS like Microsoft SQL-Server, Microsoft Access, Oracle, DB2, Sybase, MySQL use
SQL as standard database language.
4. SQL is different form other programming languages like C, C++ etc.
5. It is a English like language that processes data in groups of records rather than one record at a time.
Advantages of SQL:
1. SQL can retrieve data from a database.
2. SQL can execute queries against a database.
3. SQL can insert records in a database.
4. SQL can update records in a database.
5. SQL can delete records form a database.
6. SQL can create new databases, new tables in a database.

SQL Commands:
SQL commands are instructions used to communicate with the database to perform specific task that
work with data. SQL commands are grouped into five major categories:
 Data Query Language (DQL)
SQL commands used to retrieve data from database. DQL commands in SQL are SELECT.
 Data Definition Language (DDL)
DDL commands are used to create, modify and drop structure of database objects. DDL
commands are CREATE, ALTER, DROP, RENAME, TRUNCATE.
 Data Manipulation Language (DML)
DML commands are used to insert, update and delete records form a database. DML commands
are INSERT, UPDATE, DELETE.
 Transaction Control Language (TCL)
These commands are used to save the changes made to the database. TCL commands are
COMMIT, ROLLBACK and SAVEPOINT.
 Data Control Language (DCL)
These commands are used to provide security to the database. DCL commands are GRANT and
REVOKE.
Data Types in SQL:
1) NUMBER:- This data type is used to store Fixed Point (numeric’s) or Floating point Numbers.
Maximum precision range 1 to 38 and scale range : -84 to 127
Ex: -160, 45, 3.45, -5.67
Syntax: field-name NUMBER(P, S); (p=precision, S=scale(total length)

Example:- Sno NUMBER(10);


Avg NUMBER(7, 2);

 Number Subtypes:
o DEC , DECIMAL, NUMBER: They are used to declare fixed point numbers with Precision
range 1 to 38 decimal digits.
o FLOAT :- FLOAT is used to declare floating point numbers with precision range 1 to 126
binary digits. Ex:- avg FLOAT(3);
o INT, INTEGER, SMALLINT:- They are used to declare integers with precision range 1 to
38 Decimal digits.

2) CHAR:- CHAR data type use to store fixed length character data maximum storage 2000 bytes.
Syntax: field-name CHAR(size);
Example:- Sname CHAR(20);
Note :- if you store 10 chars then remaining 10 spaces are left unused.

3) VARCHAR / VARCHAR2 :- VARCHAR/VARCHAR2 data type used to store variable length


character data and maximum storage 4000 bytes.
Syntax: field-name VARCHAR(size); or field-name VARCHAR2(size);

Example:- Sname VARCHAR2(20);


Note : However VARCHAR / VARCHAR2 will not leave unused spaces. Oracle automatically
converts VARCHAR to VARCHAR2.

4) DATE:- It is used to store fixed length date times in the format of DD-MON-YY. Valid range
January – 1- 4712 BC to December-31-9999 AD. The size of date data type 7 bytes.
Syntax: field-name DATE;

Example:- emp_doj DATE:=’25-Jan-99’;

Example 2: start_time TIMESTAMP:-‘2014-04-13 18:10:52.33 +05:30’;


5) CLOB:- CLOB (Character Length Object) data type to storage large blocks of character data into
Database. The range from 8TB to 128 TB (Tera byte)
Syntax: field-name CLOB;

6) BLOB:- BLOB(Binary Length Object) It refers binary length object. The range from 8TB to 128
TB (Tera byte)
Data Definition Language:
 It is the subset of SQL commands to create, modify and destroy database objects like tables,
indexes, views etc.
 There are 6 types of DDL commands
1) CREATE
2) ALTER (Advanced Data Definition Commands)
3) TRUNCATE
4) RENAME
5) DROP
1) CREATE :- This command can be used to create the physical structure of the database table.
Syntax:
create table table_name
(

Column1 data type,


Column2 data type,
PRIMARY KEY (column1, …)
FOREIGN KEY (column1, ….) REFERENCES tablename,
CONSTRAINT (constraint );
)

Example1 :-
create table STUDENT
( Sno NUMBER(3) PRIMARY KEY,
Sname VARCHAR2(20),
Spec VARCHAR2(10),
Dob DATE
);

Example2 :- SQL/> CREATE TABLE MARKS(HNO NUMBER(12) PRIMARY KEY, SNO NUMBER(12)
REFERENCES STUDENT, SUB VARCHAR2(12), MARKS NUMBER(12, 2) NOT NULL);

2) ALTER:- ALTER TABLE statement is used to modify the table structure by modifying the
definition of its columns.
 There are 4 options are available in Alter command
A) ADD :- To add a column
B) MODIFY :- To change the column characteristics.
C) DROP :- To delete a column from a table.
D) ADD / DROP Constraints.

A) Adding a Column:-
 Using ALTER ADD command to adding one or more columns to an existing table.
Syntax: ALTER TABLE table_name ADD column_name datatype;
Example:- ALTER TABLE STUDENT ADD mobile_no NUMBER(10);
B) Modifying a Column Data Type, Length:-
 Using ALTER MODIFY to modify the column data type or length of the column.
Syntax: ALTER TABLE table_name MODIFY column_name datatype;
Example:- ALTER TABLE STUDENT MODIFY Sname VARCHAR2(25);

C) Dropping a Column:-
 Using ALTER DROP command you can drop (delete) the existing column of a table.
Syntax: ALTER TABLE table_name DROP COLUMN Sname;
Example:- ALTER TABLE STUDENT DROP COLUMN Sname;
3. TRUNCATE:- Using TRUNCATE command to delete all records in a table. But not delete
structure of the table. Never get back record using ROLL BACK.
Syntax:- TRUNCATE table table_name; Example:- TRUNCATE table EMP3;

4. RENAME :- Using RENAME TABLE statement to rename an existing table in any database
schema.
Syntax:- RENAME oldtable_name TO new_table_name; Example:- RENAME emp TO employee;

5. DROP:- Using DROP TABLE statement removes the table from the database server
permanently. Once the table dropped it never be roll backed.
Syntax: DROP table Table-name; Example: DROP table EMP;

Selection Operation Projection Operation:


The select statement is used to query or retrieve data from a table in the database.
Selecting All Records:
We can select all the records from a table by using the SELECT statement as follows.
Syntax:
SELECT * from Table-Name [WHERE clause][GROUP BY clause][HAVING clause][ORDER BY clause];
Example:
SELECT * FROM STUDEENT;
The above query will display all the records from the STUDENT table.
Note: The clauses placed in square brackets are optional ones.
Selecting Records Based on Condition:
We can select specific records from a table by using the WHERE clause of the SELECT command. We
can specify a condition using WHERE clause, the records which satisfy that condition will be displayed.
Syntax:
SELECT * from Table-Name WHERE condition;
Example:
SELECT * FROM STUDEENT WHERE marks >=75;
The above query will display students whose marks are greater than or equal to 75.
In both the cases the query will display all the field values of the records.
Projection Operation:
Projection is a special case of SELECT command in which we can select some specific fields to display.
Projecting all values of specific fields:
We can display all field values of the specified table.
Syntax:
SELECT field-1, filed-2,… from Table-name;
Example:
SELECT RNO,Name FROM student;
The above query will display roll number and names of all students.

Projecting specific values of specific fields:


We can display some specific filed values of specified fields based on some condition. The condition is
specified by using WHERE clause.
Syntax:
SELECT RNo, Name FROM student WHERE marks >=75;
The above query will display roll numbers and names of students whose marks are greater than 75.

AGGREGATE FUNCTIONS :-
Aggregate functions also called Group functions are built-in SQL functions that operate on groups of
rows and return one value for the entire group or table. They are used to produce summarized results.
Types of Aggregate functions :
i. COUNT ( )
ii. SUM ( )
iii. AVG ( )
iv. MAX ( )
v. MIN ( )

i) COUNT ( ) :- This function returns the number of rows in the table that satisfies the condition
specified in the WHERE clause with SELECT statement. It counts non-null values of an attribute
also.
Example 1:-
SELECT COUNT ( * ) AS Total_Employees FROM EMP WHERE deptno = 10;
Output:- Total Employees
3
Example 2:-
SELECT COUNT ( * ) AS Total_Employees FROM EMP;
Output:- Total Employees
10
Example 2:-
SELECT COUNT ( DISTINCT DEPTNO) FROM DEPT;
Output:- 3

ii) SUM ( ) :- This function is used to get the sum of a numeric column.
Example 1:- To get the total salary given out to the employees.
SELECT SUM (SAL) AS Total_Salary FROM EMP;
Output:- Total Salary
355000

iii) AVG ( ) :- This function is used to get the average of a numeric column.
Example 1:- To get the average salary, the query would be like.
SELECT AVG (SAL) AS Average_Salary FROM EMP;
Output:- Average_Salary
1500.234

iv) MAX ( ) :- This function is used to get the maximum value from a numeric column.
Example 1:- To get the maximum salary drawn by an employee, the query would be like.
SELECT MAX (SAL) AS Maximum_Salary FROM EMP;
Output:- Maximum_Salary
33000

v) MIN ( ) :- This function is used to get the minimum value from a numeric column.
Example 1:- To get the minimum salary drawn by an employee, the query would be like.
SELECT MIN (SAL) AS Minimum_Salary FROM EMP;
Output:- Minimum_Salary
10000

Data Manipulation Language:


Data manipulation Language(DML) is used to manipulate data i.e. insertion, deletion, modification of
information in the database table.

There are 5 DML commands


1) INSERT
2) UPDATE
3) DELETE

(1) INSERT :- (Adding table rows) The INSERT statement is used to insert new rows or records into a
table. We can insert single record or multiple records at a time.
1) Inserting single record:
Syntax: INSERT INTO tablename VALUES ( value1, value2,…. valueN);
Example: INSERT INTO Student VALUES(1, ‘murthy’, ‘bca’, ’25-jan-09’);
Output: 1 row created.

2) Inserting multiple record through parameter substitution:-


Syntax: INSERT INTO tablename VALUES ( &value1, ‘&value2’,…. );
Example: INSERT INTO Student VALUES(&sno, ‘&sname’, ‘&spec’, ’&doj’);
Output:-
Enter value for sno: 1
Enter value for sname: murthy
Enter value for spec: bca
Enter value for doj: 25-jan-09
1 row created.
SQL/> /
Enter value for sno: 2
Enter value for sname: sailu
Enter value for spec: bca
Enter value for doj: 22-mar-05
1 row created.
3) Inserting Rows with Optional Attributes:-
 Some times we need to insert particular attributes in a table when more than one attribute is
optional.
Example: INSERT INTO Student(sno, sname) VALUES(3, ‘Bharat’);

(2) UPDATE:- (Updating table rows) The UPDATE statement is used to modify data in a table. Changing
a single value or multiple values or single record or multiple records in a table.

Syntax: UPDATE table_name SET columnname=new value WHERE condition;


Example1:- UPDATE student SET sname=’B.S.N.Murthy’ WHERE sno=1;
Example2:- UPDATE student SET doj=’28-apr-95’ WHERE sname=’bharat’;
Output:- SQL\> 1 row updated.
SQL\> Select * from Student;
Example3:- UPDATE emp SET sal= sal + (sal * 0.5);

(3) DELETE:- (Deleting table rows) The DELETE statement is used to delete a single record or
multiple record or all records in a database table.
Syntax: DELETE FROM tablename WHERE condition;
Examples:-
a. Delete all records from STUDENT table;
Example:- DELETE FROM student;
Output:- SQL\> 5 rows deleted

b. Delete a single record using where condition in a STUDENT table;


Ex:- DELETE FROM student WHERE sno=3;
Output:- SQL\> 1 row deleted
c. Delete multiple records using where condition in a STUDENT table;
Ex:- DELETE FROM student WHERE sno IN(5, 9);
Output:- SQL\> 2 rows deleted
NOTE:- Here delete records belonging to sno 5 and 9 in the Student table.

Imposition of Constraints:
SQL uses integrity constraints to prevent invalid data entry into the tables of the database. Constraints
are a part of a table definition.
The constraints can be specified immediately after the column definition. This is called column level
constraints.
The constraints can be specified after all the columns are defined. This is called table level constraints.
The following are the various SQL constraints.
1. NOT NULL
2. UNIQUE
3. PRIMARY KEY
4. FOREIGN KEY
5. CHECK

NOT NULL:
By default, a table column can hold null values. The NOT NULL constraint enforces a column to not
accept NULL values. The constraint is placed immediately after the data type of a column.
Example:
CREATE TABLE STUDENT ( RNO NUMBER(3) NOT NULL,
NAME CHAR(30),
MARKS NUMBER(5,2) );
UNIQUE:
The UNIQUE constraint uniquely identifies each and every record in a database. It ensures that the
values entered into a column are unique, i.e., no two rows of a table have duplicate values.
Example:
CREATE TABLE STUDENT ( RNO NUMBER(3) UNIQUE,
NAME CHAR(30),
MARKS NUMBER(5,2) );

PRIMARY KEY:
A PRIMARY KEY constraint is used to identify a record uniquely from a table and it doesn’t allow
duplicate records and null values. It can be defined as a column level or table level.
Example:
CREATE TABLE STUDENT ( RNO NUMBER(3) PRIMARY KEY.
NAME CHAR(30),
MARKS NUMBER(5,2) );
Example:
CREATE TABLE STUDENT ( RNO NUMBER(3),
NAME CHAR(30),
MARKS NUMBER(5,2), PRIMARY KEY(RNO) );
FOREIGN KEY:
The FOREIGN KEY or referential Integrity identifies any column referencing the PRIMARY KEY in
another table. It establishes a relationship between two columns in the same table or between different tables.
Example:
CREATE TABLE PRODUCT ( PID NUMBER(3) PRIMARY KEY,
PNAME CHAR(30),
UNITPRICE NUMBER(4) );
CREATE TABLE CUSTOMER ( CID NUMBER(4),
PID NUMBER(3) REFERENCES PRODUCT(PID),
QTY NUMBER(3) );
On delete Cascade: By using this option, whenever a parent row is deleted then all the corresponding child rows
are deleted from the child table.
CREATE TABLE CUSTOMER
(
CID NUMBER(4),
PID NUMBER(3) REFERENCES PRODUCT(PID) ON DELETE CASCADE,
QTY NUMBER(3)
);
On Delete Set Null: By using this option, all the foreign key column values set to null when the parent value is
removed.
CREATE TABLE CUSTOMER
(
CID NUMBER(4),
PID NUMBER(3) REFERENCES PRODUCT(PID) ON DELETE SET NULL,
QTY NUMBER(3)
);
CHECK:
The CHECK constraint defines a condition that each row must satisfy. It is used to limit the value range
that can be placed in a column.
CREATE TABLE CUSTOMER
(
CID NUMBER(4),
PID NUMBER(3) REFERENCES PRODUCT(PID) ON DELETE CASCADE,
QTY NUMBER(3),
GENDER CHAR(1) CHECK( GENDER IN(‘M’,’F’)
);
Set operations:
Relational SET OPERATORS (Relational Algebra)

 In Oracle database SQL supports 8 types of relational algebra and relational SET operators.
 SET operators are used to combine information of similar types from one or more than one table.
 SQL joins tends to combine columns from different tables, whereas SQL SET operators combine rows
from different queries.
o Before apply set operators on 2 or more tables, these tables must satisfies “union compatibility”
relation.
o Union compatibility:- Two or more tables must and should have same field names, same data type
and approximate field length.
 Types of SET operators:-
1) UNION
2) INTERSECT
3) MINUS (difference)
4) DIVIDE
1) UNION:-
 The UNION operators joins the outputs of two or more queries(SELECT statement) into a single set
of rows and columns having distinct(unique) records.
 The UNON operator combines the output of two selected queries without include duplicate records.
Syntax:- SELECT column list FROM table1
UNION
SELECT column list FROM table2 [Order by clause];
ADMISSION table
STUDENT table Admsno Spec Fee
Stdno Sname Spec Fee 1 BSC 12000
1 Sailu BSC 12000 2 BCOM 10000
2 Mounika BCOM 10000 3 BCA 20000
3 Ramya BCA 20000 4 BBM 15000
4 Indu BA 8000
 Apply UNION operator on both tables. Output :-
Spec Fee
Example:- SELECT spec, fee FROM STUDENT BSC 12000
UNION BCOM 10000
SELECT spec, free FROM ADMISSION; BCA 20000
BA 8000
2) INTERSECT :- BBM 15000
 The INTERSECT operator returns the rows that are common between two
sets of rows. It returns the records that appear in the both the tables.

Syntax:- SELECT column list FROM table1


INTERSECT

SELECT column list FROM table2;

 Apply INTERSECT operator on both tables. Output :-


Spec Fee
Example:-SELECT spec, fee FROM STUDENT BSC 12000
INTERSECT
BCOM 10000
SELECT spec, free FROM ADMISSION;
BCA 20000
3) MINUS :-
 The MINUS operator returns the rows unique to first query.
 It combines records from 2 queries and returns the first table records which were not placed in the
2nd table.
Syntax:-SELECT column list FROM table1
MINUS
SELECT column list FROM table2;
 Apply MINUS operator on both tables.

Example - 1:-SELECT spec, fee FROM STUDENT Output :-


MINUS Spec Fee
SELECT spec, free FROM ADMISSION; BA 8000
Output :-
Example - 2:-SELECT spec, fee FROM ADMISSION Spec Fee
MINUS BBM 15000
SELECT spec, free FROM STUDENT;

4) DIVIDE :-
 This operator specifies table1 is DIVIDE by table2 to produce table3 whenever both tabl1 & table2
using a common field.
 The DIVIDE operation uses one single column table (i.e. columna) as the divisor and 2 column
table(i.e. column a & b) as the dividend.
 The table must have a common column (i.e.column a)
Table A
Table B  The output of a Table Output
Sname Avg
Sname A divided by Table B :-
Xyz 70
Xyz is. Avg
abc 60 DIVID
Pqr  The only value 50
pqr 50 E associated with both
xyz 50 ‘xyz’ & ‘pqr’ is 50
Pqr 90 only.
UNIT-V
PL/SQL
 PL/SQL is a combination of SQL along with the procedural features of programming languages. It was
developed by Oracle Corporation
 Pl/SWL BLOCK STRUCTURE
 PL/SQL is a block-structured language. This means that programs can be divided into logical bocks
1) Declaration: It is used to declare variables, constants, cursors etc.
2) Executable : This section starts with BEGIN and ends with END. It contains program logic.
3) Exception handling: This section starts with the EXCEPTION keyword. It can be used to
handle errors.
PL/SQL ARCHITECTURE
DECLARE
<declarations>
EXCEPTOIN
<executable statements>
END;

Compound symbols
Symbol Meaning
!= Relational operator
|| Concatenation operator
-- Single line comment
/* */ Multiline comment
:= Assignment operator

 VARIABLE: Variables are storage areas used to hold the data values that can change through the
PL/SQL block.
 Variable declaration:
DECLARE
Rno number(2):=10;
Sname VARCHAR2(30):=’bharat’;
Avg NUMBER(9,2);
basic CONSTANT number(3):=10; /* constant declaration */

 %TYPE & %ROWTYPE


1) %TYPE:- To avoid type and size conflict between a variable and the column of a table, the
attribute %TYPE is used.
Ex: ename EMP.ename%TYPE;
2) %ROWTYPE :- The %ROWTYPE attribute provides a record type that represents a row in a
database table. It stores entire row of table.
Ex: e_row EMP%ROWTYPE; e_row.sal := 5000;
CONTROL STRUCTURES:
There are 4 types of PL/SQL control structures are:
1) Conditional with the IF statements
2) CASE expressions
3) LOOP control structures.
4) Sequential control
1) Conditional with IF statement
a. IF-THEN-END IF
b. IF-THEN-ELSE-END IF
c. IF-THEN-ELSIF-END IF

a) IF-THEN-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:-
IF condition THEN
Satements;
END IF;
b) IF-THEN-ELSE-END IF:- If the condition is TRUE, then if bock executes other wise execute the
else block. DECLARE
a number(2) := 10;
Syntax:- b number(2) := 20;
IF condition THEN
Satement1; BEGIN
ELSE IF( a > b ) THEN
Satement2; dbms_output.put_line('a is big');
ELSE
END IF; dbms_output.put_line('b is big');
END IF;
END;
/

c) IF-THEN-ELSIF-END IF:- The IF-THEN- DECLARE


A NUMBER:=&A;
ELSIF statement allows you to choose between several B NUMBER:=&B;
alternatives. C NUMBER:=&C;
Syntax:- BEGIN
IF A>B AND A>C THEN
IF condition1 THEN
dbms_output.put_line('a is greater');
Statement1; ELSIF B>C THEN
ELSIF condition2 THEN dbms_output.put_line('b is greater');
Statement2; ELSE
dbms_output.put_line('c is greater');
ELSIF condition3 THEN END IF;
Statement3; END;
END IF; /
2) CASE expressions:
Like the IF statement, the CASE statement selects one sequence of statements to execute.
DECLARE
grade char(1) := 'A';
Syntax BEGIN
CASE grade
CASE selector WHEN 'A' then
WHEN search_value1 THEN Satement1; dbms_output.put_line('Excellent');
WHEN search_value2 THEN Satement2; WHEN 'B' then
WHEN search_value3 THEN Satement3; dbms_output.put_line('Very good');
... WHEN 'C' then
dbms_output.put_line('Good');
ELSE Satementn; -- default case
WHEN 'D' then
END CASE; dbms_output.put_line('passed');
WHEN 'F' then
dbms_output.put_line('failed');
3) LOOP control structures: (iterative else dbms_output.put_line('wrong grade');
control structures) END CASE;
END;
/
There are 3 types of LOOPS
a) BASIC LOOP / SIMPLE LOOP
b) WHILE loop
c) FOR loop

a) BASIC LOOP / SIMPLE LOOP:- DECLARE


Basic loop structure encloses sequence of statements in x number := 1;
BEGIN
between the LOOP and END LOOP statements. An EXIT
LOOP
statement or an EXIT WHEN statement is required to dbms_output.put_line(x);
break the loop. x := x + 1;
exit WHEN x > 11;
Syntax: END LOOP;
LOOP END;
statements; /
EXIT WHEN condition;
END LOOP;

DECLARE
b) WHILE loop:- Repeats a statement or N NUMBER := &N;
group of statements while a given condition F NUMBER := 1;
is true. It tests the condition before executing I NUMBER := 1;
the loop body. BEGIN
WHILE (I<=N) LOOP
Syntax F := F * I;
WHILE condition LOOP I:= I + 1;
Statment1; END IF;
END LOOP;
Statment2;
dbms_output.put_line(‘Factorial is‘|| F);
END LOOP; END;
/
Otupt:-
Enter value for N : 5
Factorial is 120
c) 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.
DECLARE
i number(2);
Syntax:-
BEGIN
FOR counter IN [REVERSE] FOR i in 10 .. 20 LOOP
<initial_value> .. <final_value> LOOP dbms_output.put_line('value of i:'|| i);
Statment1; END LOOP;
Statment2; END;
/ Example: Reverse Order
----
END LOOP; Output:- FOR a IN REVERSE 10 ..
value of i: 10 20 LOOP
value of i: 11
……………………………….

PL/SQL procedure successfully completed.

PROCEDURES in PL/SQL
Procedures:

 A procedure or stored procedure is a named PL/SQL block that can accept parameters
and to be invoked. But not return any value.
 Procedures − These subprograms do not return a value directly; mainly used to perform
an action.

Creating a Procedure:
 A procedure is created with the CREATE OR REPLACE PROCEDURE statement.

Syntax:
CREATE [OR REPLACE] PROCEDURE procedure_name
[ (parameter1 [mode1] datatype1,
Procedure
parameter2 [mode2] datatype2,…) ] Specification
IS / AS

BEGIN
Procedure
< procedure_body > Body
END procedure_name;
/

Note:-

 procedure-name specifies the name of the procedure.


 [OR REPLACE] option allows the modification of an existing procedure.
 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 CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/
Output: Procedure created.

Executing a Standalone Procedure


1) Using the EXECUTE keyword
Ex: SQL> EXECUTE greetings;
Output: Hello World
2) Calling the name of the procedure from a PL/SQL block

BEGIN
greetings;
END;
/
Output: Hello World
Dropping a Procedure

Syntax: DROP PROCEDURE procedure-name;


Example:- DROP PROCEDURE greetings;
Example 2:-
CREATE OR REPLACE PROCEDURE PR1(x NUMBER, Y NUMBER) AS
S NUMBER;
BEGIN
S:=X+Y;
dbms_output.put_line('Sum is :’ || S);
END PR1;
/
Output: SQL> procedure created
Executing a Standalone Procedure
1) Using the EXECUTE keyword
SQL> EXECUTE PR1(10, 20);
Output: SUM IS : 30
2) Calling the name of the procedure from a PL/SQL block
BEGIN
PR1(10, 20);
END;
/
Output : SUM IS : 30
PL/SQL procedure successfully completed.
FUNCTION in PL/SQL
Function:

 A function is a named PL/SQL block like procedure that can accept parameters and be
invoked. Generally a function is mainly used to compute a value.
 Function must return a value to the calling environment.

Creating a Function:

 A function is created with the CREATE OR REPLACE FUNCTION statement.

Syntax:
CREATE [OR REPLACE] FUNCTION function_name
[ (parameter1 [mode1] datatype1,
parameter2 [mode2] datatype2,…) ] RETURN datatype
IS / AS
[ local declaration ]
BEGIN
< function_body >
END function_name;
/

Note:-
 function-name specifies the name of the function.
 [OR REPLACE] option allows the modification of an existing function.
 Parameter: Name of the PL/SQL variable whose value is passed to the function.
 Mode :- Type of argument
o IN, OUT, IN OUT
 Data type: Data type of argument. It can be of %TYPE, %ROWTYPE or any data type.
 Return data type: Data type of the return value.

Example:- Create function to find sum of two numbers


CREATE OR REPLACE FUNCTION FUNADD(A IN NUMBER, B IN NUMBER)
RETURN NUMBER IS
C NUMBER(2);
BEGIN
C:=A+B;
RETURN C;
END;
/
Output: Function created.

Execute function:- Calling function “FUNADD” program.


DECLARE
C NUMBER(6);
BEGIN
C:=FUNADD(2,3);
DBMS_OUTPUT.PUT_LINE(C);
END;
/
Output: 5
PL/SQL procedure successfully completed.

Dropping a Function:

Syntax: DROP FUNCTOIN function-name;


Example:- DROP FUNCTION FUNADD;
Argument Modes:
S.No Parameter Mode & Description
IN : An IN parameter lets you pass a value to the subprogram. It is a read-only
1
parameter.

2 OUT:- An OUT parameter returns a value to the calling program.

IN OUT :- An IN OUT parameter passes an initial value to a subprogram and returns


3
an updated value to the caller.

CURSORS in PL/SQL

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

There are two types of cursors −


 Implicit cursors
 Explicit cursors

Implicit Cursors
 Implicit cursors are automatically created by Oracle whenever an SQL statement is
executed.
Explicit Cursors
 Explicit cursors are programmer-defined cursors for gaining more control over the context area.
S.No Attribute & Description Example
%FOUND
1 Cursor_name %FOUND
Return TRUE, if fetch statement returns at
least one row otherwise returns FALSE
%NOTFOUND
2 Cursor_name %NOTFOUND
Return TRUE, if fetch statement doesn’t
return a row. Otherwise returns FALSE
%ISOPEN
3 Cursor_name %ISOPEN
Returns TRUE, if the cursor is already open in
the program. Otherwise returns false.
%ROWCOUNT
4 Cursor_name %ROWCOUNT
Return the number of rows fetched by the
fetch statement.

Working with an explicit cursor includes the following steps −

1) Declaring the cursor for initializing the memory


2) Opening the cursor for allocating the memory
3) Fetching the cursor for retrieving the data
4) Closing the cursor to release the allocated memory

1) Declaring the Cursor


 Declaring the cursor defines the cursor with a name and the associated SELECT
statement. Syntax: CURSOR <cursor_name> IS <select_statement> ;
Example:-
CURSOR c_customers IS
SELECT id, name, address FROM customers;

2) 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.

Syntax: OPEN <cursor_name>; Example:-


OPEN c_customers;

3) Fetching the Cursor


 Fetching the cursor involves accessing one row at a time.
Syntax1: FETCH <cursor_name> INTO record;
Example:- FETCH c_customers INTO c_id, c_name, c_addr;

DECLARE
4) Closing the Cursor ENO EMP.EMPNO%TYPE;
 Closing the cursor NAME EMP.ENAME%TYPE;
SALARY EMP.SAL%TYPE;
means releasing CURSOR c1 IS
the allocated SELECT EMPNO, ENAME, SAL FROM EMP WHERE SAL>5000;
BEGIN
memory. OPEN c1;
Syntax: LOOP
FETCH c1 INTO ENO, NAME, SALARY;
CLOSE <cursor_name>; EXIT WHEN c1 % NOTFOUND;
dbms_output.put_line(EMPO || ' ' || NAME || ' ' || SALARY);
Example: END LOOP;
CLOSE c1;
CLOSE c_customers; END;
/
CURSOR FOR LOOP:-

 The cursor FOR LOOP implicitly declares its loop index as a record of type %ROWTYPE,
opens a cursor, repeatedly fetches rows of the values form the active set into fields in the
record.
DECLARE
Syntax: - CURSOR cr IS
SELECT * FROM EMP WHERE deptno=20;
FOR <INDEX> IN < CURSOR_NAME> LOOP BEGIN
OPEN cr;
<STATEMENTS>; LOOP
FOR I IN cr LOOP
END LOOP;
dbms_output.put_line(I.ENAME || ‘ ‘ ||I.sal);
END LOOP;
CLOSE cr;
END;
/

TRIGGERS in PL/SQL
 Trigger is a named PL/SQL block stored in a database and executed(fired) implicitly
(automatically) when triggering specific event occurs.
 A trigger event is a DML is INSERT, UPDATE, DELETE statement executed against a
Database Table.
 Syntax:
CREATE OR REPLACE TRIGGER trigger_name
[ BEFORE / AFTER ] [ INSERT / UPDATE / DELETE OF column_name] ON table_name
[FOR EACH ROW]
[WHEN condition]
DECLARE
Declaration statements;
BEGIN
Pl/SQL instructions; (trigger action)
……………………………………
END;
Advantages of Triggers:
 Maintaining complex security rules.
 Automatically generating values for derived columns
 Preventing invalid transactions
 Providing value auditing.
BEFORE TRIGGERS:
 Here triggers fire BEFORE any transactions are implemented.
o BEFORE INSERT , BEFORE UPDATE , BEFORE DELETE

AFTER TRIGGERS:
 Here triggers fire AFTER any transactions are implemented.
o AFTER INSERT , AFTER UPDATE , AFTER DELETE

Types of Triggers:-
1) Statement-level Trigger
2) Row-level Trigger
3) BEFORE Trigger
4) AFTER Trigger

1) Statement-level Trigger:- A statement trigger is fired once for the triggering statement.
 In this model number of rows affected by the triggering statement.
Example:-
CREATE OR REPLACE TRIGGER stmt_level
Execute Trigger: BEFORE UPDATE ON EMP
DECLARE
SQL> update emp set sal=10000
MSG VARCHAR2(30):=’Statement-level Trigger Fired’;
where deptno=20; BEGIN
DBMS_OUTPUT.PUT_LINE(MSG);
Statement-level Trigger Fired
END;
5 rows updated. /
SQL> Output:- Trigger Created.

2) Row-Level Trigger:- A row-level trigger is fired each time the table is affected by the triggering
statement. CREATE OR REPLACE TRIGGER row_level
Execute Trigger: BEFORE UPDATE ON DEPT
FOR EACH ROW
SQL> update dept set loc=’USA’ DECLARE
where dname=’FINANCE’; MSG VARCHAR2(30):=’Row-level Trigger Fired’;
BEGIN
Row-level Trigger Fired DBMS_OUTPUT.PUT_LINE(MSG);
Row-level Trigger Fired END;
2 rows updated. / Output:- Trigger Created.

3) BEFORE Trigger:- BEFORE triggers CREATE OR REPLACE TRIGGER UPP_TRIG


are commonly used to check the validity BEFORE INSERT ON EMP
of the data before the action is FOR EACH ROW
performed. DECLARE
 For example to create a trigger which : new . ENAME := UPPER( : new . ENAME );
makes the entry in ENAME column in END;
UPPERCASE. / Output:- Trigger Created.

CREATE OR REPLACE TRIGGER after_del


4) AFTER Trigger:- AFTER DELETE ON EMP
AFTER triggers are fired FOR EACH ROW
after the triggering action is DECLARE
completed. IF : old.EMPNO=7839 THEN
 For example the following raise_application_error(-20015, ‘You cannot delete this row’);
AFTER DELETE trigger is END IF;
preventing to delete END;
/ Output:- Trigger Created.
records.
Example:
Dropping Trigger:- To drop a trigger, DROP TRIGGER statement is used.
Syntax: DROP TRIGGER <trigger_name>;
Example: DROP TRIGGER t1;

EXCEPTIONSin PL/SQL

 An exception is an error conditionduring a program execution.


 PL/SQL supports programmers to catch such conditionsusing EXCEPTION block in the
program and an appropriate action is taken against theerror condition.
 There are two types of exceptions:
1. System-defined exceptions
2. User-defined exceptions

Syntax for Exception Handling:- Example for System-defined Exceptions:-


DECLARE DECLARE
<declarations section> N NUMBER;
BEGIN BEGIN
<executable command(s)> N:=10/0;
EXCEPTION EXCEPTION
WHEN ZERO_DIVIDE THEN
<exception handling goes here > dbms_output.put_line(‘Zero divide Error’);
WHEN exception1 THEN WHEN NO_DATA_FOUND THEN
exception1-handling-statements dbms_output.put_line(‘Data not exist’);
WHEN exception2 THEN WHEN OTHERSTHEN
exception2-handling-statements dbms_output.put_line(‘Error in block’);
........ END;
WHEN others THEN /
exception3-handling-statements Output:-
Zero divide Error
END;

Pre-defined Exceptions :-PL/SQL provides many pre-defined exceptions, which are


executed when any databaserule is violated by a program.

Exception Description
INVALID_CURSOR Invalid cursor
INVALID_NUMBER Invalid number
NO_DATA_FOUND It is raised when a SELECT INTOstatement returns no
rows.
ZERO_DIVIDE It is raised when an attempt is
made to divide a number by zero.
VALUE_ERROR numeric or value error
CURSOR_ALREADY_OPEN Cursor already open
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 RAISEstatement
or the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.
o Step1: Declaring an exception
o Step2. Raising an exception
o Step 3: Handling an exception
Step 1: Declaring an Exception:-
Syntax:- DECLARE
exception-identifier EXCEPTION;
Step 2: Raising an Exception:-

Syntax:- RAISE exception-identifier;

Step 3: Handling an Exception:-


Syntax:-
BEGIN
---------
---------
EXCEPTION
WHEN exception-identifierTHEN
Statements;
END;

Example program for User defined exceptions:-


DECLARE
MyException EXCEPTION;
BEGIN
IF TO_CHAR(SYSDATE, ‘DY’) = ‘SUN’ THEN
RAISE MyException;
END IF;
EXCEPTION
WHEN MyExceptionTHEN
dbms_output.put_line(‘Sunday No transaction’);
END;
/
Output:-
Sunday No transaction

Example program for Predefined exceptions:-


DECLARE
eno NUMBER(4);
enm VARCHAR2(20);
BEGIN
SELECT empno, ename INTO eno, enm FROM emp WHERE empno=&empno;
dbms_output.put_line(‘EMPNO’ | | ‘ENAME’);
dbms_output.put_line(eno | |’ ‘ ||’ ‘|| enm);
EXCEPTION
WHEN NO_DATA_FOUND THEN
dbms_output.put_line(‘Employee number not exist’);
END;
/
Output:-
Enter value for empno : 4001
Employee number not exist
PACKAGES in pl/sql

Packages:-
 A package is a database object that contains groups of pl/sql objects such as
procedures, functions, variables, cursor, type declarations into a single unit.
 This reduces the unnecessary disk I/O and network traffic.
o A Package usually has two parts;
1) Package specification
2) Package body
1) Package specification:- The package specification contains information about
variable, exceptions, cursors, procedure, function. These all objects are accessible
from other applications.
Syntax:-
CREATE OR REPLACE PACKAGE package_name[IS/AS]
procedure_specification.
function_specification;
exception_declaration;
cursor_declaration;
END package_name;
This package contain procedure called fire it used to delete employee who has been fired. It has function
dispsalwhich accepts employee number and returns the salary.
Example:-
SQL> CREATE OR REPLACE PACKAGE fire_dispsal
AS
PROCEDURE fire(pnoNUMBER);
FUNCTIONdispsal(fno NUMBER) RETURN number;

END ;

2) Package Body:-A package bodycontains the actualexecutable code for the objects
described in the package specification. It fully defines cursors, procedures, and
functions declared in the package specification. To create package body use the
CREATE PACKAGE BODY statement.
Syntax:- CREATE OR REPLACE PACKAGE BODY package_name [ IS / AS ]
procedure_definitioin.
function_definitioin;
BEGIN
Executable_statements;
[EXCEPTION
Exception_handlers]]
END package_name;

Example:-
SQL> CREATE PACKAGE BODY fire_dispsal AS
PROCEDURE fire(pno NUMBER) is
Begin
DELETE FROMempWHEREempno=pno;
End fire;
FUNCTION dispsal(fno NUMBER) RETURN NUMBER IS
s NUMBER;
begin
SELECT salINTO s FROM empWHEREempno=fno;
return s;
enddispsal;
end;
Accessing Packages:-
Package_name.procedure_name(parameter);
Package_name.function_name(parameter);
Example:-
SQL> CALL fire_dispsal.fire(101);
Example:-
SQL> declare
R number;
Begin
fire_dispsal.fire(101);
r:=fire_dispsal.dispsal(102);
dbms_output.put_line(r);
end;
/
Advantages of Packages:
1) Modularity
2) Easier application design
3) Information hiding
4) Better performance.

You might also like