You are on page 1of 98

Database Management System

III B.Com Computer Applications

Department of Computer Applications


Government Degree College
Nagari
UNIT – I
Data and Information
Data are raw facts that constitute building block of information. Data are the
heart of the DBMS. It is to be noted that all the data will not convey useful
information. Useful information is obtained from processed data. In other words, data
has to be interpreted in order to obtain information. Good, timely, relevant
information is the key to decision making. Data are a representation of facts, concepts,
or instructions in a formalized manner suitable for communication, interpretation, or
processing by humans or automatic means. The data in DBMS can be broadly
classified into two types, one is the collection of information needed by the
organization and the other is “metadata” which is the information about the database.
The term “metadata” will be discussed in detail later in this chapter. A company needs
to save information about employees, departments, and salaries. These pieces of
information are called data. Permanent storage of data are referred to as persistent
data.
Information is data that has been processed in such a way as to be meaningful
to the person who receives it. Information is data that has been converted into a more
useful or intelligible form. It is the set of data that has been organized for direct
utilization of mankind, as information helps human beings in their decision making
process. Examples are: Time Table, Merit List, Report card, Headed tables, printed
documents, pay slips, receipts, reports etc. The information is obtained by assembling
items of data into a meaningful form. For example, marks obtained by students and
their roll numbers form data, the report card/sheet is the .information. Other forms of
information are pay-slips, schedules, reports, worksheet, bar charts, invoices and
account returns etc.

Database
A database is a collection of information that is organized. So that it can easily
be accessed, managed, and updated. A database is a well-organized collection of data
that are related in a meaningful way, which can be accessed in different logical orders.
Database systems are systems in which the interpretation and storage of information
are of primary importance. The database should contain all the data needed by the
organization as a result, a huge volume of data, the need for long-term storage of the
data, and access of the data by a large number of users generally characterize database
systems

Database Management System


A database management system (DBMS) consists of collection of interrelated
data and a set of programs to access that data. It is software that is helpful in
maintaining and utilizing a database. A DBMS consists of:
 A collection of interrelated and persistent data. This part of DBMS is
referred to as database (DB).
 A set of application programs used to access, update, and manage data.
This part constitutes data management system (MS).

DBMS Page 1
 A DBMS is general-purpose software i.e., not application specific. The
same DBMS (e.g., Oracle, Sybase, etc.) can be used in railway
reservation system, library management, university, etc.
 A DBMS takes care of storing and accessing data, leaving only
application specific tasks to application programs. it is evident that
DBMS allows user to input data, share the data, edit the data,
manipulate the data, and display the data in the database. Because a
DBMS allows more than one user to share the data; the complexity
extends to its design and implementation.

Objectives of DBMS
The main objectives of database management system are data availability, data
integrity, data security, and data independence.
1. Data Availability: Data availability refers to the fact that the data are made
available to wide variety of users in a meaningful format at reasonable cost so
that the users can easily access the data.
2. Data Integrity: Data integrity refers to the correctness of the data in the
database. In other words, the data available in the database is a reliable data.
3. Data Security : Data security refers to the fact that only authorized users can
access the data. Data security can be enforced by passwords. If two separate
users are accessing a particular data at the same time, the DBMS must not
allow them to make conflicting changes
4. Data Independence : DBMS allows the user to store, update, and retrieve
data in an efficient manner. DBMS provides an “abstract view” of how the
data is stored in the database. In order to store the information efficiently,
complex data structures are used to represent the data. The system hides
certain details of how the data are stored and maintained.

Evolution of Database Management Systems


File-based system was the predecessor to the database management system.
Apollo moon-landing process was started in the year 1960. At that time, there was no
system available to handle and manage large amount of information. As a result,
North American Aviation which is now popularly known as Rockwell International
developed software known as Generalized Update Access Method (GUAM).
In the mid-1960s, IBM joined North American Aviation to develop GUAM
into Information Management System (IMS). IMS was based on Hierarchical data
model. In the mid-1960s, General Electric released Integrated Data Store (IDS).
IDS were based on network data model. Charles Bachmann was mainly
responsible for the development of IDS. The network database was developed to
fulfill the need to represent more complex data relationships than could be modeled
with hierarchical structures.
Conference on Data System Languages formed Data Base Task Group
(DBTG) in 1967. DBTG specified three distinct languages for standardization. They
are Data Definition Language (DDL), which would enable Database Administrator to
define the schema, a subschema DDL, which would allow the application programs to
define the parts of the database and Data Manipulation Language (DML) to

DBMS Page 2
manipulate the data. The network and hierarchical data models developed during that
time had the drawbacks of minimal data independence, minimal theoretical
foundation, and complex data access.
To overcome these drawbacks, in 1970, Codd of IBM published a paper titled
“A Relational Model of Data for Large Shared Data Banks” in Communications of
the ACM, vol. 13, No. 6, pp. 377–387, June 1970.
As an impact of Codd’s paper, System R project was developed during the late
1970 by IBM San Jose Research Laboratory in California. The project was developed
to prove that relational data model was implementable. The outcome of System R
project was the development of Structured Query Language (SQL) which is the
standard language for relational database management system.
In 1980s IBM released two commercial relational database management
systems known as DB2 and SQL/DS and Oracle Corporation released Oracle.
In 1979, Codd himself attempted to address some of the failings in his
original work with an extended version of the relational model called RM/T in 1979
and RM/V2 in 1990.
The attempts to provide a data model that represents the “real world” more
closely have been loosely classified as Semantic Data Modeling.
In recent years, two approaches to DBMS are more popular, which are Object-
Oriented DBMS (OODBMS) and Object Relational DBMS (ORDBMS). The
chronological order of the development of DBMS is as follows:
 Flat files – 1960s–1980s
 Hierarchical – 1970s–1990s
 Network – 1970s–1990s
 Relational – 1980s–present
 Object-oriented – 1990s–present
 Object-relational – 1990s–present
 Data warehousing – 1980s–present
 Web-enabled – 1990s–present
Early 1960s. Charles Bachman at GE created the first general purpose DBMS
Integrated Data Store. It created the basis for the network model which was
standardized by CODASYL (Conference on Data System Language).
Late 1960s. IBM developed the Information Management System (IMS). IMS
used an alternate model, called the Hierarchical Data Model.
1970. Edgar Codd, from IBM created the Relational Data Model.
In 1981 Codd received the Turing Award for his contributions to database
theory. Codd Passed away in April 2003.
1976. Peter Chen presented Entity-Relationship model, which is widely used
in database design. 1980. SQL developed by IBM, became the standard query
language for databases. SQL was standardized by ISO.
1980s and 1990s. IBM, Oracle, Informix and others developed powerful
DBMS.

DBMS Page 3
Classification of Database Management System
The database management system can be broadly classified into two
categories, they are
(1) Passive Database Management System
(2) Active Database Management System

1. Passive Database Management System.


Passive Database Management Systems are program-driven. In passive
database management system the users query the current state of database and retrieve
the information currently available in the database. Traditional DBMS are passive in
the sense that they are explicitly and synchronously invoked by user or application
program initiated operations. Applications send requests for operations to be
performed by the DBMS and wait for the DBMS to confirm and return any possible
answers. The operations can be definitions and updates of the schema, as well as
queries and updates of the data.

2. Active Database Management System.


Active Database Management Systems are data-driven or event-driven
systems. In active database management system, the users specify to the DBMS the
information they need. If the information of interest is currently available, the DBMS
actively monitors the arrival of the desired information and provides it to the relevant
users. The scope of a query in a passive DBMS is limited to the past and present data,
whereas the scope of a query in an active DBMS additionally includes future data. An
active DBMS reverses the control flow between applications and the DBMS instead
of only applications calling the DBMS, the DBMS may also call applications in an
active DBMS.

DBMS Page 4
UNIT-II

Historical Roots of File and File System


In olden days records are maintained in traditional file systems. File system
means organization of files.
File is a collection (or) group of records. A record is collection of fields.
Where the field contains the real data. For ex: Student file, Where we maintain all
students record consisting of Roll No, name, group, marks, average.
In the olden days the file system maintains all the files in flat manner (flat
files/text-files). The flat file permits to search any record in sequential access only. It
was cumbersome and slow. To overcome the slowness they have gone for Index file
system which was faster in accessing in random manner. But it occupies extra
memory to maintain Index table.
In general in the file system all the data has to be stored in the corresponding
folders (or) directories. For ex: In a college we can maintain admission details of
students. Suppose the director wants to know today’s admission status group wise in
that case the file manager (or) clerk has to open each folder to answer the director’s
question. That’s why it is time consuming, memory consuming, may be error prone.
To over come this, the data base system has evolved. Which uses the 4GL
language i.e. SQL. Which allows answering any query?
The DBMS maintains all the records in the form of tables by means of rows
and columns. But in DBMS before storing the data the schema has to be created with
the help of DDL.
File system:
Assume maintaining the first year student’s data using file systems.
BBA B.Sc B.Com BA

Folder name
Roll No, name, fees Roll No, name, fees
Every folder contains all the relevant fields which occupy extra memory, calculation
is slow. Constraints cannot be imposed in File systems DBMS.

Roll No Name Branch Fees


60012 Gopal B.Sc 20000
60013 Sainath B.Com 19000
60014 Surekha B.Sc 20000
60015 Ramya BBA 30000
In DBMS all the students information will be available in a centralized place
i.e. table. So it is easy to retrieve any data using query.
Constraints can be imposed in DBMS. [Primary key]. Data redundancy can be
removed easily.

DBMS Page 5
File processing system
File processing systems at Pine Valley Furniture Company
Pine Valley Furniture Company manufactures high-quality all-wood
furniture and distributes it to retail stores nationwide. Among the firm’s several
product lines are computer desks, entertainment centers, dinette sets, bookcases, and
wall units. Customers submit orders to Pine Valley furniture by any of several means
i.e., telephone, mail, fax (or) electronic forms via the Internet.
Early computer applications at Pine Valley furniture used the traditional
file processing approach.
Three of the computer applications based on the file processing approach
are shown in below figure. The systems illustrated are order filling, Invoicing and
payroll. The figure also shows the major data files associated with each application.
For example the order filling system has three files; customer master, inventory
master and backorder.
Disadvantages of file processing systems: Several disadvantages are associated with
conventional file processing systems. These disadvantages are
1. Program Data dependency: File descriptions are stored within each
application program that accesses a given file. For example, in the Invoicing
system in the above figure program A accesses both the Inventory pricing file
and the customer master file. Therefore, this program contains a detailed file
description for both of these files. As a consequence any change to a file
structure requires changes to the file description for all programs that the file.

Figure:
Orders Department Accounting Payroll
Department Department
Progra Progra Progra Department
Progra Progra Progra Progra
mA mB mC mA mB mA mB

Order Filling Invoicing Payroll


System System System

Customer Inventory Back Inventory Customer Employee


Master Master Order Pricing Master Master
File File File File File File

DBMS Page 6
2. Duplication of Data: Since applications are often developed independently in file
processing systems unplanned duplicate data files are rule rather than the exception.
For example in the above figure the order filling system contains an Inventory pricing
file, while the Invoicing system contains an Inventory pricing file. These files
undoubtedly both contain data describing Pine Valley Furniture company’s products.
Such as product description, unit price and quantity on hand. This duplication
wasteful since it requires additional storage space and increased effort to keep all files
up to date. Unfortunately, duplicate data files often result in loss of data integrity.
3. Limited data sharing: With the traditional file processing approach, each
application has its own private files and users have little opportunity to share data
outside their own applications. Notice in the above figure. For example, that user in
the accounting department has access to the Invoicing system and its files, but they
probably do not have access to the order filling system (or) the payroll system and
their files. It is often frustrating to managers to find that a requested report will
require a major programming effort to obtain data from several incompatible files in
separate systems.
4. Lengthy Development Times: With traditional file processing systems, there is
little opportunity to leverage previous development efforts. Each new application
requires that the developer essentially start from scratch by designing new file formats
and descriptions and then writing the file access logic for each new program. The
lengthy development times required are often inconsistent with today’s fast paced
business environment.
5. Excessive Program Maintenance: The preceding factors all combine to create a
heavy program maintenance load in organizations that rely on traditional file
processing systems. In fact, as much as 80 percent of the total information systems
development budget may be devoted to program maintenance in such organizations.
This of course leaves little opportunity for developing new applications.

Advantages and disadvantages of DBMS :


In a typical file-processing system, records are stored in various files. A
number of different application programs are written to extract records from and add
records to the appropriate files. File-processing system has a number of major
disadvantages, such as data redundancy, data inconsistency, unsharable data,
unstandardized data, insecure data, incorrect data etc.
Database management system answers all these problems as it provides a
centralized control over data. The advantages of DBMS are as follows:

1. Reduces the data redundancy to a large extent.


Data redundancy means duplication of data. Non-database systems maintain
separate copy of data for each application. The database systems do not maintain
separate copies of the same data. Rather, all the data are kept at one place and all the
applications that require data refer to the centrally maintained database.
2. Databases can control data inconsistency to a large extent
When the redundancy is not controlled, there may be occasions on which the
two entries about the same data do not agree. At such times, database is said to be
inconsistent. Obviously, an inconsistent database will provide incorrect or conflicting
information.

DBMS Page 7
3. Databases facilitate sharing of data
Sharing of data means that individual pieces of data in the database may be
shared among several different users, in the sense that each of those users may have
access to the same piece of data and each of them may use it for different purposes.
4. Databases enforce standards
The database management system can ensure that all the data follow the
applicable standards. There may be certain standards laid by the company or
organization using the database. Similarly, there may be national or international
standards.
5. Databases can ensure data security
A database management system ensures data security and privacy by ensuring
that the only means of access to the database is through the proper channel and also
by carrying out authorization checks whenever access to sensitive data is attempted.
6. Program-Data Independence
The separation of data description (metadata) from the application programs
that use the data is called data independence. With the database approach, data
descriptions are stored in a central location called the repository.
7. Increased Productivity of Application Development
A major advantage of the database approach is that it greatly reduces the cost
and time for developing new business applications.
8. Improved Data Quality
The database approach provides a number of tools and processes to improve
data quality.
9. Improved Data Accessibility and Responsiveness
With a relational database, end users without programming experience can
often retrieve and display data, even when it crosses traditional departmental
boundaries.
Disadvantages of DBMS
In spite of the advantages of using a DBMS, there are a few situations in
which such a system may involve unnecessary overhead costs that would not be
incurred in traditional file processing. The overhead costs of using a DBMS are due
to the following.
 High initial investment in hardware, software and training.
 The generality that a DBMS provides for defining and processing data.
 Overhead for providing security, concurrency control, recover, and integrity
functions.
 Additional problems may arise if the database designers and DBA do not
properly design the database or if the database systems applications are not
implemented properly.

Functions of the DBMS:


A DBMS performs several functions that guarantee the integrity and consistency
of the data in the database. Most of those functions are transparent to end users, and
most can be achieved only through the use of a DBMS.
1. Data dictionary management:- The DBMS stores definitions of the data elements
and their relationships (metadata) in a data dictionary. In turn, all programs that
access the data in the databases work through the relationship, thus relieving you from

DBMS Page 8
having to code such complex relationships in each program. In other words, the
DBMS provides data abstraction and it removes structural and data dependency from
the system.
2. Data storage management: The DBMS creates and manages the complex
structures required for data storage, thus relieving you from the difficult task of
defining and programming the physical data characteristics. Data storage management
is also important for database performance tuning. Performance tuning relates to the
activities that make the database perform more efficiently in terms of storage and
access speed.
3. Data transformation and presentation: The DBMS transforms entered data to
conform to required data structures. The DBMS relieves you of the chore of making a
distinction between the logical data format and the physical data format. That is, the
DBMS formats the physically retrieved data to make it conform to the user’s logical
expectations.
4. Security management: The DBMS creates a security system that enforces user
security and data privacy. Security rules determine which users can access the
database, which data items each user can access, and which data operations the user
can perform.
5. Multiuser access control: To provide data integrity and data consistency, the
DBMS uses sophisticated algorithms to ensure that multiple users can access the
database concurrently without compromising the integrity of the database.
6. Backup and recovery management: The DBMS provides backup and data
recovery to ensure data safety and integrity. Current DBMS systems provide special
utilities that allow the DBA to perform routine and special backup and restore
procedures. Recovery management deals with the recovery of the database after a
failure, such as a bad sector in the disk or a power failure.
7. Data integrity management: The DBMS promotes and enforces integrity rules,
thus minimizing data redundancy and maximizing data consistency. The data
relationships stored in the data dictionary are used to enforce data integrity. Ensuring
data integrity is especially important in transaction-oriented database systems.
8. Database access languages and application programming interfaces: The
DBMS provides data access through a query language. A query language is a
nonprocedural language-one that lets the user specify what must be done without
having to specify how it is to be done.
9. Database communication interfaces: Current-generation DBMSs accept end-user
requests via multiple, different network environments. For example, the DBMS might
provide access to the database via the Internet through the use of Web browsers such
as Mozilla Firefox or Microsoft Internet Explorer.

Data models:
Data model: A Model is an abstraction of a more complex real-world object
or event. A data model is the relatively simple representation, usually graphical of
complex real world data structures. The data model’s main function is to help us
understand the complexities of the real world environment.
Within the database environment, a data model represents data structures and
their characteristics, relations, constraints, and transformations. Good database design
uses an appropriate data model as its foundation.

DBMS Page 9
A data model provides a blueprint of the data that is required for a functional
system.
Types of database models.
Data modeling or database modeling is a technique that records the inventory,
shape, size, contents and rules of data elements used in the scope of business process.
The business process scope may be as large as a multidiscipline global corporation,
or as small as the receiving of dock. Simply we can define data model as modeling of
data for an organization.
Types of Database models:
1. Flat file database model
2. Hierarchical database model
3. Network database model
4. Relational database model
5. The E-R model.
6. Object oriented model
7. Object relational Database model

Flat file database model:


A flat file database consists of one or more readable files, normally stored in a
text format. Information in these files is stored as fields, the fields having either a
constant length or a variable length
Every flat file database system is different because companies store different
data and companies have different needs.

Hierarchical database model:

The architecture of a hierarchical model is based on the concept of


parent/child relationships. To overcome the problems flat file model it is developed.
It a hierarchical database, a root table, or parent table, resides at the top of the
structure, which points to child tables containing related data. The structure of
hierarchical database model appears are an inverted tree.

Publishers

Authors Book Store

Titles Inventory Orders

DBMS Page 10
Network Database model:
Improvements were made to the hierarchical model in order to derive the
network model. One of the model main advantages of the network model is the
capability of a parent to share relationships with child. This means that a child table
can have multiple parent cables. Additionally, a user can access data by starting with
any cable in the structure, navigating either up or down in the tree. The user is not
required to access a root table first to get to child tables.

Publishers

Authors Book
Store
Titles Inventory Orders

The Relational Database Model


The relational model was introduced in 1970 by E.F.Codd in his landmark
paper ”A Relational Model of Data for Large shared Databanks”. The relational
model represented a major breakthrough for both users and designers. To use an
analogy, the relational model produced an “automatic transmission“ database to
replace the “standard transmission” databases that proceeded it . Its conceptual
simplicity set the stage for genuine database revolution.
The Entity Relationship (E-R) model
The entity relationship data model is based on a perception of a real world that
consists of collection of a basic objects called entities and relationships among these
objects. Entities are described in a database by a set of attributes. For example, the
attributes acc_no, and balance may describe one particular account in a bank, and
they from attributes of the account entity set. Similarly, attributes
cust_name,cust_street and cust_city may describe a customer entity.

C_Nam C_Street
e Acc_Num balance

Cust_Id C_City

deposit
CUSTOMER or ACCOUNT

Object oriented data base model:


An OO programming language allows the programmer to work with objects to
a time an application that interacts with a relational database. During the last few
years, object oriented programming has become popular with languages such as C++,
VB & Java. For ex. Elements within a program or database application are usually
represented as objects. These objects have properties, which can be modified, and can
also be inherited from other objects. Related types of objects are assigned various

DBMS Page 11
properties that can be adjusted to define the particular object and determine how the
object will act.
Object Relational Database Model:
Although some major seems exist between the object oriented
and relational models, the object relational model was developed with the objective
of the concepts of the relational databases model with object-oriented programming
style. The OR model is supposed to represent the best of both workers ( relational &
OO ), although OR model is still early in development.

Person
Eno fname varchar
E_inf person &name varchar
Address_inf address initial varchar
Phone number
Address
Street varchar
City varchar
State varchar

Components and Interfaces of Database Management System


A database management system involves five major components:
 Hardware
 Software
 Data
 Users/People
 Procedures
The interfaces between the components are shown in the figure.
<

DBMS Page 12
Hardware:
The hardware can range from a single personal computer to a mainframe or to
a network of computers. The particular hardware depends on the requirements of the
organization and the DBMS used. A DBMS requires a minimum amount of main
memory and disk space to run, but this minimum configuration may not necessarily
give acceptable performance.
Software:
The software includes the DBMS software, application programs together with
the operating systems including the network software if the DBMS is being used over
a network. The application programs are written in third generation programming
languages like ‘C’, COBOL, etc. or using fourth generation language such as SQL,
embedded in a third generation language.
The target DBMS may have its own fourth generation tools which allow
development of applications through the provision of non procedural query languages,
report generators, graphics generators and application generators.
Data:
Database is an organized collection of logically related data, usually designed
to meet the information needs of multiple users in an organization. It is important to
distinguish between the database and the repository. The repository contains
definitions of data, whereas the database contains occurrences of data.
The data in the database is integrated, shared and persistent.
Integrated Data: A data can be considered to be a unification of several
distinct data files and when any redundancy among those files is eliminated.
Shared Data: A database contains data that can be shared by different users
for different applications simultaneously.
Persistent Data: A data which cannot be removed from the database as a side
effect of some other process. Persistent data have a life span that is not limited to
single execution of the programs that use them.
Users/people interacting with database:

Procedure:
Procedures are the rules that govern the design and the use of database.

Components of Database Environment:


The major components of a typical database environment and their
relationships are shown below.

Data System End Users


Administrators developers

CASE Tools User Interface Application


Programs

Repository DBMS Database

DBMS Page 13
1. Computer-aided software engineering (CASE) tools : CASE Tools are
automated tools used to design databases and application programs.
2. Repository: Repository is Centralized knowledge base for all data definitions,
data relationships, screen and report formats, and other system components. A
repository contains an extended set of metadata important for managing
databases as will as other components of an information system.
3. Database management system (DBMS): DBMS is a Commercial software
(and occasionally, hardware and firmware) system, which is used to define,
create, maintain, and provide controlled access to the database and also to the
repository. In other words DBMS is collection of logically related data and set
of programs to operate data.
4. Database: Database is an organized collection of logically related data,
usually designed to meet the information needs of multiple users in an
organization. It is important to distinguish between the database and the
repository. The repository contains definitions of data, whereas the database
contains occurrences of data.
5. Application Programs: Application programs are Computer programs that are
used to create and maintain the database and provide information to users.
6. User interface Languages, menus, and other facilities by which users interact
with various system components, such as CASE tools, application programs,
the DBMS, and the repository.
7. Data administrators Persons who are responsible for the overall information
resources of an organization. Data administrators use CASE tools to improve
the productivity of database planning and design.
8. System developers Persons such as systems analysts and programmers who
design new application programs. System developers often use CASE tools for
system requirements analysis and program design.
9. End users Persons throughout the organization who add, delete, and modify
data in the database and who request or receive information from it. All user
interactions with the database must be routed through the DBMS.

Ranges of Database Applications:

The range of database applications can be divided into five categories:


Personal databases, workgroup databases, department databases, enterprise databases,
and Internet, Intranet, and Extranet databases.
Personal Databases:
Personal databases are designed to support one user. Personal databases have
long resided on personal computers (PCs), including laptops. Recently the
introduction of personal digital assistants (PDAs) has incorporated personal databases
into handheld devices that not only function as computing devices but also as cellular
phones, fax senders, and Web browsers.

DBMS Page 14
Personal databases are widely used because they can often improve personal
productivity. However, they entail a risk: The data cannot easily be shared with other
users. For this reason, personal databases should be limited to those rather special
situation (such as in a very small organization) where the need to share the data
among users of the personal database is unlikely to arise.
Workgroup Database:
A workgroup is a relatively small team of people who collaborate on the same
project or application or on a group of similar projects or applications. A workgroup
typically comprises fewer than 25 persons. A workgroup database is designed to
support the collaborative efforts of such a team.
The method of sharing the data in this database is shown in below figure.
Each member of the workgroup has a desktop computer and the computers are linked
by means of a local area network (LAN). The database is stored on a central device
called the database server, which is also connected to the network. Thus each member
of the workgroup has access to the shared data.
Workgroup database with local area network
Developer 1 Developer n Project Manager Librarian

Local area network

Database
server

Workgroup
Department Databases: database

A department is a functional unit within an organization. Typical examples of


department are personnel, marketing, manufacturing, and accounting. A department
is generally larger than a workgroup (typically between 25 and 100 persons) and is
responsible for a more diverse range of functions.
Department databases are designed to support the various functions and
activities of a department.

Enterprise Databases:
An enterprise database is one whose scope is the entire organization or enterprise
(or, at least, many different departments). Such databases are intended to support
organization-wide operations and decision making. An enterprise database does,
however, support information needs from many departments. Over the last decade,
the evolution of enterprise databases has resulted in two major developments:
1. Enterprise resource planning (ERP) systems
2. Data warehousing implementations.

DBMS Page 15
An enterprise data warehouse

Branch
Office -1

Branch
Office-2
Branch Corporate
Office-3 Office
Data
Branch warehouse
Office- 4

Branch
Office-5

Internet, Intranet and Extranet Databases


Internet: The most recent changes that affects the database environment is the
ascendance of the Internet, a worldwide network that connects users of multiple
platforms easily through an interface known as a Web browser.
Extranet: Use of Internet protocols to establish limited access to company data and
information by the company’s customers and suppliers.
Intranet: Use of Internet protocols to establish access to company data and
information that is limited to the organization.

Database Architecture
Database architecture essentially describes the location of all the pieces of
information that make up the database application. The database architecture can be
broadly classified into the following categories
 Two-Tier Architecture
 Three-tier Architecture
 Multitier Architecture .
Two-Tier Architecture:
The two-tier architecture is a client–server architecture in which the client
contains the presentation code and the SQL statements for data access. The database
server processes the SQL statements and sends query results back to the client. Two-
tier client/server provides a basic separation of tasks. The client, or first tier, is
primarily responsible for the presentation of data to the user and the “server,” or
second tier, is primarily responsible for supplying data services to the client.
Presentation Services
“Presentation services” refers to the portion of the application which presents
data to the user. In addition, it also provides for the mechanisms in which the user will
interact with the data. More simply put, presentation logic defines and interacts with
the user interface. The presentation of the data should generally not contain any
validation rules.

DBMS Page 16
Application Services
“Application services” provide other functions necessary for the application.
Business Services/objects
“Business services” are a category of application services. Business services
encapsulate an organizations business processes and requirements. These rules are
derived from the steps necessary to carry out day-today business in an organization.
These rules can be validation rules, used to be sure that the incoming information is of
a valid type and format, or they can be process rules, which ensure that the proper
business process is followed in order to complete an operation.
Data Services
“Data services” provide access to data independent of their location. The data can
come from legacy mainframe, SQL RDBMS, or proprietary data access systems.
Advantages of Two-tier Architecture
 The two-tier architecture is a good approach for systems with stable
requirements and a moderate number of clients.
 The two-tier architecture is the simplest to implement, due to the number of
good commercial development environments.
Drawbacks of Two-tier Architecture
 Software maintenance can be difficult because PC clients contain a mixture of
presentation, validation, and business logic code.
 To make a significant change in the business logic, code must be modified on
many PC clients.
 Moreover the performance of two-tier architecture can be poor when a large
number of clients submit requests because the database server may be
overwhelmed with managing messages.
 With a large number of simultaneous clients, three-tier architecture may be
necessary.
Three-tier Architecture
Three-tier architecture
offers a technology neutral
method of building client/server
applications with vendors who
employ standard interfaces which
provide services for each logical
“tier.” Through standard tiered
interfaces, services are made
available to the application. A
single application can employ
many different services which
may reside on dissimilar
platforms or are developed and
maintained with different tools.
This approach allows a developer
to leverage investments in existing systems while creating new application which can
utilize existing resources.

DBMS Page 17
Multitier Architecture
A multi-tier, three-tier, or N-
tier implementation employs
a three-tier logical
architecture superimposed on
a distributed physical model.
Application Servers can
access other application
servers in order to supply
services to the client
application as well as to other
Application Servers. The
multiple-tier architecture is
the most general client–server
architecture. It can be most difficult to implement because of its generality. However,
a good design and implementation of multiple-tier architecture can provide the most
benefits in terms of scalability, interoperability, and flexibility. In the above example,
the client application looks to Application Server #1 to supply data from a mainframe-
based application. Application Server #1 has no direct access to the mainframe
application, but it does know, through the development of application services, that
Application Server #2 provides a service to access the data from the mainframe
application which satisfies the client request. Application Server #1 then invokes the
appropriate service on Application Server #2 and receives the requested data which is
then passed on to the client. Application Servers can take many forms. An
Application Server may be anything from custom application services, Transaction
Processing Monitors, Database Middleware, Message Queue to a CORBA/COM
based solution.
DBMS Vendors and their Products
Some of the popular DBMS vendors and their corresponding products are as follows
vendor product
IBM –DB2/MVS
–DB2/UDB –DB2/400
–Informix Dynamic Server (IDS)
Microsoft –Access
–SQLServer
–DesktopEdition(MSDE)
Open Source –MySQL
–PostgreSQL
Oracle –Oracle DBMS
–RDB
Sybase –Adaptive Server Enterprise (ASE)
–Adaptive Server Anywhere (ASA)
–Watcom
Different views of Database/Abstraction:

DBMS Page 18
DATA BASE ABSTRACTION: A collection of interrelated files and a set of
programs that allow users to access and modify these files are known as database
management system.
A major purpose of a database system is to provide the users only that much
information that is required by them. This means that the system does not disclose all
the details of data, rather it hides certain details of how the data is stored and
maintained.
Since the requirements of different users differ from one another, the
complexity of the database is hidden from them, if needed, through several levels of
abstraction in order to simplify their interaction with the system.
Various Levels of Database Implementation
A database is implemented through three general levels: internal, conceptual
and external so as cater to the needs of its users.
1. Internal Level (Physical Level). The lowest level of abstraction, the internal
level, is the one closest to physical storage. This level is also sometimes
termed as physical level. It describes how the data are actually stored on the
storage medium. At this level, complex low-level data structures are described
in details.
2. Conceptual Level This level of abstraction describes what data are actually
stored in the database. It also describes the relationships existing among data.
At this level, the database is described logically in terms of simple data-
structures. The users of this level are not concerned with how these logical
data structures will be implemented at the physical level. Rather, they just are
concerned about what information is to be kept in the database.
3. External Level (View Level). This is the level closest to the users and is
concerned with the way in which the data are viewed by individual users.
Most of the users of the database are not concerned with all the information
contained in the database. Instead, they need only a part of the database
relevant to them. For example, even though the bank database stores a lot
much information, an account holder (a user) is interested only in his account
details and not with the rest of the information stored in the database. To
simply such users’ interaction with the system, this level of abstraction is
defined. The system thus provides many views for the same database. The
below figure illustrates the interrelationship among these three levels of
abstraction.

DBMS Page 19
The Three Levels of Data Abstraction

Sales Purchase
Officer Officer

View 1 View 1 External Level


External View 1 View 2 View 3 Item-Name Item-Name (Individual User
Level Price Price Views)

(Application
Programs are
Conceptual Level used to fetch the
desired
information)
Conceptual
Item-Number Character (6)
Physical Level Item-Name Character (20)
Price Numeric (5+2)
Reorder-quantity Numeric (4)

Internal
Stored-Item Length = 40
Item# Type = Byte (6), Offset = 0, Index =
1x
Name Type = Byte (20), Offset = 6
Price Type = Byte (8), Offset = 26
ROQ Type = Byte (4), Offset = 34

DBMS Page 20
UNIT –III
Building Blocks of an Entity–Relationship Diagram
ER diagram is a graphical modeling tool to standardize ER modeling. The
modeling can be carried out with the help of pictorial representation of entities,
attributes, and relationships. The basic building blocks of Entity-Relationship diagram
are Entity, Attribute and Relationship.
Entity
An entity is an object that exists and is distinguishable from other objects.
Ex: person, place,department etc
Entity Type
An entity type or entity set is a collection of similar entities. Some examples of
entity types are:
– All students in EDC, say STUDENT.
– All courses in EDC, say COURSE.
– All departments in EDC, say DEPARTMENT.
An entity may belong to more than one entity type. For example, a staff working
in a particular department can pursue higher education as part-time. Hence the same
person is a LECTURER at one instance and STUDENT at another instance.
Relationship
A relationship is an association of entities where the association includes one
entity from each participating entity type whereas relationship type is a meaningful
association between entity types.
– Teaches is the relationship type between LECTURER and STUDENT.
– Buying is the relationship between VENDOR and CUSTOMER.
– Treatment is the relationship between DOCTOR and PATIENT.
Attributes
Attributes are properties of entity types. In other words, entities are described in a
database by a set of attributes.
– Brand, cost, and weight are the attributes of CELLPHONE.
– Roll number, name, and grade are the attributes of STUDENT.
ER Diagram
The ER diagram is used to represent database schema. In ER diagram:
– A rectangle represents an entity set.
– An ellipse represents an attribute.
– A diamond represents a relationship.
– Lines represent linking of attributes to entity sets and of entity sets to
relationship sets.

DBMS Page 21
Entity Set 

Attribute 

Relationship 

Classification of Entity Sets


Entity sets can be broadly classified into:
 Strong entity.
 Weak entity.
 Associative entity.

Entity Set

Strong entity Weak entity Associative entity

Strong Entity
Strong entity is one whose existence does not depend on other entity.
Example
Consider the example, student takes course. Here student is a strong entity.

Student Takes Course

Weak Entity
Weak entity is one whose existence depends on other entity. In many cases, weak
entity does not have primary key

EMPLOYEE depend DEPENDENTS


s

Associative entity 
An associative entity is a term used in relational and entity–relationship theory. A
relational database requires the implementation of a base relation (or base table) to
resolve many-to-many relationships. A base relation representing this kind of entity is
called, informally, an associative table.

DBMS Page 22
An associative entity (using Chen notation)As mentioned above, associative entities
are implemented in a database structure using associative tables, which are tables that
can contain references to columns from the same or different database tables within
the same database.
Attribute Classification
Attribute is used to describe the
properties of the entity. This
attribute can be broadly classified
based on value and structure.
Based on value the attribute can
be classified into single value,
multivalue, derived, and null
value attribute. Based on
structure, the attribute can be classified as simple and composite attribute
Symbols Used in ER Diagram
The elements in ER diagram are Entity, Attribute, and Relationship. The different
types of entities like strong, weak, and associative
entity, different types of attributes like multivalued and
derived attributes and identifying relationship and their
corresponding symbols are
Single Value Attribute
Single value attribute means, there is only one value
associated with that attribute.
Multivalued Attribute
In the case of multivalue attribute, more than one value
will be associated with that attribute.
Derived Attribute
The value of the derived attribute can be derived from the values of other related
attributes or entities. In ER diagram, the derived attribute is represented by dotted
ellipse
Null Value Attribute
In some cases, a particular entity may not have any applicable value for an attribute.
For such situation, a special value called null value is created.
Composite Attribute
Composite attribute is one which can be further subdivided into simple attributes.
Relationship Degree
Relationship degree refers to the number of associated entities. The relationship
degree can be broadly classified into unary, binary, and ternary relationship.
Unary Relationship
The unary relationship is otherwise known as recursive relationship. In the
unary relationship the number of associated entity is one. An entity related to
itself is known as recursive relationship.
Binary Relationship

DBMS Page 23
In a binary relationship, two entities are involved. Consider the example; each staff
will be assigned to a particular department. Here the two entities are STAFF and
DEPARTMENT.
Ternary Relationship
In a ternary relationship, three entities are simultaneously
involved. Ternary relationships are required when binary
relationships are not sufficient to accurately describe the
semantics of an association among three entities
Specialization and Generalization (or)
Characteristics of Super type/Subtypes
There are two processors “Specialization” and “Generalization” that serve as
mental models in developing super type / subtype relationships.
Generalization: In data
modeling “Generalization
is the process of defining a
more general entity types
from a set of more
specialized entity types”.
Thus generalization is a
bottom-up approach
process. The example of
generalization is as show
in the following figure.
The above figure represents three entity
types car, truck motorcycle. At this stage
data modeler intends to represents this
separately on E-R diagram however, on
close examination, we see that three entity
types have a no. of attributes is common
and they are vehicle-identifier, vehicle-
name, price and engine displacement.
This fact suggests that each of the three entity types is really a version a more
general entity type. This more general entity type vehicle, together with the resulting
supertype/subtype relationship is shown below.

DBMS Page 24
The entity CAR has the specific attribute no. of passengers, while truck has two
specific attributes capacity and cab-type. Thus, generalization has allowed us to group
entity types, along with their common attributes and at the same time preserve
specific attributes that are unique to each subtype.
The entry type motorcycle is not included in the relationship because it doesn’t satisfy
the subtype conditions.
Referring to the figure (d) you will notice that the only attributes of motorcycle are
those that are common to all vehicles, there are no attributes specific to motorcycles.
Motorcycle does not have a relationship to another entity type. Thus, there is no need
to create a motorcycle subtype. The fact that there is no motorcycle subtype
suggests that it must be possible to have an instance of vehicle that is not a member of
any of its subtypes.
b) Specialization: Specialization is “the process of defining one or more subtypes of
the supertype and forming supertype / subtype relationship”. Each subtype is formed
based on some distinguishing characteristic, such as attributes or relationships specific
to the subtype specialization is a top down process, direct reverse of generalization.
Fig. (b) Specialization to MANUFACTURED PART and PURCHASED
PART
The fig(a) shows an entity type
named PART together with its
attributes. The
identifier is part no and other
attributes include description,
unit-price, location,
Quantity_On_Hand, routing
number and supplier. Supplier a
multivolume attribute. Since
there may be more than one
supplier with associated unit
price for a part.
In discussion with users we discover that there are two possible sources for
parts some are manufactured internally, while other are purchased from outside
suppliers. Further, we discover that some parts of are obtained from both sources.
Some of the attributes of entity type in fig(a) apply to all parts regardless of
source. However, others depend on the source. Thus, routing-number applies only to

DBMS Page 25
manufactured parts. While, supplier-id and unit-price apply only to purchased parts.
Analyst suggested that they create a new relationship between purchased part and
supplier. This relationship (named supplies) allows users to more easily associated
purchased parts with their suppliers. The attribute unit-price is now associated with
the relationship supplies, so that the unit price for a part may vary from one supplier
to another. These factors suggest that part should be specialized defining the subtypes
manufactured part and purchased part as show in the fig (b).
Combining Generalization and Specialization
Specialization and Generalization are both valuable technique for developing
supertype/subtype relationships. Which technique we use at particular time depends
on several factors such as the nature of the problem domain, previous modeling
efforts and personal preference. We should be prepare to use both approaches and to
alternate back and forth as dictated by the proceeding factors.
Specifying constraints in Supertype/Subtype Relationships.
The specifying constraint in supertype/subtype relationship allows us to
capture some of the important business rules that apply to these relationships; these
two most important types of constraints are “completeness” and “disjointness
constraints”.
i) Specifying completeness constraints:
“A completeness constraint addresses the question whether an instance of a
supertype must also be a member of at least one subtype”.
The completeness constraints have two possible rules.
a. Total specialization rule.
b. Partial specialization rule.
a. Total Specialization Rule:- “The total specialization rule specifies that each entity
instance of the supertype must be a member of some subtype in the relationship”.

DBMS Page 26
This figure introduces the notation for total specialization. In this example, the
business rule is the following “A patient must be either an OUTPATIENT or
RESIDENT PATIENT” total specialization is indicated by the double line extending
from the patient entity type to the circle.
b) Partial Specialization Rule:- The partial specialization rule specifies that the
entity instance of the supertype is allowed not belong to any subtype.
If a vehicle is a CAR, it must appear as an instance of CAR and if it is a truck, it must
appear as an instance of truck. However, if the vehicle is a motorcycle, if cannot
appear as an instance of any subtype. It is an example of partial specialization and it is
specified by the single line from the vehicle, super type to the circle.

II) Specifying Disjoint ness constraints:


A disjoint ness constraint addresses the question whether an instance of a supertype
may simultaneously a member of two or more subtypes.
The disjoint ness constraints have two possible rules.
a. The disjoint rule and
b. The overlap rule
a. The disjoint rule:- The disjoint rule specified that if an entity instance (of the
supertype) is a member of one subtype. It can’t simultaneously be a member of any
other subtype.

DBMS Page 27
The business rule in this PATIENT example is the following
At any given time a PATEINT must be either an OUT PATIENT or a
RESIDENT PATIENT but cannot be both. This is the disjoint rule as specified by the
letter‘d’ in the circle joining the supertype and its subtypes.
b. Overlap rule: - The overlap rule specified that an entity instance can
simultaneously be a member of two or more subtype. The following figure shows an
example of overlap rule. Below figure shows the entity type “PART” with its two sub
types, “MANUFACTURED PART” and “PURCHASED PART”. Some parts are
both manufactured and purchased.
The overlap rule is specified by placing the letter ‘O’ the circle. Notice in the
figure that the total specialization rule is also specified as indicated by the double line.
Thus any part must be either or purchased part or a manufactured part or it may
simultaneously be both of these.

II) Specifying subtype discriminators:


A subtype discriminator is an attribute of the supertype, whose values
determine the target subtype or subtypes.

DBMS Page 28
a. Disjoint Subtypes:- An example of the use of a subtype discriminator is shown in
the following figure.
In the above figure, a new attribute “Employee - type” has been added to the
supertype to serve as subtype discriminator”. When a new employee is added to
supertype, this attribute is coded with one of three values as follows:
“H” – for hourly
“S” – for salaried
“C” – for consultant.

Depending on this code the instance is then assigned to the appropriate


subtype.
The notation we use to specify the subtype discriminator is also shown in the figure.
The expression “Employee-type” is placed next to the line leading from the supertype
to the circle. The value of the attribute that selects the appropriate subtype is placed
adjacent to the line leading to the subtype. Thus, for example to condition employee –
type = S, causes an entity instance to be inserted in to the SALARIED EMPLOYEE
subtype.
b. Overlaping Subtypes:- When subtypes overlap, a slightly modified approach must
be applied for the subtype discriminator. The reason is that a given instance of the
supertype may require that we create an instance in more than one subtype.
An example of this situation is shown in the following figure.

DBMS Page 29
The figure shows an entity PART and its overlapping subtypes. A new attributed
named part-type has been added to PART Part type is a composite attribute with
components manufactured? And purchased? Each of these attributes is a Boolean
Variable (i.e., it takes only the values yes “Y” and No “N”). When a new instance is
added to PART, these components are coded as follows.

Normalization
Normalization is a design technique that is widely used as a guide in
designing relational databases. Normalization is essentially a two step process that
puts data into tabular form by removing repeating groups and then removes duplicated
data from the relational tables.
Normalization theory is based on the concepts of normal forms. A relational table is
said to be a particular normal form if it satisfies certain set of constraints
Advantages of Normalization
 Avoids data modification (INSERT/DELETE/UPDATE) anomalies as each
data item lives in One place
 Greater flexibility in getting the expected data in atomic granular
 Normalization is conceptually cleaner and easier to maintain and change as
your needs change
 Fewer null values and less opportunity for inconsistency
 A better handle on database security
 Increased storage efficiency
 The normalization process helps maximize the use of clustered indexes, which
is the most powerful and useful type of index available. As more data is
separated into multiple tables because of normalization, the more clustered
indexes become available to help speed up data access

DBMS Page 30
Disadvantages
1. Requires much more CPU, memory, and I/O to process thus normalized data gives
reduced database performance
2. Requires more joins to get the desired result. A poorly-written query can bring the
database down
3. Maintenance overhead. The higher the level of normalization, the greater the
number of tables in the database.
Basic and Higher Normal forms:
Normal forms are classified into two main categories they are
1. Basic Normal Forms
2. Higher Normal Forms.
1) Basic Normal Forms:
The basic normal forms are
 First normal form
 Second normal form
 Third normal form
First Normal Form:
A relation is in a first normal form if it contains no multi-valued attribute.
For example the relation EMPLOYEE contains the attributes like Emp-Id,
Emp-Name, Sal, and gender. Here is no multi valued attribute. So the relation
EMPLOYEE is in first normal form.
EMPLOYEE
Emp-No Emp-Name Sal Gender
Second Normal Form (2NF):
A relation is in second normal form if it is in first normal form and every non-
key attribute is fully functionally dependent on the primary attribute. That means no
partial functional dependency.
If a relation is in second normal form if any one of the following conditions apply.
i. A relation contains only one primary key.
ii. No non-key attributes in the relation.
iii. Every non-key attribute is functionally dependent on the full set of
primary key attributes (fully functional dependency)
For example the relation EMPLOYEE contains the attributes like Emp-Id, Emp-
Name, course-Id, Sal, and Date-completed. In this example the primary key for this

DBMS Page 31
relation is composite key of Emp-Id, Course-Id. Here the relation employee is not in
second normal form because the non-key attribute Emp-Name, Sal are functionally
dependent on the part of the primary key (Emp-Id, Partial functional dependency). So
we decompose the relation EMPLOYEE into new relations EMPLOYEE.
EMPLOYEE
Emp-No Course-Id Emp-Name Sal Date-completed
Course-Id → Date-completed
Emp-Id→ Emp-Name
Emp-Id → Sal
EMPLOYEE
Emp-Id Emp-Name Sal
COURSE
Emp-Id Course_Id Date-completed

Third Normal Form (3NF):


A relation is in 3rd normal form if it is in second normal form and no transitive
dependency. A transitive dependency in a relation is a functional dependency between
two or more non-key attributes. For example consider the following relation SALEs.
SALES.
Cust-Id Cust-Name Salesperson-Id Region
In the above relation cust-Id is the primary key. So all of the remaining
attributes are functionally dependent on this attribute. However there is a transitive
dependency. The attribute region is functionally dependent the attributes salesperson-
Id. So we decompose the above relation into new relations that satisfy our 3 rd normal
form.
CUSTOMER
Cust-Id Cust-Name Salesperson-Id
SALES
Salesperson-Id Region
Advanced Normal Forms/Higher Normal Forms:
Advanced Normal Forms are
1. Boyce codd normal form (BCNF)
2. Fourth normal form
3. Fifth normal form

DBMS Page 32
1) Boyc/ Codd Normal Form:
A relation is in Boyce codd normal form if it is in third normal form and the
determinants are candidate keys. For example consider a relation STUDENT with
attributes like St.No, subject, Adviser.
In the above relation primary key is a composite key of St.No, subject. Here
two functional dependencies occur.
STUDENT
St-No Subject Adviser
St-No adviser
Subject Adviser
In the above second functional dependency determinant is adviser. It is not a
candidate key. So the above relation cannot follow Boyce codd normal form. So we
decompose the above relation into new relations.
STUDENT
St-No Adviser

ADVISER
Subject Adviser
2) Fourth Normal Form:
A relation is in fourth normal form if it is in Boyce codd normal form and no
multi valued dependency. Here multi-valued dependency is a functional dependency
that exists a non-key attribute is functionally dependent on two or more sets of
primary key attributes.
For example consider a relation student contains attributes like st-No, st-
Name, course-Id and grade. Here primary key is a composite key of st-No, st-Name,
course-Id. In the above example the non-key attribute grade is functionally dependent
on st-no, course-Id, and st-name, course-Id.
STUDENT
St-No St-name Course-Id Grade
St-No, course-Id grade
St-Name, course-Id grade
The above relation contains multi-valued dependency. So it is not in fourth
normal form. To avoid the multi-valued dependency we decompose the above
relations into new relations.

DBMS Page 33
St-No St-Name

St-No Course-Id Grade

3) Fifth Normal Form (5NF):- (Domain Normal Form) (Projection-join Normal


Form)
A relation is in fifth normal form if it is in fourth normal form and that
contains joined dependency. Here join-dependency means if a relation
contains minimum of 3 attributes and every attribute may functionally
dependent on the remaining attributes. For example consider a relation
CLASS with attributes like subject, teacher and text-book. Here primary key
is a composite key of subject, teacher, text-book. The above relation CLASS
is not in fifth normal form because it satisfies join-dependency. So we
decompose the above relation into new relations.
Subject Teacher Text-book

Subject, teacher --- text-book Subject Teacher

Text-book, subject --- teacher


Teacher Text-book

Text-book, teacher --- subject


Text-book Subject

Aggregation and Composition


Relationships among relationships are not supported by the ER model. Groups
of entities and relationships can be abstracted into higher level entities using
aggregation. Aggregation represents a “HAS-A” or “IS-PART-OF” relationship
between entity types. One entity type is the whole, the other is the part. Aggregation
allows us to indicate that a relationship set participates in another relationship set. The
car has various components like tires, doors, engine, seat, etc., which varies from one
car to another. Relationship drives is insufficient to model the complexity of this
system. Part of relationships allow abstraction into higher level entities. In this
example engine, tires, doors, and seats are aggregated into car.

DBMS Page 34
Composition is a stronger form of aggregation where the part cannot exist
without its containing whole entity type and the part can only be part of one entity
type. Consider the example of DEPARTMENT has PROJECT. Each project is
associated with a particular DEPARTMENT. There cannot be a PROJECT without
DEPARTMENT. Hence DEPARTMENT has PROJECT is an example of
composition.
Relationships within the relational data base/ Mapping cardinalities :
Mapping cardinalities (or) cardinality ratios express the number of entities to which
another entity can be associated via a relationship set. Mapping cardinalities are most
useful in describing binary relationship sets although occasionally they contribute to
the description of relationship sets that involve more than two entity sets.
For a binary relationship set R between entity sets A and B, the mapping
cardinality must be one of the following.
(i) One – to – One: An entity in A is associated with at most one entity in B; and an
entity in B is associated with at must one entity in A
A B

a b
1 1

a b
2 2

a b
3 3

Example: a One – to - One b


4 4

DBMS Page 35
Employee Parking Place
Is-assigned
One - to - One
The above example indicates that an employee is assigned one parking place,
and each parking place is assigned to one employee.
(ii)One – to – Many An entity in A is associated with any b1
number of entities in B. An entity in B, however can be a b2
associated with at most one entity in A. 1
b3
a b4
2
b5
a
3
One – to - Many
CUSTOMER ORDER
Submit

(iii) Many – to – One An entity in A is associated with at most one entity in B. An


entity in B however, can be associated with any number of entities in A.
A B
a1
b1
a2
b2
a3
b3
a4

a5

Many – to - One
Example:

PRODUCT Contains Product_Line

Many - to - One

The above example indicates that each product belongs to only one product
line and a product line may contain several products.
(iv) Many-to-Many An entity in A is associated with any number of entities in B and
an entity in B is associated with any number of entities in A.
a b
A1 1B

a b
2 2
DBMS Page 36
a b
a b
4 4

Many – to - Many
Example:
STUDENT Registers- Course
for

The above example shows that a student may register for more than one
course and that each course may have many student registrants.

Entity Relationship model constructs(ER Model)


(OR)
Data model basic building blocks
The basic constructs of the entity relationship model are entities, relationships
and attributes. The richness of the E-R Model allows designers to model real world
situations accurately and expressively, which helps account for the popularity of the
model.
Entity:
An entity is an object that may represents person, place, object, event or concept in
the user environment about which the organization wishes to maintain data.
Eg: Employee, Student, Store, warehouse, Machine, Registration, Account,
course.
Entity type versus Entity Instance:
Entity Type: An entity type “is a collection of entitles that share common properties
or characteristics”. Each type in an E-R model is given a name. Since the name
represents a collection of items, all it is always singular. We use capital letters for
names of entity types. In an E-R diagram the entity name is placed inside the box
representing the entity type.
Entity Instance: An entity instance “is a single occurrence of an entity type”. An
entity type is described just once (Using metadata) in database, while many instances
of that entity type may be represented by data stored in the databases.

DBMS Page 37
Strong Vs weak entity types:

Strong entity: An entity that exists independently of other entity type, then it is called
strong entity type or An entity set that has a primary key is termed as a strong entity
set. Strong entity is denoted by a symbol single lined Box.
Weak entity: An entity set may not have sufficient attributes to form a primary key
such entity set is termed as weak entity set (or) An entity type whose existence
depends on some other entity type is called weak entity type. weak entity type has no
meaning in the E- R diagram without the entity on which it depends. the entity type
on which the weak entity type depends is called “the identifying owner” (or) simply
called “owner” . Weak entity is denoted by a symbol double lined Box.

Identity Relationship : The relationship that associates the weak entity set with an
owner is the identifying relationship.
Attributes: property or characteristic of an entity type that is of interest to the
organization is called attribute. An attribute is denoted by a symbol ellipse.
Ex:
FACULTY

F_Nam
e M_Nam
e

L_Nam
F_Id Name
e

FACULTY Dob
Skill

Qualificatio
Age n

In above example F_Id,Name,Dob,Age,Skill Qualification are attributes of the


FACULTY entity.
Types of attributes :
1. Simple Vs Composite Attribute:
Simple attribute:

DBMS Page 38
A ‘Simple” or atomic attribute is an attribute that cannot be broken down into smaller
components. In above Example F_Id, Dob, Skill, Age, Qualificaton are Simple
attributes.
Composite attribute: A “composite” attribute is an attribute that can broken down
into component parts. In above Example Name is Composite attribute. Because it is
broken in to 3 parts(Components) namely F_Name, M_Name, and L_Name.
2. Single valued Vs Mutlivalued Attribute:
Single valued attribute :A “Single valued’ attribute is an attribute that takes only one
value for a given entity instance.
Eg : The F_Id attribute of an entity FACULTY takes only one value for each entity
instance.
Mutlivalued Attribute: A “multi valued” attribute is an attribute that may take
more than one value for a given entity instance. We indicate a multi valued attribute
with a double lined ellipse.

Ex: Consider a FACULTY entity set with the attribute Skill. Any particular faculty
may have Skill in more than one topic.
3. Null attributes: A null value is used when an entity does not have a value for an
attribute.
4. Stored Vs Derived Attributes :
Stored attribute: Some attribute values are calculated or derived from other
related attribute values that stored in the database.
Ex : In FACULTY entity type F_Id, Dob are stored attributes.
Derived Attribute: A “derived” attribute is an attribute whose values can be
calculated from related attribute values. We indicate a derived attribute in an E-R
Diagram by using an ellipse with a dashed line.
Ex : The FACULTY entity type has Age attribute. If the users need to know Age, that
value must be derived from the attribute Dob.
5. Identifier attribute or Primary Key: An identifier is an attribute that uniquely
identifies individual instances of an entity type. The identifier for the Faculty entity
type is F_Id. Each entity instance must have a single value for the attribute and the
attribute must be associated with entity. We underline identifiers name on the E-R
Diagram.
Primary Key: A Primary key is a set of one or more attributes that can uniquely
identify tuples within the relation.

DBMS Page 39
Composite identifier or Composite key attribute: A composite identifier is an
identifier that consists of a composite attribute.
The following figure shows the entity set flight with the composite identifier-
flight-id. The Flight-id composite attribute inturn has component attributes flight-no
and date. This combination is required to uniquely identify individual occurrences of
flight.

Flight-no date

No.of
Flight-id passengers

Primary key Flight

Relationships:
A relationship is an association among the instances of one (or) more entity
types i.e., of interest to the organization.
Eg : Consider the entity type employee and course where courses represents training
courses that may be taken by employees. To track courses that have been completed
by particular employees. We define a relationship called “Completes” between two
entity types as shown in the following figure.
Relationship type (Completes):

Course- Course-
id title
Employee Employee-
name
-id
Topic

Birthdate

Employee Comple Course


tes

Relationship instances:
Employee Course
Raju C++
Kiran Java

DBMS Page 40
Suman COBOL
Hema C
This is a many-To- many relationship since each employee may complete any
no. of course, while a given course may be completed by any no. of employees.
1. Associative Entities : An associative entity is an entity type that associates
the instances of one or more entity types and contains attributes that are
peculiar to the relationships between those entity instances,
In the E-R model associative entities are represented with the diamond
relationship symbol enclosed within entity box. The purpose of this symbol is
to preserve the information that the entity was initially specified as a
relationship on E-R Model.
An associative entity (Certificate):”
Employe Employee- Certificate-
e-id name DOC Cours
Number
e -id Course -
Title

EMPLOYEE CERTIFIC Course


ATE

Figure (b) shows the relationship “completes” converted to an associative


entity type. In this case the training department for the company has decided to award
a certificate to each employee who completes a course. Thus, the entity is named
certificate which certainly has independent meaning to end users. Each certificate has
a number that serves as a identifier. The attribute date completed is also included.
Constraint:
A constraint is a restriction placed on the data. Constraints are important because they
help to ensure data integrity. Constraints are normally expressed in the form of rules.

Different Keys:
Keys: It is important to be able to specify how rows in a relation are distinguished
conceptually, rows are distinct from one another, but from a database perspective the

DBMS Page 41
difference among them must be expressed in terms of their attributes. Keys come here
for a rescue.
Primary key: A primary key is a set of one (or) more attributes that can uniquely
identify tuple within the relation.
Ex: In our sample database, sup # is the primary key for supplier’s relation (table) as
it contains unique value for each tuple in the relation.
Composite Primary Key: In some tables, combination of more than one attribute
provides a unique value for each row. In such tables, the group of these attributes is
declared as primary key. In such cases, the primary key consists of more than one
attribute; it is called composite-primary-key.
Ex: Supp # and item # is the primary key for the shipments relation (table).
Candidate Key: All attribute combinations inside a relation that can serve as primary
key are candidate keys as they are candidates for the primary key position.
Ex: In our sample database, there are two candidate keys supp # and sup-name in the
suppliers relation. Both of these attributes contain unique values for each tuple.
Super Key
A super key is a column (or) set of columns that uniquely identifies a row
within a table.
Ex:
Given table : Employees { employee-id, first-name, sur-name, sal }
Possible super keys are :
{ Employee_Id}
{ Employee_Id, First_Name }
{ Employee_Id, First_Name, Surname }
{ Employee_Id, First_Name, Surname, Sal }
Secondary Key: It is defined as a key that is used strictly for data retrieval purposes.
Ex: Suppose customer data are stored in a CUSTOMER table in which the
customer number is the primary key. Suppose, that some of the customers forget their
number? Data retrieval for a customer can be facilitated when the customer’s last
name and phone number are used. In that case, the primary key is the customer
number, the secondary key is the combination of the customer’s last name and phone
number.
Foreign Key: A non-key attribute, whose values are derived from the primary key of
some other table, is known as foreign-key in its current table.
SUPPLIER

DBMS Page 42
Supp # Supp-Name Status city
S1 Britannia 10 Delhi
S2 New-Bakers 30 Mumbai
S3 Mother Dairy 10 Delhi
S4 Cockz 50 Bangalore
S5 Haldiram 40 Jaipur
SHIPMENT
Supp # Item # Qty-supplied
S1 12 10
S1 13 20
S1 16 20
S2 14 20
S2 15 10
S3 11 10
S3 17 10
S4 18 30
S5 19 30

Data dictionary and System catalog


Data Dictionary:
An integral part of RDBMS is the data dictionary which stores Meta
data, (or) information about the database, including attribute names and definitions for
each table in the database. The data dictionary is usually a part of the system catalog
that is generated for each database.
The system catalog describes all database objects, including table-
related data such as table names, table creators (or) owners, column names and data
types, foreign keys and primary keys, index files, authorized users, user access
privileges and so forth. The system catalog is created by the DBMS and the
information is stored in system tables, which may be queried in the same manner as
any other data table, if the user has sufficient access privileges.
The system catalog automatically produces database documentation. As new
tables are added to the database, that documentation also allows the RDBMS to check
for and eliminate homonyms and synonyms.
Homonyms are similar-sounding words with different meanings, such
as boar and bore (or) identically spelled words with different meanings such as fair
( meaning “just”) and fair (meaning “festival”).

DBMS Page 43
In a database context, the word homonym indicates the use of the
same attribute name to label different attributes. To lesser confusion, you should
avoid database homonyms, the data dictionary is very useful in this regard.
A synonym is the opposite of a homonym and indicates the use of different
names to describe the same attribute. For ex, can and auto refer to the same object.
Synonyms must be avoided.
Integrity constraints
Integrity Rules:
Relational database integrity rules are very important to good database design.
Many RDBMSs enforce integrity rules automatically. However, it is much safer to
make sure that your application design conforms to the entity and referential integrity
rules.
Entity Integrity:
All primary key entries are unique, and no part of a primary key may be null. Each
row will have a unique identity, and foreign key values can properly reference
primary key values.
Referential Integrity:
A foreign key may have either a null entry, as long as it is not a part of its tables
primary key, or an entry that matches the primary key value in a table to which it is
related. (Every non-null foreign key value must reference an existing primary key
value.)
Integrity Constraints: The relational data model includes several types of integrity
constraints. The purpose of integrity constraints is to implement the business rules in
the database. In relational data model several types of integrity constraints are
1. Domain Integrity Constraints:
A domain is a set of values that may be assigned to an attribute. All of the
values that may appear in a column of a table must be taken from the same domain. A
domain consists of values like column name, data type, size and allowable values.
Domain integrity constraints are 1) Not Null and 2) Check. The Not Null constraint is
used to avoid null values. The check constraint is used to specify a condition for an
attribute. In relational data model NULL values is not equal to zero or Null strings.
Here one null value is not equal to another null value.
2. Entity Integrity Constraints:

DBMS Page 44
Mainly Entity integrity constraints are two types. They are (i) Primary key and
(ii) Unique:
Every primary key attribute is non-null and contains unique values. In some
cases a particular attribute cannot be assigned a data value. These are two situations.
Where this is likely to occur either there is no applicable data value (or) the applicable
data value is not known. In this case we use the entity integrity constraint unique.
3. Referential Integrity Constraints:
In the relational data model association between the tables are defined with the
help of Referential integrity constraints (foreign key). For example the association
between the CUSTOMER and ORDER tables is identified by including the customer-
Id attribute as foreign key in ORDER table.

CUSTOMER
Customer-Id Cust-Name Add
Primary key
ORDER
Order-Id Order description Customer-Id

Foreign key
A referential integrity constraint is a rule that maintains consistency among the
rows of two relations. The says that if there is a foreign key in one relation, the
foreign key values must match the primary key values in another relation.

Logical view of Data


Logical view of data: A collection of interrelated files and a set of programs that
allow users to access and modify these files is known as a database management
system.
The database stores and manages both data and meta data. The DBMS
manages and controls access to the data and the database structure. Such an
arrangement i.e; placing the DBMS between the application and the database,
eliminates most of the file system’s internet limitations.
The relational data model allows the designer to focus on the logical
representation of the data and its relationships, rather than on physical storage details.
The relational model enables you to view data logically rather than physically.

DBMS Page 45
The use of a table, how the advantages of structural and data independence. A
table does resemble a file from a conceptual point of view. Because you can think of
related records as being stored in independent tables, the relational data base model is
much easier to understand than the hierarchical and network models. Logical
simplicity tends to yield simple and effective database design methodologies. The
table plays such a prominent vole in the relational model.
Tables and their characteristics
The logical view of the relational database is facilitated by the creation of data
relationships based on a logical construct known as a relation. Because a relation is a
mathematical construct, end-users find it much easier to think of a relation as a table.
A table is perceived as a two-dimensional structure composed of rows and columns. A
table is also called a relation because the relational model’s creator, E.F. Codd, used
the term relation as a synonym for table.
Characteristics of a Relational Table
1. A table is perceived as a two-dimensional structure composed of rows and
columns.
2. Each table row (tuple) represents a single entity occurrence within the
entity set.
3. Each table column represents an attribute, and each column has a distinct
name.
4. Each row/column intersection represents a single data value.
5. All values in a column must conform to the same data format.
6. Each column has a specific range of values known as the attribute
domain.
7. The order of the rows and columns is immaterial to the DBMS.
8. Each table must have an attribute or a combination of attributes that
uniquely identifies each row.

Relational set operators


The relational algebra is a collection of operations on relations. Each operation
takes one (or) more relations as its operand (s) and produces another relation as its
result. Relational algebra defines the theoretical way of manipulating table contents
using the eight relational operators. The operations defined in relational algebra

DBMS Page 46
include select, project, Cartesian product, union, set difference, set intersection,
natural join, division e.t.c; The select and project are unary operations since they
operate on one relations.
1. The select operation
The select operation selects tuples (horizontal subset) from a relation that
satisfy a given predicate (i.e.: a given condition). The selection is denoted by s
(sigma). Ex: To select those tuples from Items relation where the price is more than
14.00, we shall write
price > 14.00 (items)
ITEM ITEM
Item # Items-Name Price Item # Item-Name price
I1 Milk 15.00 I1 Milk 15.00
I2 Cake 5.00 I7 Ice cream 16.00
I4 Milk bread 14.00 I9 Namkeen 15.00
I5 Plain biscuit 6.00
I6 Cream biscuit 10.00 Fig (b)
I7 Ice cream 16.00 Fig (a)
I8 Namkeen 15.00 The relation that results from the above
query is as shown in fig (b)
2. The project operation
The project operation yields a “vertical” subset of a given relation. The projection lets
you select specified attributes in a specified order. Projection is denoted by Ù (Pi)
Ex: To project supplier names and their cities from the relation suppliers, we shall
write Ù Supp-Name, city (suppliers)
The relation resulting from this query is as shown in fig (b)
SUPPLIER
Supp # Supp-Name Status city
S1 Britannia 10 Delhi
S2 New Bakers 30 Mumbai
S3 Mother Dairy 10 Delhi
S4 Cookz 50 Bangalore
S5 Haldiram 40 jaipur
Fig (a)
SUPPLIER

DBMS Page 47
Supp-Name City
Britannia Delhi
New Bakers Mumbai
Mother dairy Delhi
Cookz Bangalore
Haldiram jaipur

Fig (b)
3. The Cartesian product operation
The Cartesian product is a binary operation and is denoted by a cross (X). The
Cartesian product of two relation A and B is written as A x B. The Cartesian product
yields a new relation which has a degree (number of attributes) equal to the sum of the
degrees of the two relations. Operated upon. The Cartesian product of two relations
yields a relation with all possible combinations of the tuples of the two relations
operated upon. Let us consider how does it work let us assume there are two relations
student and Instructor
STUDENT INSTUUCTOR
Stud # Stud-Name Hosteler
INST# INST-Name subject
S001 Meenakshi Y
101 K.Lal English
S002 Radhika N
102 R.L.Arora Maths
S003 Abhinav N
The resulting relation has been shown in
below figure student x Instructor

The resulting relation contains all possible combinations of tuples of the two relations.
STUDENT_INSTUUCTOR
Stud # Stud-Name Hosteler INST# INST-Name Subject
S001 Meenakshi Y 101 K.Lal English
S001 Meenakshi Y 102 R.L.Arora Maths
S002 Radhika N 101 K.Lal English
S002 Radhika N 102 R.L.Arora Maths
S003 Abhinav N 101 K.Lal English
S003 abhinav N 102 R.L.Arora Maths

4. The union operation


The union operation is a binary operation that requires two relations as its
operands. It produces a third relation that contains tuples from both the operand

DBMS Page 48
relations. The union operation is denoted by U. To denote the union of two relations
X and Y we will write X U Y
One thing must be remembered about union that is both the operand relations
must be union-compatible. For a union operation A U B to be valid, the following two
conditions must be satisfied by the two operands A and B.
1. The relations A and B must be of the same degree. That is, they must have the
same number of attributes.
2. The domains of the ith attributes of A and the ith attribute of B must be the
same.
A B

AUB
consider that we have following two relations Drama and Song, then the result
of SONG U DRAMA will be as shown in Fig (c)
DRAMA SONG
Roll No. Name Age
2 Manya 15
10 Rishabh 15
13 Kush 15

Result of SONG V DRAMA will be


Roll No. Name Age
2 Manya 15
10 Rishabh 15
13 Kush 15
17 Swathi 14

DBMS Page 49
Fig (c)
In the result an relation, all the duplicating tuples will be automatically removed.
5. The set Difference operation
The set difference operation, denoted by-(minus) allows us to find tuples that
are in one relation but not in another. The expression A-B results in a relation
containing those tuples in A but not in B.

DRAMA SONG A B
Roll No. Name Age
2 Manya 15
10 Rishabh 15
13 Kush 15

Result of DRAMA_SONG will be


Roll No. Name Age
17 Swathi 14
6. The set Intersection operation
The set intersection operation finds tuples that are common to the two operand
relations. The set intersection operation is denoted by Ç. The A Ç B will yield a
relation having tuples common to A and B.
DRAMA SONG A B
Roll No. Name Age
2 Manya 15
10 Rishabh 15
13 Kush 15
AÇB

Result of DRAMA Ç SONG will be


Roll No. Name Age
13 Kush 15
7. The join operation
The join operation joins two relations to form a new relation on the basis of
one common column the two operand relations have. That is, if two tables each have a
column defined over some common domain, they may be joined over those two

DBMS Page 50
columns, the result of the join is a new, wider table in which each row is formed by
concatenating two rows, one from each of the original tables, such that the two rows
have the same value in those two columns.
Ex: If we have a relation suppliers and another relation say clients as shown below.

SUPPLIER CLIENT

Client # Client-Name C city


C101 ABC Co. Delhi
C102 XYZ Co. Jaipur
ow, if tables suppliers and clients are joined over
C104 ZIGS Co. jaipur
city columns, the result will be as shown.
SUPPLIER_CLIENT
Supp # Supp-Name Status City Client # Client-Name C City
S1 Britannia 10 Delhi C101 ABC Co. Delhi
S3 Mother 10 Delhi C101 ABC Co. Delhi
S5 Dairy 40 Jaipur C102 XYZ Co. Jaipur
S5 Haldiram 40 Jaipur C104 ZIGS Co. Jaipur
8. Division Operation: The DIVIDE operation uses one single-column table (i.e.
column “a”) as the divisor and one 2-column table (i.e. columns “a” and “b”) as the
dividend. The tables must have a common column (i.e. column “a”.) The output of the
DIVIDE operation is a single column with the values of column “a” from the dividend
table rows where the value of the common column (i.e. column “a”) in both tables
match.

E.F. CODD’S RELATIONAL DATABASE RULES


In 1985, Dr.E.F.Codd published a list of 12 rules to define a relational
database system. The reason Dr.Codd published the list was his concern that many
vendors were marketing products as “relational” even though those products did not
meet the minimum relational standards. Dr.Codd’s list below serves as a frame of
reference for what a truly relational database should be.
1. Information Representation: All information in a relational database must be
logically represented as column values in rows within tables.
2. Guaranted Access: Every value in a table is guaranteed to be accessible through a
combination of table name, primary key value, and column name.

DBMS Page 51
3. Systematic Treatment of Nulls: Nulls must be represented and treated in a
systematic way, independent of data type.
4. Dynamic On-Line Catalog Based on the Relational Model: The metadata must
be stored and managed as ordinary data, that is, in tables within the database. Such
data must be available to authorized users using the relational database relational
language.
5. Comprehensive Data Sublanguage: The relational database may support many
languages. However, it must support one well defined, declarative language.
However, it must support one well defined, declarative language with support for data
definition, view definition, data manipulation (interactive and by program), integrity
constraints, authorization, and transaction management (begin, commit, and rollback).
6. View Updating: Any view that is theoretically updatable must be updatable
through the system.
7. High-Level Insert, Update and Delete: The database must support set-level
inserts, updates, and deletes.
8. Physical Data Independence: Application programs and ad hoc facilities are
logically unaffected when physical access methods or storage structures are changed.
9. Logical Data Independence: Application programs and hoc facilities are logically
unaffected when changes are made to the table structures that preserve the original
table values (changing order of column or inserting columns.)
10. Integrity Independence: All relational integrity constraints must be definable in
the relational language and stored in the system catalog, not at the application level.
11. Distribution Independence: The end users and application programs are unaware
and unaffected by the data location (distributed vs. local databases).
12. Nonsubversion: If the system supports low-level access to the data, there must
not be a way to bypass the integrity rules of the database.
13. Rule Zero: All preceding rules are based on the notion that in order for a database
to be considered relational, it must use its relational facilities exclusively to manage
the database.

DBMS Page 52
UNIT-IV

SQL and its features and advantages


SQL stands for Structured Query Language , it allows us to create a database
and table structures ,to perform basic data management tasks(add, update and delete)
and to perform complex queries designed to transform the raw data into useful
information . Moreover its command structure and syntax that are very easy to learn.
SQL is the real standard language used to manipulate and retrieve data from these
relational databases. SQL enables a programmer or database administrator to do the
following
-> Modify a database’s structure

DBMS Page 53
-> Change system security settings
-> Add user permissions on databases or tables
-> Revoke user permissions on databases or tables
-> Query a database for information
-> Update the contents of a database

Features of SQL
1. SQL can be used by a range of users, including those with little or no
programming experience.
2. It is a non procedural language.
3. It reduces the amount of time required for creating and maintaining
systems.
4. It is an English like language.

table
s
sequenc
es
views
Databa
se
indexe
synonym s
s

Advantages of SQL
Reduced training costs: Training in an organization can concentrate on one
language. A large number of professional trained in a common language reduces
retraining when hiring new employee.
Productivity: Professional can learn SQL thoroughly and become proficient with it
from continued use. The company can invest more to help professional become more
productive.
Application Portability: Application can moved from machine to machine when
each machine uses SQL. Also it is economical for the computer software industry to
develop off the self application software when there is a standard language.
Application Longevity: a standard language tends to remain so for a long time ,
hence there will be little pressure to rewrite old application . rather application will be
simply be updated as the standard language is enhanced or new versions of DBMSs
are introduced.

DBMS Page 54
Reduced dependence on a single vendor: when a non proprietary language is used ,
it is easier to use different vendors for the DBMS , training and educational services ,
application software etc.
Cross System Communication: different DBMSs application program can more
easily communicate and cooperate in managing data and processing user programs .
DDL commands
SQL includes commands to create database objects such as tables, indexes and
views as well as commands to define access rights to those database objects. The SQL
DDL provides commands for defining relation schemas, deleting relations , modifying
relation schemas The data definition commands are as follows.

CREATE: This command is used to create database objects like tables, views,
indexes, sequences etc.
Syntax:
create table tablename(col1 datatype(size),col2 datatype(size)…);
create view viewname as select query;
ex:
create table emp(eno number(4),name varchar2(10),sal number(8,2));
create view empview as select * from emp;

ALTER:
Alter command is used to modifying the structure of the table. we can alter an
existing table by adding one or more columns. Occasionally you might want to
modify a table by deleting a column.
Syntax:
alter table tablename add col datatype(size);
alter table tablename drop colname;
Ex:
alter table emp add hra number(8,2);
alter table emp drop hra;
DROP:
This command is used to delete the database object like table, view, index
sequence etc.. from the database permanently.
Syntax:

DBMS Page 55
drop table tablename;
drop view viewname;
Ex:
drop table emp;
drop view empview;
TRUNCATE:
This command is used to delete a table from the database but only difference
between drop and truncate is drop command delete the values along with structure but
truncate command deletes only values but not the structure . we can access the deleted
table using rollback if it is deleted by truncate . It is not possible by drop.
Syntax:
truncate table tablename;
Ex: truncate table emp;
RENAME:
It is used to change the name of the table from one name to another.
Syntax:
rename oldname to newname;
Ex: rename employee to emp;

CREATE DATABASE:
When we create a new database the RDBMS creates the physical files that will
hold the database. when we create a new database the RDBMS automatically create
the data dictionary tables to store the metadata.
Syntax:
create database databasename;
Ex: create database Bsc;
Database Schema:
A schema is a group of database objects such as tables and indexes that are
related to each other. Usually , the schema belongs to a single user or application. A
single database can hold schemas belonging to different users or schemas. It can be
considered as a logical grouping of database objects such as tables, views and
indexes.
Syntax:
create schema authorization{creator};

DBMS Page 56
Ex:
create schema authorization bsc;
DML commands
Data manipulation language (DML) statements are used for managing data
within schema objects. The basic SQL data manipulation commands are as follows
 insert
 select
 commit
 update
 rollback
 delete

Insert
This command is used to enter data into a table. The insert command basic
syntax as follows
Syntax:
Insert into tablename values(val1,val2,val3…);
The SQL insert into clause has actually two parts, the first specifying the table we are
inserting into and giving the list of columns we are inserting values for, and the
second specifying the values inserted in the column list from the first part. While
inserting a row , if you are adding value for all the columns of the table you need not
specify the columns name in the sql query. But you need to make sure the order of the
values is in the same order as the columns in the table. The sql insert query will be as
follows.
Ex: insert into student values(111,’rama’,’bsc’,87,78,93);
Select
The most commonly used SQL command is select command. The SQL select
command is used to retrieve data from database object like table or view in the
database.
Syntax :
Select columnlist from table_name;
The columnlist represents one or more attributes, separated by commas.
Syntax:

DBMS Page 57
Select <col list>from<table_name>[where clause][group by clause][having
clause][order by clause]
 table_name is the name of the table from which the information is retrieved.
 Col list includes one or more columns from which data is retrieved.
 Code with in the brackets is optional.
We could use the *(asterisk) as a wildcard character to list all attributes. A wild
character is a symbol that can be used as a general substitute for other characters or
commands.
Ex:
select * from student;
commit:
Any changes made to the table contents are not saved on disk until you close
the database, close the program you are using, or use the commit command. If the
database is open and a power outage or some other interruption occurs before you
issue the commit command, your changes will be lost and only the original table
contents will be retained.
Syntax:
Commit[work];
Ex: commit;
Update
Update command is used to modify data in a table.
Syntax :
Update <table_name>set col1=val1,col2=val2…[where conditionlist];
If you don’t specify a where condition, the update command will apply the changes to
all rows in the specified table. Confirm the corrections by using select command.
Ex
Update student set total=m1+m2+m3;
Update emp set sal=sal+sal*0.2 where sal<10000;
Rollback
If you have not yet used the commit command to store the changes
permanently in the database, you can restore the database to its previous condition
with the rollback command. Rollback undoes any changes since the last commit
command and brings the data back to the values that existed before the changes were
made.

DBMS Page 58
Syntax:
Rollback;
Delete
Delete command is used to delete rows from atable.
Syntax:
Delete from table_name [where condition_list];
The delete command is a set oriented command. And the where condition is optional .
therefore , if you do not specify a where condition , all rows from the specified table
will be deleted.
Ex:
Delete from student where sno=111;
Delete from student;
Data types available in SQL
SQL data takes shape in several different forms, including character strings,
numbers, file stores and dates. SQL developers call the shots as to what types of data
will be stored inside each and every table column when creating a SQL table. The
developer must specify the column type of each new SQL table column.

Data types

Character Number Date & Time


Long

Char Integer Date


BLOB
Varchar2 Float Time
CLOB
Nchar
NCLOB
Nvarchar2

Character Data Types

DBMS Page 59
The character data types store alphanumeric data in strings, with byte values
corresponding to the character encoding scheme, generally called a character set or
code page.
Char Data type
The char data type stores fixed length character strings. When you create a table with
a char column, you must specify a string length between 1 and 2000 bytes for the char
column width. The default is 1 byte.
Varchar and varchar2 Data types
The varchar2 data type stores variable length character strings. When you create a
table with a varchar2 column, you specify a maximum string length(in bytes or
characters) between 1 and 4000 bytes for the varchar2 column.

Nchar and Nvarchar2 Data type


Nchar and nvarchar2 are Unicode data types that store Unicode character data. The
character set of Nchar and Nvarchar2 data types can only be either AL16UTF16 or
UTF8 and is specified at database creation time as the national character set .
AL16UTF16 and UTF8 are both Unicode encoding.
 the Nchar data type stores fixed-length character strings that correspond to the
national character set.
 The Nvarchar2 data type stores variable length character strings .
 When you create a table with an NCHAR and NVARCHAR2 column, the
maximum size specified is always in character length semantics. Character
length semantics is the default and only length semantics for NCHAR and
NVARCHAR2.
Number Datatype
The NUMBER datatype stores fixed and floating point numbers. Numbers of virtually
any magnitude can be stored and are guaranteed portable among different systems
operating database , up to 38 digits of precision.
The following numbers can be stored in a NUMBER column.
 Positive numbers.
 Negative numbers.
 Zero
 Positive and negative infinity.
Date Datatype

DBMS Page 60
The DATE data type stores point in time values(dates and times) in a table. The Date
data type stores the year, the month, the day, the hours, the minutes, and the seconds.
BLOB datatype(Binary Large Object)
The BLOB datatype stores unstructured binary data in the database . BLOBs can store
up to 128 TB of binary data.
BLOBS participate fully in transactions . changes made to a BLOB value by the
DBMS_LOB package,PL/SQL, or the OCI can be committed or rolled back.
LONG datatype
The LONG data type stores variable length character strings. When you create a table
with a LONG column, you specify a maximum string length(in bytes or characters)
between 1 byte and 4 GB for the LONG column. Maximum one per table.
Select query/Select Statement:
The most commonly used SQL command is select command. The SQL select
statement is used to query or retrieve data from a table in the database. A query may
retrieve information from from specified columns or from all of the columns in the
table.
Syntax:
Select column_list from tablelist
[where conditionlist]
[group by clause]
[having clause]
[order by clause]
The code within the brackets is optional
From: identifies the tables or views from which columns will be chosen to appear in
the result table, and includes the tables or views needed to join tables to process the
query.
Where: Includes the conditions for row selection within a single table or view , and
the conditions between tables or views for joining.
Group by: this clause is used along with the group functions to retrieve data grouped
according to one or more columns.
Having: it is used to filter data based on the group functions.
Order by: It is used to sort results either in ascending or descending order.
Ex: select * from student where total>450;

SQL Operators:

DBMS Page 61
There are two types of operators, namely comparison operators and logical
operators. These operators are mainly used in the where clause, having clause to filter
the data to be selected.
Comparison operators: these operators are used to compare the column data
with specific values in a condition.
Symbol Meaning
= Equal to
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
<> or != Not equal to

Logical Operators:
SQL allows you to have multiple conditions in a query through the use of
logical operators. The logical operators are AND, OR and NOT.
Operator description
AND for a row to be selected all the specified conditions must be true.
OR for a row to be selected at least one of the conditions must be true.
NOT for a row to be selected the specified condition must be false.
SQL comparison keywords :
There are other comparison keywords available in SQL which are used to
enhance the search capabilities of a SQL query. They are ‘IN’, ‘BETWEEN’, ‘IS
NULL’, ‘LIKE’.

IN used to check whether an attribute value matches any value


with in a value list.

BETWEEN used to check whether an attribute value is with in a range.

LIKE used to check whether an attribute value matches a given string


pattern

IS NULL used to check whether an attribute value is null.

EXISTS used to check whether a sub query returns any rows.

DBMS Page 62
Alter command (advanced DDL command):
All changes in the table structure are made by using the alter table command,
followed by a keyword that produces the specific change you want to make. Three
options are available ADD, MODIFY and DROP. We can use ADD to add a column ,
MODIFY to change column characteristics , and DROP to delete a column from a
table.
Syntax:
alter table <tablename>{add|modify}(colname datatype[{add|modify}colname
datatype]);

alter table <tablename>add (column datatype(size));


alter table <tablename>modify(colname new_datatype(size));
alter table <tablename>drop column colname;
Ex:
alter table student add(total number(4));
alter table student modify(sno varchar2(6));
alter table student drop column address;

The alter table command can also be used to add table constraints. In those cases
syntax
alter table <tablename>add constraint[add constraint];
Ex:
alter table student add primary key(sno);
We could also use the alter table command to remove a column or table constraint .
Syntax:
alter table <tablename>drop{primary key |column columnname|constraint
constraintname};
Ex:
alter table student drop primarykey;
Note: when removing a constraint we need to specify the name given to the
constraint.
Functions available in SQL

DBMS Page 63
Functions in SQL enable you to perform calculations such as determining the
sum of a column or converting all the characters of a string to uppercase or
lowercase . types of functions available in SQL as follows.
 Aggregate functions
 Date and Time functions
 Numeric functions
 String functions
 Conversion functions

Aggregate functions
aggregate functions are also called as group functions. They return a value
based on the values in a column.
COUNT
The count function is used to tally the number of non null values of an
attribute. that means it returns the number of rows in the table that satisfies the
condition specified in the where clause. If the where condition is not specified then
the query returns the total number of rows in the table.

Syntax: select count(colname) from <table name>


Ex: select count(sno) from student;
If we specify the col name then count ignore nulls. If we specify the asterisk
(*), this function returns all rows, including duplicates and nulls. COUNT never
return null.
Ex:
Select count(*) from student;
SUM
It computes the total sum for any specified attribute, using whatever
condition(s) we have imposed.
Ex:
Select sum(sal) as total_sal from emp;
AVG

It is used to get the average value of a numeric column.


Syntax: select avg(colname) from <table name>

DBMS Page 64
Ex:
Select avg(sal) from emp;
MAX and MIN
This functions are used to find maximum and minimum values from a column.
Syntax:
Select max(colname) from tablename;
Select min(colname) from tablename;
Ex:
Select max(sal) from emp;
Select min(sal ) from emp;
Date and Time functions
SQL supports different date and time functions for its manipulation. All date
functions take one parameter (date or character datatype)and return a value(character,
numeric, data type);
ADD_MONTHS
This function is used to add number of months to a specified date.
Syntax:
add_months(date_value,n);
n-number of months.
Ex: if exams have been postponed for 4 months , then the query for view next date
will be
Select exam, exam_date, add_months(exam_date,4) from student;
LAST_DAY
This function is used to return the date of the last day of the month given in a
day or last day of a specified month .
Syntax: LAST_DAY(date_value);
Ex:
Select dob, last_day(dob) from student;
MONTHS_BETWEEN
If we want to know how many months fall between month M1 and month M2
we can use MONTHS_BETWEEN function.
Syntax : MONTHS_BETWEEN(M1,M2);
Ex:
Select copen, cclose, months_between(copen,cclose)as academic from college;
Copen- college open date, cclose- college closing date

DBMS Page 65
NEXT_DAY
This function finds the name of the first day of the week that is equal to or
later than another specified date.
Ex: select dob, next_day(dob) from student;
SYSDATE
It returns current system date and time
Numeric Functions: Numeric functions can be grouped in many different
ways such as algebraic, trigonometric, and logarithmic. Numeric functions take one
numeric parameter and return one value.
ABS
The ABS function returns the absolute value of a number you point to.
Syntax: ABS(numeric_value);
Ex: select abs(-1.9) as absolute from dual;
ROUND
It rounds a value to a specified precision
Syntax: ROUND(num_val)
Ex: select eno, name, round(sal,0) from emp;
CEIL and FLOOR
Ceil returns the smallest integer greater than or equal to its argument. Floor
does just the reverse, returns the largest integer equal to or less than its argument .
Syntax: CEIL(num_val), FLOOR(num_val)
Ex: select avg_marks, ceil(avg_marks), floor(avg_marks) from marks;
POWER
We can use power function to raise one number to the power of another. In
this function the first num is raised to the power of the second.
Select x,y,power(x,y) from dual;
SQRT
The function sqrt returns the square root of the given number. You can not use
this function for negative numbers, because the square root of a negative number is
undefined.
Select x, sqrt(x) from dual;
String Functions
SQL provides many functions to manipulate characters and strings.
CHR

DBMS Page 66
It returns the character equivalent of the number it uses as an argument. The
character it returns depends on the character set of the database. For this example the
database is set to ASCII. The column sno includes numbers.
Select sno, chr(sno) from characters;
CONCAT
The || symbol splices two strings together , as does concat.
Select concat(fname,lname) from dual;
INITCAP
It capitalizes the first letter of a word and makes all other characters
lowercase.
Select sname, initcap(sname) from student;
UPPER and LOWER
Upper returns a string in all capital letters and lower returns a string in all
lowercase letters.
Select upper(sname) from emp;
Select lower(sname) from emp;
SUBSTR
It returns a substring or part of a given string parameter .
Syntax : substr(str_val,p,l);
In the above syntax the first argument is the string value , the second
argument is the position of the first character to be output and third argument
is the number of characters to be select.
LENGTH
It returns the number of characters in a string value.
Syntax: length(string);
Ex: select ename, length(ename) from emp;
Conversion Functions:
TO_CHAR
This function is used to convert a number into character.
Syntax: TO_CHAR(numeric_val,format)
TO_NUMBER
Returns a formatted number from a character string , using a given format.
Syntax: TO_NUMBER(char_val,format)

DBMS Page 67
Virtual tables or Views in SQL
A view is a virtual table, which is based on select query. The query can
contain columns, computed columns, aliases, aggregate functions from one or more
tables. The views data is generated dynamically when the view is refreshed. We can
create a view by using the CREATE VIEW command.
Syntax:
Create view <view_name>as select query
Create view <view_name>as <col_list>from<table_name>[where condition];
Ex:
Create view empview as select * from emp where sal>10000;
Advantages:
Security:
Views provide a level of security in the database because the view can restrict
users to only specified columns and specified rows in a table. A user can be permitted
to access the database, only through a small set of views that contain the specific data
the user is authorized to see.

Query simplicity:
A view can draw data from several different tables and present it as single
table, thus effectively turning multi table queries into single table queries.

Structural simplicity:
Views can give a user , a personalized view of the database structure ,
presenting the database as a set of virtual tables that make sense to the user.

Data integrity:
if data is accessed and entered through a view , the DBMS can automatically
check the data to ensure that it meets specified integrity constraints.

Disadvantages:

Performance:
the DBMS translates the queries against the view into queries against the
underlying source tables. If a view is defined by a multi table query, then even a
simple query against view becomes a complicated join and it may take a long time to
complete.

Update restrictions:
When a user tries to update rows of a view, the DBMS must translate the
request into an update on rows of the underlying source tables. This is possible for
simple views, but more complicated views can’t be updated.
Drop view:
This command is used to drop a view.
Syntax: drop view <view_name>;
Ex: drop view emp_view;

DBMS Page 68
Relational set operators available in SQL
Relational set operators are used to combines results from two or more
queries, using some relation between them.
In SQL we have UNION, INTERSECT, MINUS to implement the union, intersect
and difference relational operators. UNION, INTERSECT, MINUS work properly
only if relations are union compatible i.e all the statements concatenated with sets
must have the same structure. This means that they need to have the same number of
columns and corresponding columns must have the same or compatible data types .
UNION
The union statement combines rows from two or more queries without
including duplicate rows .
Syntax: query1 union query2;
Select <col_list> from tabl1 union select <col_list> from table2;
Ex:
Select * from student1
Union
select * from student2;
The column names in the result of a union are always the same as the column names
in the first select statement in the union.
UNION ALL
The union operator by default removes duplicate rows from the result set. The
union all query can be used to produce a relation that retains the duplicate rows.
Syntax:
Query1 union all Query2;
Select<col_list> from table1 union all select <col_list> from table2;
Ex:
Select * from student1
union all
select * from student2;
INTERSECT
The intersect statement can be used to combine rows from two queries,
returning only the rows that appear in both sets.
Syntax:
Query1 intersect Query2;

DBMS Page 69
Select <col_list>from table1 intersect select<col_list>from table2;
Ex:
Select * from student1
intersect
select * from student2;
MINUS
The minus statement in SQL combines rows from two queries and returns only
the rows that appear in the first set but not in the second set.
Syntax:
Query1 minus Query2;
Select<col_list>from table1 minus select <col_list>from table2;
Ex:
Select * from student1
Minus
Select * from student2;
Different constraints that can be placed on a SQL table

Constraints are used to limit the type of data that can go into a table.
Constraints can be specified when a table is created(with the create table statement)or
after the table is created(with the alter table statement).
Table level and column level constraints:
The table level constraints are part of the table definition. An integrity
constraint defined at the table level can impose rules on any column in the table
whereas column level constraint being a part of the column definition can be imposed
only on the column on which it is defined.
Syntax:
create table <table name>(col1 datatype[column constraint],…..[table constraint][…..]
);
Not null constraint
By default all columns in a table allow Null values. The not null specification
for the attributes ensure that a data entry will be made.when it is crucial to have the
data available, the not null specification will not allow the end user to leave the
attribute empty.because this specification is made at the table leveland stored in the
data dictionary,application programs can use this information to create the data

DBMS Page 70
dictionary validation automatically. Not null constraint can be given only at column
level and not at the table level.
Ex: name varchar2(10)not null
Unique constraint
The unique specification creates a unique indexe in the respective
attribute.This constraint is used to prevent the duplication of values within the rows of
a specified column or a set of columns in a table. Columns defined with this constraint
can also allow null values. If unique constraint is defined in more than one column, it
is said to be composite unique key.
Syntax: colname datatype[unique]
Ex: sno number(5)unique
Default constraint
Default constraint specifies default value of a particular column. The default
constraint assigns a value to an attribute when a new row is added to a table . the end
user may , of course , enter a value other than the default value.
Ex: tot number(4)default 0
Check constraint
The check constraint is used to validate data when an attribute value is
entered. The check constraint does precisely what its name suggests, it checks to see
that a specified condition exists.
Ex: sal number(8,2)check sal>10000
If the check constraint is met for the specified attribute (i.e the condition is true), the
data are accepted for that attribute. If the condition is found false, an error message is
generated and the data are not accepted.
Primary key constraint
A primary key is used to identify uniquely each row in a table. The primary
key can consist of one or more fields on a table. The primary key attributes contains
both a not null and a unique specification. When multiple fields are used as a primary
key , they are called a composite key.
Syntax: colname datatype[primary key]
Ex: sno number(5) primary key
Foreign key constraint
The referential integrity constraint enforces relationship between tables. It
designates a column or combination of columns as a foreign key. The foreign key
establishes a relationship with a specified primary key or unique key in another table,

DBMS Page 71
called the referenced key. In this relationship,the table containing the foreign key is
called the child table and the table containing the referenced key is called the parent
table.
To implement this the common column must be defined in the parent table as
a primary key and in the child table as a foreign key.
Ex: deptno number(5)references emp(deptno)

DBMS Page 72
UNIT-V
Procedural SQL(PL/SQL)
PL/SQL is Oracle’s procedural language, it comprises the standard language
of SQL and a wide array of commands that enable us to control the execution of SQL
statements according to different conditions. Options such as loops and IF…THEN
statements give PL/SQL the power of third generation programming languages.
The advantages of using PL/SQL are several and generally associated with
performance and ease of programming.
 Reduction in the number of calls from an application to the server.
 Portability between the platforms where oracle is executed.
 Error management.
Basic structure of PL/SQL block

Declaration section:
This section is optional. However , the if block uses variable or constants, all
must be declared before being referenced in a command. To initiate this section the
keyword declare should be used .
 Declare an identifier name
 Declare the identifier type(constant or variable)
 Declare the identifier datatype
 Attribute a content to the identifier
Each variable or constant should be specifies with its name , type and an optional
initiate value. All the statements ended with a semicolon.
Execution section:
This section is initiated with the begin declaration . The commands specified
in this section should follow the same rules used for the execution of a command in

DBMS Page 73
SQL. It is mandatory that they end with a semicolon. This section may contain SQL
commands , logical control commands etc.
Exception section:
This section serves to handle an error which may occur during execution of a
PL/SQL program. When an error happens within a PL/SQL program, an error
message is displayed.
Declare
a number
b number
c number
begin
a:=&a;
b:=&b;
c:=a+b;
dbms_output.put_line(‘sum of two numbers is ‘||c);
end;

OUT PUT
Enter value for a 15
Enter value for b 20
Sum of two numbers is 35

PL/SQL Language Elements


Like other programming languages PL/SQL also have specific character sets,
operators, indicators,punctuations, identifiers, comments, etc.
Character Set
A PL/SQL program consists of text having specific set of characters. Character set
may include the following characters:
– Alphabets, both in upper case [A–Z] and lower case [a–z]
– Numeric digits [0–9]
– Special characters ( ) + − * /< >= ! ∼ ˆ ; : . _ @ % , __ # $ & |
{}?[]
– Blank spaces, tabs, and carriage returns.
Lexical Units

DBMS Page 74
A line of PL/SQL program contains groups of characters known as lexical units,
which can be classified as follows:
– Delimiters
– Identifiers
– Literals
– Comments
Delimiters
A delimiter is a simple or compound symbol that has a special meaning to PL/SQL.
Simple symbol consists of one character, while compound symbol consists of more
than one character.
PL/SQL supports following
simple symbol delimiters:
+ − * / => <; % _ , ( ) @ : __
Compound symbol delimiters legal in PL/SQL are as follows:
<>! =∼= ˆ= <=>= := ** .. || << >>
Identifiers
Identifiers are used in the PL/SQL programs to name the PL/SQL program items as
constants, variables, cursors, cursor variables, subprograms, etc. Identifiers can
consists of alphabets, numerals, dollar signs, underscores, and number signs only.
Any other characters like hyphens, slashes, blank spaces, etc. are illegal.
Literals
A literal is an explicitly defined character, string, numeric, or Boolean value, which is
not represented by an identifier. In the following sections we will discuss about each
of these literals in detail:
Numeric Literals
A numeric literal is an integer or a real value. An integer literal may be a positive,
negative, or unsigned whole number without a decimal point. Some examples of
integer numeric literals are as follows:
100 006 −10 0 +10
A real literal is a positive, negative, or unsigned whole

Character Literals

DBMS Page 75
A character literal is an individual character enclosed by single quotes
(apostrophes).Character literals include all the printable characters in the PL/SQL
character set: letters, numerals, spaces, and special symbols. Some examples
of character literals are as follows:
“A” “@” “5” “?” “,” “(”
String Literals
A character string can be represented by an identifier or explicitly written as a string
literal. A string literal is enclosed within single quotes and may consist of one or more
characters. Some examples of string literals are as follows:
“Good Morning!”
“TATA INFOTECH LTD”
“04-MAY-00”
Boolean Literals
Boolean literals are the predefined values TRUE, FALSE, and NULL.
Comments
Comments are used in the PL/SQL program to improve the readability and
understandability of a program. A comment can appear anywhere in the program
code. The compiler ignores comments. Generally, comments are used to describe the
purpose and use of each code segment. A PL/SQL comment may be a single-line or
multiline.
Single-Line Comments
Single-line comments begin with a double hyphen (–) anywhere on a line and extend
to the end of the line.

Steps to Create a PL/SQL Program


1. First a notepad file can be created as typing in the Oracle SQL editor. the command
to create a file,
2. Then a Notepad file will appear and at the same time background Oracle
will be disabled
3. We can write our PL/SQL program in that file, save that file, and we can execute
that program in the Oracle editor . In this program Cursor (Current Set of Records)
concept is used which we will see in the following pages. Here content of EMP table
is opened by the cursor and they are displayed by the DBMS OUTPUT package.
Command IF is used to check whether the cursor has been opened successfully by
using %Found attribute.

DBMS Page 76
4. Then we can execute that file as follows

Procedure
A procedure is a subprogram that performs some specific task, and stored in the data
dictionary. A procedure must have a name, so that it can be invoked or called by any
PL/SQL program that appears within an application.
Procedures can take parameters from the calling program and perform the specific
task. Before the procedure or function is stored, the Oracle engine parses and
compiles the procedure or function. When a procedure is created,
the Oracle automatically performs the following steps:
1. Compiles the procedure
2. Stores the procedure in the data dictionary
Benefits of Procedures and Functions
Stored procedures and functions have many benefits in addition to modularizing
application development.
1. It modifies one routine to affect multiple applications.
2. It modifies one routine to eliminate duplicate testing.
3. It ensures that related actions are performed together, or not at all, by doing the
activity through a single path.
4. It avoids PL/SQL parsing at runtime by parsing at compile time.
5. It reduces the number of calls to the database and database network traffic by
bundling the commands.
Defining and Creating Procedures
A procedure consists of two parts: specification and body. The specification
starts with keyword PROCEDURE and ends with parameter list or procedure name.
The procedures may accept parameters or may not. Procedures that do not accept
parameters are written parentheses. The procedure body starts with the keyword IS
and ends with keyword END. The procedure body is further subdivided into three
parts:
1. Declarative part which consists of local declarations placed between keywords IS
and BEGIN.
2. Executable part, which consists of actual logic of the procedure, included between
keywords BEGIN and EXCEPTION. At least one executable statement is a must in
the executable portion of a procedure. Even a
single NULL statement will do the job.

DBMS Page 77
3. Error/Exception handling part, an optional part placed between EXCEPTION and
END.
The syntax for creating a procedure is follows:
CREATE OR REPLACE PROCEDURE [schema.] package name
[(argument {IN, OUT, IN OUT} data type,. . . . . . . . .)] {IS, AS}
[local variable declarations]
BEGIN
executable statements
EXCEPTION
exception handlers
END [procedure name];
Create: Creates a new procedure, if a procedure of same name already exists, it gives
an error.
Replace: Creates a procedure, if a procedure of same name already exists, it replace
the older one by the new procedure definition.
Schema: If the schema is not specified then procedure is created in user’s current
schema.
Argument: It is the name of the argument to the procedure.
IN: Specifies that a value for the argument must be specified when calling the
procedure.
OUT: Specifies that the procedure pass a value for this argument back to its calling
environment after execution.
IN OUT: Specifies that a value for the argument must be specified when calling the
procedure and that the procedure passes a value for this argument back to its calling
environment after execution. If no value is specified then it takes the default value IN.
Datatype:
It is the unconstrained datatype of an argument. It supports any data type
supported by PL/SQL. No constraints like size constraints or NOT NULL constraints
can be imposed on the data type. However, you can
put on the size constraint indirectly.
Executing/Invoking a Procedure
The syntax used to execute a procedure depends on the environment from
which the procedure is being called. From within SQLPLUS, a procedure can be
executed by using the EXECUTE command, followed by the procedure name. Any

DBMS Page 78
arguments to be passed to the procedure must be enclosed in parentheses following
the procedure name.
Removing a Procedure
To remove a procedure completely from the database, following command is
used:
DROP PROCEDURE <PROCEDURE NAME

Function
A Function is similar to procedure except that it must return one and only one
value to the calling program. Besides this, a function can be used as part of SQL
expression, whereas the procedure cannot.
Difference Between Function and Procedure
Before we look at functions in deep, let us first discuss the major differences between
a function and a procedure.
1. A procedure never returns a value to the calling portion of code, whereas a function
returns exactly one value to the calling program.
2. As functions are capable of returning a value, they can be used as elements of SQL
expressions, whereas the procedures cannot. However, user-defined functions cannot
be used in CHECK or DEFAULT constraints and cannot manipulate database values,
to obey function purity rules.
3. It is mandatory for a function to have at least one RETURN statement, whereas for
procedures there is no restriction. A procedure may have a RETURN statement or
may not. In case of procedures with RETURN
statement, simply the control of execution is transferred back to the portion of code
that called the procedure.
CREATE OR REPLACE FUNCTION [schema.] functionname
[(argument IN datatype, . . . .)] RETURN datatype {IS,AS}
[local variable declarations];
BEGIN
executable statements;
EXCEPTION
exception handlers;
END [functionname];
where RETURN datatype is the datatype of the function’s return value. It can be any
PL/SQL datatype. Thus a function has two parts: function specification and function

DBMS Page 79
body. The function specification begins with keyword FUNCTION and ends with
RETURN clause which indicates the datatype of the value returned by the
function. Function body is enclosed between the keywords IS and END. Sometimes
END is followed by function name, but this is optional. Like procedure, a function
body also is composed of three parts: declarative part, executable part, and an optional
error/exception handling part.
Removing a Function
To remove a function, use following command:
DROP FUNCTION <FUNCTION NAME>;
Parameters
Parameters are the link between a subprogram code and the code calling the
subprogram. Lot depends on how the parameters are passed to a subprogram. Hence it
is absolutely necessary to know more about parameters, their modes,their default
values, and how subprograms can be called without passing all the parameters.
Parameter Modes
Parameter modes define the behavior of formal parameters of subprograms. There are
three types of parameter modes: IN, OUT, IN/OUT.
IN Mode
IN mode is used to pass values to the called subprogram. In short this is an input to
the called subprogram. Inside the called subprogram, an IN parameter acts like a
constant and hence it cannot be assigned a new value.
The IN parameter in actual parameter list can be a constant, literal, initialized
variable, or an expression. IN parameters can be initialized to default values, which is
not the case with IN/OUT or OUT parameters.
It is important to note that IN mode is the default mode of the formal parameters. If
we do not specify the mode of a formal parameter it will be treated as an IN mode
parameter.
OUT Mode
An OUT parameter returns a value back to the caller subprogram. Inside the
subprogram, the parameter specified with OUT mode acts just like any locally
declared variable. Its value can be changed or referenced in expressions, just like any
other local variables.
The points to be noted for an OUT parameter are:
1. The parameter (in actual argument list) corresponding to OUT parameter must be a
variable; it cannot be a constant or literal.

DBMS Page 80
2. Formal OUT parameters are by default initialized to NULL, so we cannot
constraint the formal OUT parameters by NOT NULL constraint.
3. The parameter (in actual argument list) corresponding to OUT parameter can have
a value before a call to subprogram, but the value is lost as soon as a call is made to
the subprogram.
IN/OUT
An IN/OUT parameter performs the duty of both IN parameter as well as OUT
parameter. It first passes input value (through actual argument) to the called
subprogram and then inside subprogram it receives a new value
which will be assigned finally to the actual parameter. In short, inside the called
subprogram, the IN/OUT parameter behaves just like an initialized local variable.
Like OUT parameter, the parameter in the actual argument list that corresponds to
IN/OUT parameter, must be a variable, it cannot be a constant or an expression. If the
subprogram exits successfully, PL/SQL assigns value to actual parameters, however,
if the subprogram exits with unhandled exception, PL/SQL does not assign values to
actual parameters.

Packages in SQL
A package can be defined as a collection of related program objects such as
procedures, functions, and associated cursors and variables together as a unit in the
database. In simpler term, a package is a group of related procedures
and functions stored together and sharing common variables, as well as local
procedures and functions. A package contains two separate parts: the package
specification and the package body.
Advantages of Packages
Packages offer a lot of advantages. They are as follows.
1. Stored packages allow us to sum up (group logically) related stored procedures,
variables, and data types, and so forth in a single-named, stored unit in the database.
This provides for better orderliness during the development process. In other words
packages and its modules are easily understood because of their logical grouping.
2. Grouping of related procedures, functions, etc. in a package also make privilege
management easier. Granting the privilege to use a package makes all components of
the package accessible to the grantee.

DBMS Page 81
3. Package helps in achieving data abstraction. Package body hides the details of the
package contents and the definition of private program objects so that only the
package contents are affected if the package body
changes.
4. An entire package is loaded into memory when a procedure within the package is
called for the first time. This load is completed in one operation, as opposed to the
separate loads required for standalone procedures.
Therefore, when calls to related packaged procedures occur, no disk I/O is necessary
to execute the compiled code already in memory. This results in faster and efficient
operation of programs.
5. Packages provide better performance than stored procedures and functions because
public package variables persist in memory for the duration of a session. So that they
can be accessed by all procedures and functions that
try to access them.
6. Packages allow overloading of its member modules. More than one function in a
package can be of same name. The functions are differentiated, depending upon the
type and number of parameters it takes.
Parts of Package
A Package has two parts. They are:
– Package specification
– Package body
Package Specification
The specification declares the types, variables, constants, exceptions, cursors, and
subprograms that are public and thus available for use outside the package. In case in
the package specification declaration there is only types, constants, exception, or
variables, then there is no need for the package body because package specification
are sufficient for them. Package body is required when there is subprograms like
cursors, functions, etc.
Package Body
The package body fully defines subprograms such as cursors, functions, and
procedures. All the private declarations of the package are included in the package
body. It implements the package specification. A package specification and the
package body are stored separately in the database. This allows calling objects to
depend on the specification only, not on both. This separation enables to change the
definition of program object in the package body without causing Oracle to interfere

DBMS Page 82
with other objects that call or reference the program object. Oracle invalidates the
calling object if the package specification is changed.
Creating a Package
A package consists of package specification and package body. Hence creation of a
package involves creation of the package specification and then creation of the
package body. The package specification is declared using the CREATE PACKAGE
command
The syntax for package specification declaration is as follows.
CREATE[OR REPLACE] PACKAGE <package name>
[AS/IS]
PL/SQL package specification
All the procedures, sub programs, cursors declared in the CREATE PACKAGE
command are described and implemented fully in the package body along with private
members. The syntax for declaring a package body is as
follows:
CREATE[OR REPLACE] PACKAGE BODY <package name>
[AS/IS]
PL/SQL package body
Removing a Package
A package can be dropped from the database just like any other table or database
object. The exact syntax of the command to be used for dropping a package is:
DROP PACKAGE <PACKAGE NAME>;

Exceptions Handling

During execution of a PL/SQL block of code, Oracle executes every SQL sentence
within the PL/SQL block. If an error occurs or an SQL sentence fails, Oracle
considers this as an Exception. Oracle engine immediately tries
to handle the exception and resolve it, by raising a built-in Exception handler.
Introduction to Exceptions
One can define an EXCEPTION as any error or warning condition that arises during
runtime. The main intention of building EXCEPTION technique is to continue the
processing of a program even when it encounters runtime error or warning and

DBMS Page 83
display suitable messages on console so that user can handle those conditions next
time.
EXCEPTION
WHEN exception name THEN
User defined action to be carried out.
Advantages of Using Exceptions
1. Control over abnormal exits of executing programs on encountering error
conditions, hence the behavior of application becomes more reliable.
2. Meaningful messages can be flagged so that the developer can become aware of
error and warning conditions and act upon them.
3. In traditional error checking system, if same error is to be checked at several places,
you are required to code the same error check at all those places. But with exception
handling technique, we will write the exception for that particular error only once in
the entire code. Whenever that type error occurs at any place in code, the exceptional
handler will automatically raise the defined exception.
4. Being a part of PL/SQL, exceptions can be coded at suitable places and can be
coded isolated like procedures and functions. This improves the overall readability of
a PL/SQL program.
5. Oracle’s internal exception mechanism combined with user-defined exceptions,
considerably reduce the development efforts required for cumbersome error handling.

Triggers
A trigger is procedural SQL code that is automatically invoked by the
RDBMS upon the occurrence of a given data manipulation event. Some of the points
about trigger as follows.
 A trigger is invoked before or after a data row is inserted, updated, or deleted.
 A trigger is associated with a database table.
 Each database table may have one or more triggers.
 A trigger is executed as part of the transaction that triggered it.
 Triggers can be used to update table values, insert records in tables, and call
other stored procedures.

There are two types of triggers which can be used in tables


Statement level triggers

DBMS Page 84
This type of trigger is executed once, before or after the triggering statement is
completed.
Row level triggers
This trigger requires use of the FOR EACH ROW keywords .This type of
trigger is executed once for each row affected by the triggering statement.
A trigger may be fired before or after one of the activation commands(INSERT,
UPDATE, DELETE) is executed. A table can contain up to 12 triggers associated
with the activation commands and the firing moment. There are six row level type and
six statement level triggers.
 BEFORE INSERT
 AFTER INSERT
 BEFORE UPDATE
 AFTER UPDATE
 BEFORE DELETE
 AFTER DELETE
Syntax:
Create [or replace]trigger trigger_name
{before|after}
{INSERT|UPDATE|DELETE[OF column[,column]…]}
On table
[[REFERENCING{OLD[AS]old[NEW[AS]new]|
NEW[AS]new[OLD[AS]old]}]
FOR EACH ROW
[WHEN (condition)]]
PL/SQL statements
Ex:
Create or replace trigger stu_trigger after insert or update of m1,m2,m3 on
student
Begin
Update student set tot=m1+m2+m3 where sno=:OLD.SNO;
End;
Removing Trigger

When you delete a table , all trigger objects are deleted with it. To
delete a trigger the following command is used

DBMS Page 85
Drop trigger trigger_name;

Write about SQL joins


SQL joins are used to relate information in different tables. A join condition is
a part of the SQL query that retrieves rows from two or more tables. A SQL join
condition is used in the SQL where clause of select, update, delete statement.
Syntax:
Select col1,col2,col3… from talble1,table2
Where table1.col=table2.col;
SQL joins can be classified into EQUI join and non Equi join.
SQL Equi joins:
It is a simple sql join condition which uses the equal sign as the comparison
operator. Two types of equi joins are SQL outer join and SQL inner join.
SQL non equi joins
It is a sql join condition which makes use of some comparison operator
other than the equal sign like >, <, >=,<=
SQL equi joins
An equi join is further classified into two categories
 SQL Inner join
 SQL Outer join
SQL inner join
All the rows returned by the SQL query satisfy the sql join condition specified.
Ex: If you want to display the product information for each order the query will be as
given below. Since you are retrieving the data from two tables , you need to identify
the common column between these two tables , which is the product_id.

Select order_id,product_name,unit_price,supplier_name,total_units from


product,order_items
Where order_items.product_id=product.product_id;
The column must be referenced by the table name in the join condition, because
product_id is a column in both the tables and needs a way to be identified . this avoids
ambiguity in using the columns in the SQL select statement.
SQL outer join

DBMS Page 86
This sql join condition returns all rows from both tables which satisfy the join
condition along with rows which do not satisfy the join condition from one of the
tables. The sql outer join operator in oracle is + and is used one side of the join
condition only.
The syntax differs for different RDBMS implementation. Few of them
represent the join conditions sa “sql left outer join”, “sql right outer join”.
If you want to display all the product data along with order items data, with
null values displayed for order items if a product has no order item, the sql query for
outer join would be as shown below.
Select p.product_id, p.product_name, o.order_id, o.total_units from
order_items o, product p
Where o.product_id(+)=p.product_id;
If the + operator is used in the left side of the join condition it is equivalent to left
outer join . if used on the right side of the join condition it is equivalent to right outer
join.
SQL self join
A self join is a type of sql join which is used to join a table to itself,
particularly when the table has a “foreign key” that references it own “primary key” .
it is necessary to ensure that the join statement defines an alias for both copies of the
table to avoid column ambiguity.
Ex:
Select a.sales_person_id,a.name,a.manager_id,b.sales_person_id,b.name from
sales_person a, sales_person b where a.manager_id=b.sales_person_id;

SQL non equi join


A non equi join is a sql join whose condition is established using all
comparison operators except the equal(=) operator. Like >=,<=,<,>
Ex
If you want to find the names of students who are not studying either
economics , the sql query would be like,
Select first_name, last_name,subject from student
Where subject!=’economics’;

DBMS Page 87
SQL indexes
Index in SQL is created on existing tables to retrieve the rows quickly. When
there are thousands of records in a table , retrieving information will take a long time.
Therefore indexes are created on columns which are accessed frequently , so that the
information can be retrieved quickly.
An index can be created on a single column or set of columns in a database
table. A table index is a database structure that arranges the values of one or more
columns in a database table in specific order. The table index has pointers to the
values stored in specified column or combination of columns of a table. These
pointers are ordered depending on the sort order specified in the index.
When index is created , it first sorts the data and then it assigns a RowId for each row.
Explicit indexes are created by the user.
Syntax: create index <index_name>on tablename(col1,col2…);
 Index_name is the name of the index
 Tablename is the name of the table to whichthe indexed column belongs.
 Col1,col2 is the list of columns which make up the index.
Ex: create index stu_index on student(sno);
Syntax to unique index
create unique index<index_name>on<table_name>(col1,col2…)
Creating a unique index guarantees that any attempt to duplicate key values fails. Data
validation occurs in the same manner , and the query optimizer does not differentiate
between a unique index created by a constraint or manually created. However , you
should create a unique constraint on the column when data integrity is the objective.
Ex:create unique index s_index on student(sno);
In oracle there are two types of SQL index namely , implicit and explicit.
Implicit indexes:
These indexes are created when a column is explicit defined with primary key,
unique key constraint.
Drop index
By using this command index can be dropped.
Syntax : drop index <index_name>
Ex: drop index s_index;
DCL Commands with example:

DBMS Page 88
DCL commands are used to enforce database security in a multiple user
database environment. Two types of DCL commands are GRANT and REVOKE.
Only Database Administrator's or owners of the database object can provide/remove
privileges on a database object.
SQL GRANT Command
SQL GRANT is a command used to provide access or privileges on the database
objects to the users.
The Syntax for the GRANT command is:
SQL>GRANT privilege_name/all
ON object_name
TO {user_name |PUBLIC |role_name}
[WITH GRANT OPTION];

privilege_name is the access right or privilege granted to the user. Some of the access
rights are ALL, EXECUTE, and SELECT.

Object_name is the name of an database object like TABLE, VIEW, STORED PROC
and SEQUENCE.

User_name is the name of the user to whom an access right is being granted.

User_name is the name of the user to whom an access right is being granted.

PUBLIC is used to grant access rights to all users.

ROLES are a set of privileges grouped together.

WITH GRANT OPTION - allows a user to grant access rights to other users.

For Example: GRANT SELECT ON employee TO user1;This command grants a


SELECT permission on employee table to user1.You should use the WITH GRANT
option carefully because for example if you GRANT SELECT privilege on employee
table to user1 using the WITH GRANT option, then user1 can GRANT SELECT
privilege on employee table to another user, such as user2 etc. Later, if you REVOKE
the SELECT privilege on employee from user1, still user2 will have SELECT
privilege on employee table.
Ex: SQL> Grant all privileges on employee to user1;

DBMS Page 89
SQL REVOKE Command:
The REVOKE command removes user access rights or privileges to the database
objects.
The Syntax for the REVOKE command is:
SQL>REVOKE privilege_name
ON object_name
FROM {user_name |PUBLIC |role_name}
For Example: REVOKE SELECT ON employee FROM user1;This command will
REVOKE a SELECT privilege on employee table from user1.When you REVOKE
SELECT privilege on a table from a user, the user will not be able to SELECT data
from that table anymore. However, if the user has received SELECT privileges on
that table from more than one user, he/she can SELECT from that table until everyone
who granted the permission revokes it. You cannot REVOKE privileges if they were
not initially granted by you.
Ex: SQL> Revoke all privileges on employee from user1;
UPDATABLE VIEWS:
The SQL UPDATE VIEW command can be used to modify the data of a view.
All views are not updatable. So, UPDATE command is not applicable to all
views. An updatable view is one which allows performing an UPDATE command on
itself without affecting any other table
To create an updatable view:-
1. The view is defined based on only one table.
2. The view must include the PRIMARY KEY column and NOT NULL columns of
the table
based upon which the view has been created.
3. The view should not have any field made out of aggregate functions.
4. The view must not have any DISTINCT clause in it's definition.
5. The view must not have any GROUP BY or HAVING clause in it's definition.
6. The view must not have any SUBQUERIES in it's definitions.
7. If the view you want to update is based upon another view, the later should be
updatable.
8. Any of the selected output fields (of the view) must not use constants, strings or
value expressions.
Syntax

DBMS Page 90
SQL>UPDATE < view_name >
SET<column1>=<value1>,<column2>=<value2>,.....
WHERE <condition>;
Parameters
Name Description
view_name Name of the virtual table or view where data will be
modified.
column1,column2 Name of the columns of the table.
value1,value2 Values for the columns which is going to be updated.
condition Condition or criteria.
Example:
Sample view: Studentview
To update the view 'Studentview' with following conditions -
1. 'Ph_No' must be set at 9998887771,
2. 'Course' must be 'BSc',
The following SQL statement can be used :
SQL>UPDATE studentview 
  SET Ph_No=9876543210  
WHERE Course=’BSc’;  
Output:
1 row(s) updated.

Sequences
SQL provides an automatic sequence generated of numeric values, which can a
maximum values upto 38 digits. A sequence can be define to
Generate number in ascending or descending order
Provide intervals between numbers
Sequence can be created by issuing the following statement that references the
sequence. Sequences are creating independent of the tables that it may be used.
The general syntax for creating a sequence is:
CREATE SEQUENCE sequence name
     START WITH VALUE
     INCREMENT BY VALUE
     MINVALUE VALUE
     MAXVALUE VALUE/NOMAXVALUE

DBMS Page 91
     CYCLE/NOCYCLE;
In the above syntax:
Sequence name: It specifies the name of the sequence which can be used while
creating a table.
Increment by: It specifies the interval between sequence numbers. It can be any
positive or negative value, but not zero. If this clause is omitted, the default value is
one.
MinValue: Specifies the sequences minimum value.
No MinValue: It specifies a minimum value of 1 for an ascending sequence.
MaxValue: Specifies a maximum value that a sequence can be generated.
No MaxValue: Specifies a maximum of 1027 for an ascending sequence or -1 for a
descending sequence. This is default clause.
StartWith: Specifies the first sequence number to be generated. The default for an
ascending sequence is the sequence minimum value and for descending, it is the
maximum value.
Cycle: This specifies that the sequence continues to generate values after reaching its
maximum or minimum value.
NoCycle: Specifies that a sequence can’t generate more values after reaching
maximum or minimum value.
Control structure available in PL/SQL
As other programming language we also have control statement in PL/SQL
through we can change the sequential flow of control i.e., commands to control the
flow of program execution. They make the difference, analyzing condition and
allowing decisions to be made within the program. The control structures can be
divided as:
1. Conditional controls
2. Unconditional controls
3. Sequential controls
4. Repetition controls
Condition Controls: Based on value of particular variable decision is taken which
statement is to be executed. The following are the condition controls available in
PL/SQL:

DBMS Page 92
IF…THEN Command: The purpose of the If..Then command is to evaluate a
condition and execute one or more command lines only if the condition analyze is
true. The If..Then command has two variations.
Syntax: IF <condition> THEN
Statements
END IF;
The commands found after the THEN and END IF clauses are executed only if the
condition is true.
IF- ELSE ladder Command:
In this structure, more than one condition may be analyzed and consequently several
action executed.
Syntax:
IF <condition> THEN
Statements
ELSIF <condition> THEN
Statements
ELSIF <condition> THEN
Statements
……………………………
……………………………
…………………………..
ELSE
Statements
END IF;
In this structure we can have numerous ELSIF clauses, but may have
only one ELSE clause. In this structure if the main condition returns False, the first
ELSIF clause is analyzed. If it is TRUE, the next commands are executed until
another ELSIF or ELSE clause is found. If the first ELSIF condition is FALSE, the
program tests the second, and so forth. Upon finding the first TRUE condition, it
executes its command and continues the program after the END IF command line. An
IF…THEN command may be nested within other IF.THEN commands.
LOOP command:
The LOOP command executes a group of command indefinitely or until some
condition forces breaking out of the loop and long program execution elsewhere. The

DBMS Page 93
LOOP command is used with EXIT command, which is responsible for stopping
execution of the loop.
Syntax:
LOOP
Body of the loop;
END LOOP;
Each time a the commands within a loop are executed, the cycle is restarted at
the command immediately after the LOOP command. Upon executing an EXIT
command control of execution passes to the line following that of the END LOOP
command.
FOR..LOOP Command:
The FOR..LOOP command is a variation of the LOOP command. Here the
commands are executed automatically until an evaluated condition returns false.
Syntax:

FOR <counter variable> IN [REVERSE]<initial_value>..<final_value>


LOOP
Body of the loop;
END LOOP;
WHILE Command: Another possible execution is the use of the WHILE
command. This structure analyze a condition only if it is TRUE are the commands
contained within the structure executed.
Syntax
WHILE <condition>
LOOP
Body of the loop;
END LOOP;
GOTO Command: The GOTO command allows you to change the flow of control
with in PL/SQL block. The entry point of a block is defined with in two less than <<
and two greater than >> symbols.
Syntax:
<<label_name>>
Statements;
IF <condition> THEN
GOTO <lable_name>;

DBMS Page 94
END IF;

cursors in sql
A cursor is a special construct used in procedural SQL to hold the data rows returned
by an SQL to hold the data tows returned by an SQL query. A cursor is a reserved
area of memory in which the output of the query is stored like an array holding
columns and rows. There are two types of cursor:
1. Implicit Cursor: An implicit cursor is automatically created in procedural SQL
when the SQL statement returns only one value. Oracle implicitly opens a cursor to
process each SQL statement not associated with an explicitly declared cursor.
2. Explicit Cursor: An explicit cursor is created to hold the output of an SQL
statement that may return two or more rows.
Database cursors enable you to select a group of data, scroll through the group of
records and examine each individual line of data as the cursor points to it.
Follow these steps to create, use, and close a database cursor:
1. Create the cursor.
2. Open the cursor for use within the procedure or application.
3. Fetch a record's data one row at a time until you have reached the end of the
cursor's records.
4. Close the cursor when you are finished with it.
5. Deallocate the cursor to completely discard it.
Creating a Cursor
To create an explicit cursor, we use the following syntax:
CURSOR cursor_name IS SQL statement;
For example: Declare
CURSOR csr_stud IS Select sno, sname, savg FROM student ;
Opening a Cursor:
Opening a cursor execute the query and identifies the active set that contains
all the rows which need the query search criteria.
Syntax : OPEN cursor_name;
Eg: Begin
Open csr_stud;
End;
Fetching a Record from the Cursor:

DBMS Page 95
The fetch statement retrieves the rows from the active set to the variables one
at a time. We can make use of any loop structure like Loop..End Loop, While, For
etc., to fetch the records from the cursor into variables one row at a time.
Syntax: Fetch cursor_name INTO var1, var2, ……….varN;
For each column value returned by the query associated cursor, there must be
corresponding variable in the into list and there data types must match. These variable
must be declared in the declare section of the PL/SQL block.
Eg:
LOOP
FETCH csr_stud into csno,csname,csavg;

Dbms_output.put_line(csno||csname||csavg);
END LOOP;
Closing a Cursor:
The close statement Tables the cursor and the active set becomes undefined.
This will release the memory occupied by the cursor and its data set. Once a cursor is
close, the user can re-open the cursor using the open statement.
Syntax: close cursor_name;

DBMS Page 96

You might also like