Relational Database Management Systems by N.P. Singh
Relational Database Management Systems by N.P. Singh
DATABASE SYSTEMS
used. For example in banking system with branches in several cities may store customer
data at each branch. In this decentralized database system, it is job the DBMS system to
provide information of customer from any location by hiding all the details of how data is
searched. Another advantage if this system is in one the server gets down, user can still
find information from others
1.3.1 Functions of DBMS
• DBMS free the programmers from the need to worry about the organization and location
of the data i.e. it shields the users from complex hardware level details.
• DBMS can organize process and present data elements from the database. This
capability enables decision makers to search and query database contents in order to
extract answers that are not available in regular Reports.
• Programming is speeded up because programmer can concentrate on logic of the
application.
• It includes special user friendly query languages which are easy to understand by non
programming users of the system.
1.3.2 Advantages and disadvantages of database systems
Using a DBMS to manage data has many advantages:
1. Data independence — Application programs should be as independent from details of
data storage and representation. DBMS provides us abstract view of the data to insulate
application code from such details.
2. Data administration — Using DBMS software, it is very easy to manage database.
Centralizing the administration of data can improve performance of database system when
several users share the data.
3. Data integrity and security — DBMS can provide security to databases by assigning
privileges to different users. It provides authorization or access controls to different
classes of users to perform different operations on databases, such as creation,
modification, deletion and updation of data. DBMS can enforce integrity constraints on
the data. For example before inserting student marks into database file, the DBMS can
verify that whether student is on roll or not. In the conventional systems because the data
is duplicated in multiple files so updating or changes may sometimes lead to entry of
incorrect data in some files where it exists.
4. Flexibility — Since changes are often necessary to the contents of the data stored in
any system, these changes are made more easily in a centralized database than in a
conventional system. Because programs and data are independent, programs do not have
to be modified when types of unrelated data are added to or deleted from the database, or
when physical storage changes.
5. Fast response to information requests — Because data are integrated into a single
database, complex requests can be handled much more rapidly then if the data were
located in separate, non-integrated files. In many businesses, faster response means better
customer service.
6. Efficient data and multiple accesses — A DBMS uses a variety of techniques to store
and retrieve data efficiently. DBMS allows data to be accessed in a variety of ways (such
as through various key fields) and often, by using several programming languages (both
3GL and nonprocedural 4GL programs).
7. Lower user training costs — Users often find it easier to learn such systems and
training costs may be reduced. Also, the total time taken to process requests may be
shorter, which would increase user productivity.
8. Less storage — Theoretically, all occurrences of data items need be stored only once,
thereby eliminating the storage of redundant data. System developers and database
designers often use data normalization to minimize data redundancy.
9. Standards can be enforced — Since all access to the database must be through
DBMS, so standards are easier to enforce. Standards may relate to the naming of data,
format of data, structure of the data etc. Standardizing stored data formats is usually
desirable for the purpose of data interchange or migration between systems.
10. Controlling Data Redundancy — In the conventional file processing system, every
user group maintains its own files for handling its data files. This may lead to
• Duplication of same data in different files.
• Wastage of storage space, since duplicated data is stored.
• Errors may be generated due to updation of the same data in different files.
• Time in entering data again and again is wasted.
• Computer Resources are needlessly used.
• It is very difficult to combine information.
11. Elimination of Inconsistency — In the file processing system information is
duplicated throughout the system. So changes made in one file may be necessary be
carried over to another file. This may lead to inconsistent data. So we need to remove this
duplication of data in multiple file to eliminate inconsistency.
1.3.3 Disadvantages of database systems
Because of the larger number of users accessing the data when a database is used, the
enterprise may involve additional risks as compared to a conventional data processing
system in the following areas.
1. Complexity — The supply and operation of a database management system with
several users and databases is quite costly and demanding. A DBMS is a complex piece of
software, optimized for certain kinds of workloads (e.g., answering complex queries or
handling many concurrent requests), and its performance may not be adequate for certain
specialized applications.
2. Data Quality — Since the database is accessible to users remotely, adequate controls
are needed to control users updating data and to control data quality. With increased
number of users accessing data directly, there are enormous opportunities for users to
damage the data. Unless there are suitable controls, the data quality may be compromised.
3. Cost of Hardware & Software — A computer with high speed of data processing and
memory of large size is required to run the DBMS software. It means that you have to up
grade the hardware used for file-based system. Similarly, DBMS software is also very
costly.
4. Cost of Data Conversion — When a computer file-based system is replaced with a
database system, the data stored into data file must be converted to database file. It is very
difficult and costly method to convert data of data files into database. You have to hire
database and system designers along with application programmers. Alternatively, you
have to take the services of some software house. So a lot of money has to be paid for
developing software
5. Cost of Staff Trailing — Most DBMSs are often complex systems so the training for
users to use the DBMS is required. Training is required at all levels, including
programming, application development, and database administration. The organization has
to be paid a lot of amount for the training of staff to run the DBMS.
6. Database Damage — In most of the organizations, all data is integrated into a single
database. If database is damaged due to electric failure or database is corrupted on the
storage media, then valuable data may be lost forever.
1.4 CLASSIFICATION OF DBMS USERS
People may be direct or indirect DBMS user. They operate in various roles requiring
various levels of training. They can access and retrieve data as per requirement from
databases. Following is the list of few Databases users:
Database Administrator (DBA)
Database Designers
End Users
Application Programmers
1.4.1 Database Administrator (DBA)
The DBA is a person or a group of persons who is responsible for the supervision of the
database. In any organization DBA plays a very crucial role. The DBA is responsible for
giving permission to the users to access the database by grant and revoke privileges. He is
also responsible for coordinating and monitoring its use, managing backups and repairing
damage due to hardware and/or software failures and for acquiring hardware and software
resources as needed. In case of small organization the role of DBA is performed by a
single person and in case of large organizations there is a group of DBA’s who share
responsibilities.
For example in a university / college, it is job of the DBA to make sure that DBMS makes
the correct address of students or staff available from one central storage. Some of the
roles of the DBA may include:
Installation/ Upgradation / Configuration of software and hardware: It is job of the DBA
to install DBMS software, application software, and other software related to DBMS
administration. DBA test new software before it is moved into a production environment.
DBA also configure hardware and software.
Security administration: In client/server or distributed computing where number of users
share databases, security is very important issue. DBA monitors and administers DBMS
security. The DBA is also responsible for assigning users to databases and determining the
proper security level for each user. Within each database, the DBA is responsible for
assigning permissions to the various database objects such as tables, views, and stored
procedures.
Database design: The DBA is often involved at the preliminary database-design stages.
The DBA is the person who is well familiar with DBMS and system, so helps the other
users like development team with special performance considerations and can point out
potential problems.
Data analysis: It is also very important to analyze store data to increase performance and
efficiency of system. The DBA is called on to perform this task data analysis.
Data modeling and optimization: By modeling the data, it is possible to optimize the
system layouts to take the most advantage of the I/O subsystem. System administrator
performs periodic maintenance. DBA also understand and implement of schemas (layout
of Database).
Performing Backup and Recovery : Backup and recovery are the DBA’s most critical
tasks; they include the following aspects:
Establishing standards and schedules for database backups
Developing recovery procedures for each database
Making sure that the backup schedules meet the recovery requirements
a. Establishing and Enforcing Standards — The DBA should establish naming
conventions and standards for the DBMS Server and databases and make sure that
everyone sticks to them.
1.4.2 Database Designers
They are responsible for identifying the data to be stored in the database and for choosing
appropriate structure to represent and store the data. It is the responsibility of database
designers to communicate with all prospective of the database users in order to understand
their requirements so that they can create a design that meets their requirements. The
database designer is responsible for defining the detailed database design, including tables,
indexes, views, constraints, triggers, stored procedures, and other database specific
constructs needed to store, retrieve, and delete objects. Database Designers are also
identify the data (entities and attributes), relationships between the data and constraints on
the data. He/she maps the logical database design into a set of tables and integrity
constraints. He designs any security measures required on the data.
1.4.3 End Users
End Users are the people who interact with the database through applications or utilities.
The various categories of end users are:
Casual End Users - These Users occasionally access the database but may need different
information each time. They use sophisticated database Query language to specify their
requests. For example: High level Managers who access the data weekly or biweekly.
Native End Users - These users frequently query and update the database using standard
types of Queries. The operations that can be performed by this class of users are very
limited and effect precise portion of the database.
For example, reservation clerks for airlines/hotels check availability for given request and
make reservations. Also, persons using Automated Teller Machines (ATM’s) fall under
this category as he has access to limited portion of the database.
Standalone end Users/On-line End Users - Those end Users who interact with the
database directly via on-line terminal or indirectly through Menu or graphics based
Interfaces. For example, user of a text package, library management software that store
variety of library data such as issue and return of books for fine purposes.
1.4.4 Application Programmers
As we know Computer programs as being composed of three parts:
a. input
b. processing
c. output
A programmer is a person who writes, tests, debugs, and maintains the detailed
instructions, called computer programs. There are mainly two types of computer
programmers, system and application programmers. Systems programmers, write
programs to manage and maintain computer systems software, such as operating systems
and utility software. Application software is written according to the requirements of the
users/ organizations. Programmer converts that software design into a logical series of
instructions that the computer can follow. Application programmers write programs to
handle a specific job, such as a program for railways reservation, hospital management,
banking, inventory control etc. Different programming languages are used depending on
the use of the program. Database programmers write programs to access data and perform
calculations. These programs could be written in General Purpose Programming languages
such as Visual Basic, Developer, C, FORTRAN, COBOL etc. to manipulate the database.
These application programs operate on the data to perform various operations such as
retaining information, creating new information, deleting or changing existing
information.
For example, these days Visual Basic is a very popular language for front end
programming. Menus, forms, Macros and reports are created by visual basic language, can
be connected with back-end DBMS, with the help of software tools and utilities. Another
job of database programmers is to manage information of an organization without
reducing the flexibility of data storage, manipulation and retrieval process. In the process
testing and debugging, programmer test program, makes the appropriate modification,
then rechecks the program until an acceptably low level. Programmers prepare program
documentation and writes operating procedure.
1.4.5 System Analysts
System analysis and design involves the building of systems. The systems analyst plays a
vital role in the systems development process. System analysts are the architect of the
systems. The Systems analysts bring the users and owners ideas together to create a
solution for their business needs. System analysis and design are two different activities
preformed by system analysts. A systems analyst must attain skills like technical,
managerial, analytical, and interpersonal. There are major objectives of system analyst:
1. Defines the overall objectives of the system project.
2. Creates a road map of the existing organization/system, identifying the creators of data
and the primary user of data.
3. Describes hardware and software that serves the organizations.
4. Interacts with the customers to know their requirements
5. Prepares test data and tests programs as necessary to eliminate errors in logic, coding or
performance problems.
6. Identifies the areas of required organizational change or implements the new system
7. Prepares quality documentation and writes operating procedures.
8. Trains and prepares training material for operators and program users, or arranges for
training.
1.6 WORKERS BEHIND THE SCENE
1.6.1 DBMS system designers and implementers
DBMS Systems design is the process of defining the architecture, components, modules,
interfaces, and data for a system to satisfy specified requirements. He decides how the
logical database design is to be physically realized. DBMS Systems design ensures that
the direction of database development ultimately supports corporate objectives. There aim
is to design the DBMS software packages.
1.6.2 Tool developers
Tools are special purpose software used to assist designers/ developers/users to do a
specific task on computer. Tools are optional packages that are often purchased separately.
Tool developers jobs are to design and implement tool that facilitate the use of the DBMS
software. Tools include design tools, performance tools, specials interfaces, graphical
interfaces, prototyping, simulation, and test data generation etc.
1.6.3 Operator and maintenance personnel
They work on running and maintaining the hardware and software environment for the
database system.
REVIEW QUESTION
Chapter 2
DATABASE SYSTEM CONCEPTS AND ARCHITECTURE
So some of the characteristics of both the hierarchical and network database approaches
are:
They use pointers.
Their architecture uses redundancy to create relationships and optimization. They
evolved over time, almost on a trial and error basis.
Models were developed after the fact to explain and improve them, but not as
part of the original design and theory.
Advantages
The network database gives fast data access
It also allows users to create queries that are more complex than those they created using
a hierarchical database.
Disadvantages
A user has to be familiar with the structure of the database in order to work through the
set structures.
Change in the database structure is difficult without affecting the application programs
that interact with it.
2.1.4 Relational Database Model
It is a data model in which the data is stored in tables (also referred to as entities).
Each table has rows (also referred to as records or tuples) and columns (also referred to
as attributes). In relational database model any tables can be linked together. The relational
model is based on a collection of mathematical principles drawn primarily from set
theory and predicate logic. These principles were first applied to the field of data modeling
in the late 1960s by Dr. E. F. Codd. Each row in a table has a unique identifier (UID). In
this database model relationships between tables are defined using the UID of one table
and joining them with the UID of another table. Pointers are not used. Data redundancy
is reduced via a process called normalization.
The relational model presents data in familiar two-dimensional tables, much like
a spreadsheet does. Unlike a spreadsheet, the data is not necessarily stored in tabular
form and the model also permits combining (joining in relational terminology) tables to
form views, which are also presented as two-dimensional tables.
The entire structure is, as we’ve said, a relation. The relation is divided into two
sections, the heading and the body. The tuples make up the body, while the heading is
composed of, well, the heading. The body of the relation consists of an unordered set of
zero or more tuples. A relation is a relation provided that it’s arranged in row and
column format and its values are scalar. Its existence is completely independent of any
physical representation. As such, a user isn’t required to know the physical location of
a record in order to retrieve its data. This is unlike the hierarchical and network database
models, in which knowing the layout of the structures is crucial to retrieving data. As
long as a user is familiar with the relationships among the tables in the database, he can
access data in an almost unlimited number of ways. He can access data from tables that
are directly related and from tables that are indirectly related.
Example 3:
The relational model categorizes relationships as one-to-one, one-to-many, and many-to-
many. A relationship between a pair of tables is established implicitly through matching
values of a shared field. In the above figure, the Student and Course tables are related via
Course ID field; a specific course is associated with student through a matching Course
ID.
The benefits of the two-tier client/server model include the following: User interface is
improved as compared with systems using dumb terminals. workstation processor did
most of the work and did not have to be shared with
anyone else, so it offer the potential for improved performance Here are the drawbacks:
Expensive client workstations are required because all the application logic ran on the
client.
Applications are installed on every client workstation, and all have to be updated with a
new software release at the same time.
REVEIW QUSETIONS
Short Anwser Type
1. Metadata, which literally means “data about data”
2. In network model, root node may have multiple child nodes.
3. In network model, a child node has only one parent node.
4. A schema is the physical layout of tables in a database
5. A back end , responsible for interfacing with the user
6. DDL stands for …………..
7. DCL stands for …………..
8. DML stands for …………..
9. SQL stands for …………..
10. Drop command is used to ………….. a table.
11. Create command is used to ………….. a table.
12. Insert command is used to ………….. data
13. Select command is used to ………….. data1.
Long Answer Type
1. What is data modeling?
2. Expalin various types of Datamodels.
3. What do you understande by architecture of DBMS?
4. Explain database schema levels.
5. What is the role of Schems?
6. What is difference between distributed and centerlized DBMS?
7. Classify DBMS.
8. Explain Database schema levels.
9. Write various advantages or disadvantages of Relational Model.
10. What is database state and instance?
11. What do you mean by data independence?
12. Explain terms DDL, DML,and DCL.
13. What do you mean by interface?
14. What is the role of view level in data abstaction?
(True/ False) (True/ False) (True/ False) (True/ False) (True/ False)
15. What is the difference between Procedural DML and Non-procedural DML?
Chapter 3
DATA MODELING USING E.R. MODEL
Formal Terminology
Conceptual Physical
relation table
attribute field
tuple record
3.5.1 Constraint and Cardinality
Constraints are some rules to store or retrieve data from a database. They restrict users
what data can be stored and retrieved. Constraints should be added after a logical data
model is stable. A primary key consists of one or more attributes of an entity that
distinguishes each record from the others. Cardinality (or degree) concerns the number of
instances involved in a relationship. A relationship can be said to be either a 1:1 (oneto-
one) relationship, a 1:M (one-to-many) relationship, or a M:M (many-to-many)
relationship.
3.6 ENTITY RELATIONSHIP MODELING
Entity relationship modeling is the process of visually representing entities, attributes, and
relationships, producing a diagram called an entity relationship diagram (ERD). Non-
technical people can easily understand it. It provides great value to technical persons.
ERDs are platform independent and can even be used for non relational databases if
desired. It was developed by Peter Chen in 1976. Many variations in ERD have been
developed by various vendors, computer scientists, and academician. The elements
common to all ERD formats are shown below:
Entities are represented as rectangles or boxes.
Relationships are represented as lines.
Line ends indicate the maximum cardinality of the relationship . Symbols near the line
ends indicate the minimum cardinality of the relationship. Attributes may be optionally
included.
3.6.1 One-to-One ( 1: 1) Relationships
A one-to-one relationship is an association where an instance of one entity can be
associated with at most one instance of the other entity, and vice versa. The one-toone
relationship is simplest type of relationship. A pair of tables have a one-to-one relationship
when a one record in the first table is related to only one record in the second table, and a
single record in the second table is related to only one record in the first table. In one-to-
one relationship, one table serves as a “parent” table and the other
serves as a “child” table. One-to-one relationships are not very common among entities.
In following figures, the relationship between the Employee and Pay Receivable entities is
one-to-one. This means that an Employee can have at most one associated Pay, and Pay
can have at most one associated Employee. The relationship is also mandatory
in both directions, meaning that an employee must have at least one pay receivable
associated with it, and a Pay receivable must have at least one Employee associated with
it. Putting this all together, we can read the relationship between the Employee and Pay
entities as “one employee has one and only one associated pay receivable, and one pay
receivable has one and only one associated employee .”
Following figure shows an example of a typical one-to-one relationship. In this figure,
Employee is the parent table and Pay Receivable is the child table. A single record in the
Employee table can be related to only one record in the Pay Receivable table, and a single
record in the Pay Receivable table can be related to only one record in the Employee table.
Both the tables are linked together by Employee ID is indeed the primary key in both
tables.
3.6.2 One-to-Many (1: M) Relationships
A one-to-many relationship is an association between two entities where any instance of
the first entity may be associated with one or more instances of the second, and any
instance of the second entity may be associated with at most one instance of the first.
The relationship between Department and Faculty as shown in the figure, which is
mandatory in only one direction, is read as follows: “At any point in time, each
Department can have zero to many Faculties, and each Faculty must have one and only
one Department.” One-to-many relationships are quite common. In fact, they are the
fundamental building block of the relational database model in that all relationships in a
relational database are implemented as if they are one-to-many.
A one-to-many relationship exists between a pair of tables when a single record in the first
table can be related to many records in the second table, but a single record in the second
table can be related to only one record in the first table.
The example in following figure illustrates a typical one-to-many relationship. A single
record in the Department table can be linked to one or more records in the Faculty table,
but a single record in the Faculty table is related to only one record in the Department
table. Department ID is a foreign key in the Faculty table ( more detail in chapter 4).
3.6.3 Many-to-Many ( M:M ) Relationships
A many-to-many relationship is an association between two entities where any instance of
the first entity may be associated with zero, one, or more instances of the second, and vice
versa. following figure, shows many-to-many relationship between Teacher and Student.
Relationship is read as: “At any given event, each Teacher teaches zero to many students,
and each student is being taught by zero to many teachers.”
This particular relationship has data associated with it as shown in the diamond on the
diagram. Data that belongs to a many-to-many relationship is called intersection data.
Many-to-many relationships are quite common, and most of them will have intersection
data. The relational model does not directly support many-to-many relationships. In
Relational database, some changes are required to map the conceptual model to the
corresponding logical model. The intersection data is mapped to a separate table (an
intersection table). The many-to-many relationship are mapped to two one-tomany
relationships. The intersection table is kept in the middle and on the “many” side of both
relationships.
A pair of tables have many-to-many relationship when a single record in the X table can
be related to many records in the Y table and a single record in the Y table can be related
to many records in the X table. The relationship are established with a linking table. A
linking table makes it easy for database designer to link records from one table with those
of the other. It helps user to add, delete, or modify related data without any problem. A
linking table can be defined by taking copies of the primary key of each table in the
relationship. Structure of the new table is form with the use of these primary keys.
As shown in following figure, there is no relation between Teacher and Student entities.
To implement many-to-many relationship, third table teaching is being created with
primary keys from both the tables
3.6.4 Unary or Recursive Relationships
Unary relationships have only one participant the relation is associated with itself. These
relationships can exist between entity instances of the same type. These are also called
recursive relationships. An example of a unary relationship is Employee to Manager.
One’s manager is, in most cases, also an employee with a manager of his or her own.
Unary relationships can be of any cardinality. One-to-many unary relationships are used to
implement hierarchies, such as the organizational hierarchy implicit in the Employee-
Manager relationship.
Example 1:
In following figure the line drawn between ‘Computer Engg.’ and ‘230’ indicates that
lecturer 230 is employed by the Computer Engg department. Note that the cardinality of
the relationship is 1:M. The department ‘Computer Engg’, for instance, has two lecturers
associated with it. The entity Lecturer has mandatory participation while Department has
optional participation.
Electrical Engg., for instance, is not associated with any lecturers.
Example 2:
In following figure, Lecturer to Student is a many-to-many relationship. Lecturer 234, for
example, teaches students 34698 and 37798. The participation of Lecturer is optional;
Student is mandatory.
3.7 MAPPING THE ENTITY DIAGRAM TO A RELATIONAL DATABASE
Converting an ER diagram into a database is called mapping. A relational database is also
represented by two-dimensional tables called “relations.” The tables are composed of rows
and columns. The rows are called tuples and the columns, attributes. All attributes of a
relation must be atomic and keys must not be null. Mapping rules are required to convert
ER diagram into a relational database.
3.7.1 Rule 1: Mapping of strong entities
For strong entities, create a new table/relation for each strong entity. The indicated key of
the strong entity is made the primary key of the table. If there is more than one candidate
key in ER diagram, choose one as a primary key.
3.7.2 Rule 2: Mapping atomic attributes
For entities with atomic attributes, entities are mapped to a table by forming columns for
the atomic attributes.
Example 3:
Conversion of following ER diagram with atomic attributes into relation database
A relational database of the above Entity diagram with some data would be like following
table:
The entity name, Student, would be the name of the relation/table. The attributes in the
diagram become the column headings.
Now suppose that the above example had name as a key. It would be mapped
into two relations: a relation with the multi-valued attribute, and a resulting relation
with the multi-valued attribute excised.
3.8 MAPPING RELATIONSHIPS TO A RELATIONAL DATABASE
In this section we are going learn how to mapping of relationships. Before mapping go
through these steps
Identify the entities
Add attributes to entities, identifying primary keys:
What relationship is there
3.8.1 Rule: mapping M:M relationships
For each M:M relationship, form a new table ( relation) with the primary keys of both of
the two entities (owner entities) that are being related in the M:M relationship. The key of
this newly created table will be the concatenated keys of the owner entities. Include any
attributes that the M:M relationship may have in this new table.
Example 6:
For example, refer to following ER diagram. The student and course tables have
the following data:
Both CourseID and RegNo together are the primary key of the relation, admission. 3.8.2
Rule: Mapping 1:M relationships
For binary 1:M relationships, we have to find what kind of participation constraints the M
side of the relationship has. For binary 1:M relationships, if the M-side has full
participation, include the key of the entity from the 1 side, in the relation on the M side as
a foreign key.
Example 7:
For example, in following ERD, we assume full participation on the student side,
we will have:
Rooms may have zero or more students and Students must live in one and only one room.
The relational implementation would be:
Here, the full participation is on the student entity side that is the M side. Key is taken
from room (RoomNo) relation and included it in the student relation. If the relationship
had an attribute, it would be included in the M side and that is student.
3.8.3 Rule: Mapping 1:M relationships with partial participation
For binary 1:M relationships, if the M-side has partial participation, the 1:M relationship is
handled just like a binary M:M relationship. A separate table is created for the
relationship. The key of the newly created table consists of a concatenation of the keys of
the related entities. Include any attributes that were on the relationship, on this new table.
3.8.3 Rule: Mapping 1:1 relationships
For binary 1:1 relationships, include the primary key of Entity X into Entity Y as the
foreign key.
Example:
In the following ERD there is One to one relationship between employee and
house
To map this relation ship key is added to any one the table like EmployeeID is added to
house relation
REVIEW QUESTION
Chapter 4
RELATIONAL MODEL
4.1 INTRODUCTION
The relational data model is unusual in being largely due to the efforts of one man, E.F.
Codd. In 1970 E.F. Codd published a seminal paper which laid the foundation for
probably the most popular of the contemporary data models. A database is effectively a set
of data structures for organising and storing data. In any data model, and consequently in
any DBMS, we must have a set of principles for exploiting such data structures for
information systems applications with in organisations. Data definition is the process of
exploiting the inherent data structures of a data model for a particular organisational
application.
4.2 DOMAINS
Each column of a table there is a set of possible values called its domain. The primary unit
of data in the relational data model is the data-item. Such data-items are said to be non-
decomposable or atomic. A set of such data-items of the same type is said to be a domain.
Domains are therefore pools of values from which actual values appearing in the columns
of a table are drawn.
In the above figure we have five columns in student table. Let d1 represents the set of all
Registration No, d2 is set of name, d3 is set of semester, d4 is set of Branch and d5 is set of
cities
So the table Student can be represented as :
d1 x d2 x d3 x d4 x d5
Example 1:
The possible domain definitions for the attributes person-name, date-of-birth,
and city might be:
PERSON-NAMES = {Ajit Kumar, Aman, Ram Gopal , Akash, Anjali, Balraj} CITY = {
Hoshiarpur, Jalandhar, Ludhiana, Patiala, Bathinda}
DATE-OF-BIRTH = {a string in dd-mm-yyyy format, such that: 03–02–1940 dd, mm,
yyyy represent day, month year}
To make the distinction between the attributes and their corresponding domains, we are
using small letters for the names of the attributes and capital letters for the domains. An
empty set {} is a member of any of these domains.
4.3 TABLE
According to the relational model, data in a relational database is stored in relations,
which are perceived by the user as tables. Each relation is composed of tuples (records)
and attributes (fields). A table that stores data used to supply information is called a data
table, and it is the most common type of table in a relational database. Data in this type of
table is dynamic because you can manipulate it (modify, delete, and so forth) and process
it into information in some form or fashion.
4.4 FIELD
A field (also called an attribute in theory of relational database) is the smallest structure in
the database. It shows a characteristic of the subject of the table to which it belongs. Fields
are the structures that actually hold data. The data in these fields can then be retrieved and
presented as useful information. The importance of fields cannot be ignored. Every field
contains one and only one value, and its name will identify the type of value it store. If
you see fields with names such as RollNo, Name, City, State, And Zipcode, you can easily
imagine exactly what type of values move into each field.
Types of fields in an improperly or poorly designed database.
A multipart field (composite field), which holds two or more distinct items within
its value.
A multivalued field, which contains multiple instances of the same type of value. A
calculated field, which holds a concatenated text value or the result of a
mathematical expression.
4.5 RECORD
A record (a tuple) represents a unique instance of the subject of a table. It is composed of
the entire set of fields in a table, regardless of whether or not the fields contain values.
Each record should be identified throughout the database by a unique value in the primary
key field of that record. Records are a key factor in understanding table relationships.
Table relationships deals how a record in one table relates to other records in another table.
4.6 RELATIONS
A relation may be thought of as a set of rows. A relation may alternately be though of as a
set of columns. There is only one data structure in the relational data model – the relation.
The relational data model consists of the following three component parts:
structure - a uniform single data structure type called a relation manipulations a set of
operators that transform relations into other relations behaviour - general integrity rules
that guard the consistency of any database
Example 2:
Let us take a product of the domains defined in Example 1, that is P = PERSONNAMES ×
CITIES × -DATES-OF-BIRTH. P will then contain all tuples that were obtained by
combining all the values from these three domains:
P={<Ajit Kumar, 03–02–1940, Hoshiarpur>, <Ajit Kumar, 03–02–1940, Jalandhar>,
……………, <Ajit Kumar, 13–02–1947, Ludhiana>,…………, < Aman, 1– Jalandhar>,
……………, <Ajit Kumar, 13–02–1947, Ludhiana>,…………, < Aman, 1– 09-1960,
Hoshairpur>,..…<Balraj, 31–12–1999, Bathinda>}
‘A person with person-name exists, is of 50 years of age or more, was born on date-of-
birth at city’, the corresponding relation might only hold the following triples:
PERSON50={<Ajit Kumar, 12–10–1950, Hoshiarpur>,
<Aman, 12–11–1950, Ludhiana>,
<Akash, 13–11–1951, Jalandhar>}
PERSON50 is a subset of P and contains only those tuples of P that represent information
about the 50-year old people in that society.
It is very easy to show relations in a tabular form as shown in following figure. Each row
of the table acts as distinct tuple, so that its degree is a number of columns and its
cardinality is a number of rows in the table. The attribute names may not be the same as
the names of their underlying domains. In a relation, no two tuples can be identical and the
order in which the tuples appear is not significant. The values in the relations will thus be
referred to through a combination of a relation name and the attribute name. Tuples are
solely identified through the attribute values in the relational model. An attribute (or a set
of attributes) uniquely identify any particular tuple within a relation.
Because the idea of a relation is modeled on a mathematical construct, a relation is a table
which obeys a certain restricted set of rules:
Every relation in a database must have a unique name
Every column in a relation must have a unique name within the relation All entries in a
column must be of the same kind. They are said to be defined on
the same domain
Each row in a relation must be unique. Duplication of rows are not allowed in a
relation
The ordering of rows and columns in a relation is not significant Each cell or
column/row intersection in a relation should contain only a atomic
value. multiple-values are not allowed in the cells of a relation
4.5.1 Definition
A relation R is a subset of an expanded cartesian product of n, not necessarily distinct
domains D1×D2×…,×Dn, such that for every element dk=<dk1, dk2,…, dkn> R a
predefined proposition p(<dk1,dk2,…,dkn>) is true;
dk Di for every i=l, 2,…,n where k is the number of ntuples in the relation Ri
(cardinality of R) and n is the number of attributes in the relation R (degree of R). Let us
take an example of first row of the above table, where see ; t(Registration No.) =
6226204201, t(Name) = “Amrik Singh”, t(Semester) = 1, t( Branch) = “CSE” , t( City)
=”Jalandhar”
Relation scheme R, can be represented by set of attributes a1, a2, a3,….…., an. None empty
set Di( 1<i <n ) is known as domain of attribute ai. It is denoted as Dom(ai). A relation r of
relation scheme R is a set of tuples { t1, t2, t3,………………. ,tm) from R to D.
4.6 VIEW
It is a “virtual” table made of fields from one or more tables in the database. The tables
used to compose a view, are called base tables. The relational model refers to a view as
“virtual” because it takes data from base tables rather than storing data on its own. The
only information about a view that is kept in the database is its structure. Many major
RDBMS programs support views Views enable us to see the information in our database
from many different aspects, providing us with a great amount of flexibility. Views are
created in a variety of ways. They are very useful when the base on multiple related tables.
For example, in a college scheduling database, we can create a view that consolidates data
from the students, classes, courses and class schedules tables.
4.7 CONSTRAINTS
In is very important for a user to know that what data can be stored or retrieved from a
database. Constraints are rules restricting for storing and retrieving data. They should be
added after a logical data model is stable. Primary and, to some extent, foreign key
constraints fit this definition. They are critical components of a relational database.
4.7.1 Key Constraints
Keys are important for a table structure for the following reasons:
They ensure that each record in a table is uniquely identified. The complete set of records
within the table constitutes the collection, and each record represents a unique instance of
the table’s subject within that collection. A key is mean of accurately identifying each
instance
Various types of integrity, are established and enforced by keys. Keys play a major role of
table-level integrity and relationship-level integrity. Keys ensure that a table has unique
records and that the fields those are used to establish a relationship between a pair of
tables always contain matching values.
Table relationships are established by keys.
4.8 CANDIDATE KEYS
The first type of key that is establish for a table is the candidate key, which is a field or
group of fields that uniquely identifies a single instance of the table’s subject. Each table
must have at least one candidate key. It is examined from the table’s pool of available
candidate keys and designate one of them as the official primary key for the table.
Before, a field is designated as a candidate key, we must make certain it complies with all
of the elements of a Candidate Key. Set of guidelines determines whether the field is fit to
serve as a candidate key. A field cannot be designated as a candidate key if it fails to
conform to any of these elements.
4.8.1 Elements of a Candidate Key
It cannot be a multipart field. Usage of one field as an identifier is a bad idea. It should
not contain null values because a null value represents the absence of a
value
Optional value is not allowed in completely or in part. An optional value may be
null at some point.
It comprises a minimum number of fields necessary to define uniqueness.
Combination of fields can be used as a candidate key, so long as each field
contributes to defining a unique value.
Its values must be uniquely identify each record in the table. It protects us against
duplicate records.
Its value must exclusively identify the value of each field within a given record.
With this, the table’s candidate keys give the only means of identifying each field
value within the record.
Only in rare cases its value can be modified.
Example 3:
In following figure we probably identified Registration No., NAME, Address, Branch and
City as potential candidate keys. But, we have to examine these fields more closely to
determine which ones are truly eligible to become candidate keys.
4.8.6 Non-keys
A non-key is a field that does not act as a candidate, primary, alternate, or foreign key. Its
sole purpose is to represent a characteristic of the table’s subject. Its value is determined
by the primary key. There is no particular designation for a non-key, so it is not marked in
the table structure.
4.9 CONSTRAINTS ON NULL
A null represents a missing or unknown value. A null does not represent a zero or a text
string of one or more blank spaces. The reasons are quite simple.
A zero can have a very wide variety of meanings. It can represent the state of an account
balance, the number of available product in a stock.
Although a text string of one or more blank spaces is guaranteed to be meaningless to
most of us.
A zero-length string two consecutive single quotes with no space in between (‘’) is also an
acceptable value to languages such as SQL.
4.9.1 The Value of Nulls
Missing values in a database are commonly the result of human error. Unknown values
appear in a table for a variety of reasons. One reason may be that a specific value needed
for a field is yet not defined. Each null in the Sate Code field shows a missing or unknown
Sate Code for the record in which it appears.
4.9.2 The Problem with Nulls
Nulls adversely effect mathematical operations. An operation involving a null evaluates to
null. If a number is unknown then the result of the operation is obviously unknown.
Following examples demon sate outcome of the operation with nulls :
(20 x 3) + 7 = 67
(Null x 7) + 8 = Null
(20 x Null) + 14 = Null
(23x 4) + Null = Null
Example 7 :
The Product table in following figure illustrates the effects of null values on mathematical
expressions. The value for the Total Value field is derived from the mathematical
expression “[Price] x [Qty on Hand]”. Value for the Total Value field is missing where the
Qty on Hand value is null, resulting in a null value for the Total Value field as well. This
leads to a serious undetected error that occurs when all the values in the Total Value field
are added together: an inaccurate total. The only way to avoid this problem is to ensure
that the values for the Qty on Hand field cannot be null.
4.10 DATA INTEGRITY
Data integrity refers to the validity, consistency, and accuracy of the data in a database.
There are four types of data integrity. The following is a brief description of each:
1. Table-level integrity (known as entity integrity) ensures that there are no duplicate
records within the table and that the field that identifies each record within the table is
unique and never null.
2. Field-level integrity ( known as domain integrity) ensures that the values in each field
are valid, consistent, and accurate; and that fields of the same type (such as NAME fields)
are consistently defined throughout the database.
3. Relationship-level integrity (known as referential integrity) ensures that the records in
the tables are synchronized whenever data is entered into, updated in, or deleted from
either table.
4. Business rules impose restrictions or limitations on certain aspects of a database based
on the ways an organization perceives and uses its data. 4.11 DOMAIN INTEGRITY
An integrity constraint that determines the range of possible values for a domain.field
specification represents all the elements of a field. This type of data integrity warrants the
following: the identity and purpose of a field is clear and all of the tables in which it
appears are properly identified; field definitions are consistent throughout the database;
the values of a field are consistent and valid; and the types of modifications, comparisons,
and operations that can be applied to the values in the field are clearly identified. Each
field specification incorporates three types of elements: general, physical, and logical.
General elements constitute the most fundamental information about the field and include
items such as Field Name, Description, and Parent Table.
Physical elements determine how a field is built and how it is represented to the person
using it. This category includes items such as Data Type, Length, and Display Format.
Logical elements describe the values stored in a field and include items such as Required
Value, Range of Values, and Default Value.
4.12 ENTITY INTEGRITY
Definition
No prime attribute of a relation may hold a null value
Entity constraints ensure the integrity of the entities being modeled by the system. Entity
integrity is an integrity rule which states that every table must have a primary key and that
the column or columns chosen to be the primary key should be unique and not null. If
each value of a primary key must be distinct, no duplicate rows can logically appear in a
table.
Example 8:
Let Account (AccountNo, Name, Type of Account, Amount) with a primary key
AccountNo be a relation in a bank database. Following figure shows its possible instance.
According to definition, NULL value of primary key is not allowed therefore marked row
cannot be recorded into a database.
4.13 Referential Integrity
Referential Integrity ensures the integrity of relationships between primary and foreign
key values in related tables. In a relation between two tables, one table has a primary key
and the other a foreign key. The primary key uniquely identifies each record in the first
table. There can be only one record in the first table with the same primary key value. The
foreign key is placed into the second table in the relationship such that the foreign key
contains a copy of the primary key value from the record in the related table.
Primary and foreign keys are both constraints. A constraint is a piece of metadata (data
catalog) defined for a table defining restrictions on values. A primary key constraint forces
the primary key field to be unique.
The integrity constraints that ensure that relationships between entities remain valid. No
record in the foreign table can contain a foreign key that doesn’t match a record in the
primary table.
Referencing (or referential) foreign key constraints can be in any table, including the same
table as the primary key constrained field referenced by the foreign key (a self join). A
foreign key constraint uses its reference to refer back to a referenced table, containing the
primary key constraint, to ensure that the two values in the primary key field and foreign
key field match.
It allows us cascading update where records in a foreign table are updated automatically
when the corresponding record in the primary table is changed. There are some specific
circumstances to consider in terms of how Referential Integrity is generally enforced:
A primary key table is assumed to be a parent table and a foreign key table a child table.
When adding a new record to a child table, if a foreign key value is entered, it must exist
in the related primary key field of the parent table.
Foreign key fields can contain NULL values. Primary key field values can never contain
NULL values as they are required to be unique.
When changing a record in a parent table if the primary key is changed, the change must
be cascaded to all foreign key valued records in any related child tables.
When changing a record in a child table, a change to a foreign key requires that a related
primary key must be checked for existence, or changed first. If a foreign key is changed to
NULL, no primary key is required. If the foreign key is changed to a non-NULL value, the
foreign key value must exist as a primary key value in the related parent table.
When deleting a parent table record then related foreign key records in child tables must
either be cascade deleted or deleted from child tables first. 4.14 RELATIONAL
ALGEBRA
The relational algebra is a set of eight operators. Each operator takes one or more relations
as input and produces one relation as output. The three main operators of the algebra are
restrict, project and join. Using these three operators most of the manipulation required of
relational systems can be accomplished.
The additional operators – product, union, intersection, difference and division are
modeled on the traditional operators of set theory. There is no standard syntax for the
operators of the relational algebra.
Relational Algebra operations :
select(σ),
project(π),
cross product(×),
union( ),
intersection( ),
difference(—),
join ( )
4.14.1 Restrict
Restrict( select) is an operator which takes one relation as input and produces a single
relation as output. Restrict can be considered a ‘horizontal slicer’ in that it extracts rows
from the input relation matching a given condition and passes them to the output relation.
It is also known as selection operator.It is denoted by a symbol sigma (σ). The notation T
where c orσc(T) is used, where T is a table expression, c is a condition. The selection
operation can use any of the comparison operations (=, !=, <=, <, >=, >).
Syntax for the restrict operator is as follows:
RESTRICT <table name> [WHERE <condition>] ’!<result table>
Example 9:
In the following figure, only those rows are extracted from table product where
Qty on Hand is greater than 10.
Example 10:
To select all rows from product relation/ table where Qty on hand getaer than
10, we can write same as:
σ Qty on hand > 10 ( Product )
4.14.2 Project
The project operator takes a single relation as input and produces a single relation
as output. Project is a ‘vertical slicer’ in that it produces in the output relation a subset of
the columns in the input relation. It is denotedby symbol pi (π). We can represent the
projection operation by T[c1, c2, …], Where T is a table expression and [c1, c2, …] is a
column list, also called a projection list.
Syntax for the project operator is as follows:
PROJECT <table name> [<column list>]<result table>
Example 11:
In the following figure, only three columns (Product ID, Product Name, Price)
are extracted from table product.
Example 12:
To see three fields ( Product ID, Product Name, price) , we can write as:
π product ID,Product Name,Price (Product)
Another example Projection operator
π Product Name(σ Price >1000(student))
4.14.3 Product
Joins are based on the relational operator product, a direct analogue of an operator in set
theory known as the Cartesian product. It is denoted by a symbol cross (x). Product takes
two relations as input and produces as output one relation composed of all the possible
combinations of input tuples/rows. Product is a little-used operator in practice because of
its potential for generating an ‘information explosion’.
Syntax of the product operator is given below:
PRODUCT <table 1> WITH <table 2><result table>
Example13:
PRODUCT Teacher WITH Subject R
In the following figure we have two relation Teacher and Subject.
The output of this product have all combination of tuples/rows of both relations/ tables.
We get a relation of six tuples with six attributes.
4.14.4 Equi-Join
The join operator takes two relations as input and produces one relation as output.
In Equi-Join two tables are combined together but only for records where the values
match in the join columns of two tables. The equi-join operator is a product with an
associated restrict. We shall assume that the primary key of one table and the foreign
key of the other table form the default join columns.
Syntax is:
EQUIJOIN <table1> WITH <table2><result table>
Example 14:
EQUIJOIN Teacher WITH Module R
Here we have joined Teacher and Module, but only produced a row in R where a Teacher
table TeacherID value matches a module table TeacherID value.
Note that although Manoj Kumar appears in both the Teacher and Administrator table, he
only appears once in R. This is because, since R is a relation, it cannot have duplicate
rows.
4.14.7 Intersection
Intersection is fundamentally the opposite of union. Whereas union produces the
combination of two sets or tables, intersection produces a result table which contains rows
common to both input tables.
Syntax of Intersection is:
<table 1> INTERSECTION <table 2><result table>
Example 17:
Lecturers INTERSECTION Administrators R
It give us rows, those are common in lecturer and administrator tables.
4.14.8 Difference
In most operators of the relational algebra, the order of specifying input relations is
insignificant. A union of table 1 with table 2, for instance, is exactly the same as a union of
table 2 with table 1. Using difference, in contrast, the order of specifying the input tables
does matter.
Example 18:
Teacher DIFFERENCE Administrator R
will produce all Teachers who are not administrators
Teacher ID Teacher Name
102 Aman Kumar
103 Nigam
Designation Sr. Lecturer Lecturer
Administrator DIFFERENCE Teacher R will show rows from administrator table who
are not Teachers
4.14.9 Division
Division or divide takes two tables as input and produces one table as output.
One of the input tables must be a binary table (i.e. a table with two columns). The other
input table must be a unary table (i.e. a table with one column). The unary table must
also be defined on the same domain as one of the columns in the binary table. The
fundamental idea of division is that we take the values of the unary table and check
them off against the associated column in the binary table. Whenever all the values in
the unary table match with the same value in the binary table then we output a value to
the output table.
Example 19:
Suppose that we maintain a table( ModuleDay) with a list of days on which
particular modules are taught:
We might want to find a common date on which both Introduction to DBMS and
Programming in C are taught. Hence, our unary table (PairedModule) would be:
Obtain the regID of students who got more than 800 marks π regID(student) – π regID(σ
marksObt > 800 (admission))
Obtain the department Ids for departments with no lady teacher π deptID (department) – π
deptID(σ gender = ‘F’(teacher))
Obtain the regID of male students who have obtained at least 800 marks πregID(σ gender =
‘M’(student)) )” π regID(σ marksObt >= 800(admission))
REVIEW QUESTION
Chapter 5
NORMALIZATION
The rule,
which seems quite obvious, says if I give you the combination <Sachin, Amritsar>, what
is this person’s Name? What is this person’s City?
5.2.3 The Augmentation Rule
If X Y, then XZ Y. You might call this rule, “more information is not really needed,
but it doesn’t hurt.”
5.2.4 The Decomposition Rule
The decomposition rule says that if it is given that X YZ (that is, X defines both
Y and Z), then X Y and X Z.
5.2.5 The Union Rule
The union rule is the reverse of the decomposition rule in that if X Y and X
Z, then X YZ.
5.2.6 Full functional dependence
Some times X determines Y, but X combined with Z does not determine Y. Y
depends on X and X alone. If Y depends on X with anything else, there is not full
functional
dependence. Essentially X, the determinant, cannot be a composite key. A composite
key contains more than one field (the equivalent of X with Z).
5.2.7 Multiple valued dependency
Not all dependencies can be modeled in terms of functions. Y is said to be nonfunctionally
dependent on data-item X if for every value of data-item X there is a
delimited set of values for data-item Y. This is also known as a non-functional
dependency.
A commonly used example of a multi-valued dependency is a field containing a
commadelimited list or collection of some kind. A collection could be an array of values
of the
same type. Those multiple values are dependent as a whole on the primary key, as a
whole meaning the entire collection in the comma delimited list. A trivial multi-valued
dependency occurs between two fields when they are the only two fields in the table.
5.3 THE CONCEPT OF ANOMALIES
The motive of relational database theory is to remove anomalies from occurring in a
database. Anomalies can occur during changes to a database. Due to anomaly, data can
become logically corrupted. An anomaly with respect to relational database design is
essentially an erroneous change to data, more specifically to a single record. There are
mainly three types of anomalies that can corrupt data
5.3.1 Insert anomaly
Insert anomaly occurs when a record is inserted to a detail table, with no related record
existing in a master table. Addition of a new subject in detail table (see following figure)
requires that the teacher should be added first in master table, assuming, that the teacher
does not already exist.
A given cell of the table for the attributes StudentID, StudentName and MarksObt have
multiple values. In above table StudentID, StudentName and MarksObt all repeat with
respect to SubjectName. The attributes StudentID, StudentName and MarksObt are clearly
not functionally dependent on the primary key SubjectName. The attributes TeacherID and
TeacherName clearly are. This means that we have to form two tables: one for the
functionally dependent attributes, and one for the non-dependent attributes. SubjectName
and StudentID are declared as primary key of this second table Results.
The two candidate keys in this example are (SupplierID, ProductID) and ( SupplierName,
ProductID) , and the functional dependency is illustrated in following figure.
So there is a functional dependency {SupplierID} { SupplierName}, which is in
violation of BCNF . A write model of BCNF is shown in following figures.
Chapter 6
DATABASE ACCESS AND SECURITY
Chapter 7
SQL USING ORACLE
7.1 Introduction to SQL
SQL, pronounced “sequel,” is an acronym for Structured Query Language. A standards
body called ANSI, the American National Standards Institute, maintains this language.
SQL is a powerful query language that was created as a means to communicate with
databases. Databases store data. SQL can be used to view, manipulate, and create this data.
It can even define the structures that will hold the data. Because SQL is a standards-
controlled language, it is reusable from database to database.
What are the advantages of SQL?
1. SQL is not a proprietary language used by specific database vendors. Almost
every major DBMS supports SQL, so learning this one language will enable you
to interact with just about every database you’ll run into.
2. SQL is easy to learn. The statements are all made up of descriptive English words,
and there aren’t that many of them.
3. Despite its apparent simplicity, SQL is actually a very powerful language, and
by cleverly using its language elements you can perform very complex and
sophisticated database operations.
7.2 SQL Tools
Oracle has provided a user-friendly interactive tool for running SQL since its first release.
The SQL*Plus tool today has four variations from which to choose:
SQL*Plus Command Line. Use this when you don’t have a Windows interface, such as
when using telnet to reach a remote UNIX database server.
SQL*Plus Windows. Use this in a Windows-capable environment (can be invoked using a
network name from a client or directly on the database server, regardless of the operating
system).
SQL*Plus Worksheet. This comes as part of Oracle Enterprise Manager, a Windows-like
user interface created to support the database administrator and simplify many tasks.
iSQL*Plus. This gives you the same interface as SQL*Plus Windows, except it runs in a
Web browser. Use this to run SQL commands and automatically generate a report in
HTML format.
7.3 Data Definition Languages
7.3.1 Creating and Modifying Table Structure
There are generally two ways to create database tables:
Most DBMSs come with an administration tool that can be used to create and manage
database tables interactively.
Tables may also be manipulated directly with SQL statements.
A named schema object defined by a table definition in a CREATE TABLE statement.
Persistent base tables hold the SQL data that is stored in your database. Syntax of Create
Table:
CREATE TABLE tablename (colunname1 colunname2 datatype(size), datatype(size),
…………………………..
colunnamen datatype(size));
Column Data Types
Whenever you define a column in a CREATE TABLE statement, you must, at the very
least, provide a name for the column and an associated data type or domain. The data type
or domain (discussed in Chapter 4) restricts the values that can be entered into that
column. For example, some data types limit a column’s values to numbers, while other
data types allow any character to be entered.
Data Type Description
CHARACTER Specifies the exact number of characters that will be stored for each value.
For example, if we define the number of characters as 15, but the value contains only 10
characters, the remaining five characters will be spaces. The data type can be abbreviated
as CHAR.Example: STUDENT_NAME CHAR(40)
VARYING
CHARACTER
INTEGER
NUMBER
DATE
BOOLEAN
LONG Specifies the maximum number of characters that can be included in a value. The
number of characters stored is exactly the same number as the value entered, so no spaces
are added to the value. For example, if we define the number of characters as 25, but the
value contains only 15 characters, the remaining ten characters space can be saved. The
data type can be abbreviated VARCHAR2.Example: STUDENT_NAME
VARCHAR2(40)
Only integers are accepted. Any parameters with this data type are not specified. It is
abbreviated as INT.Example: PRODUCT_ID INT
It is used to store numbers( fixed or floating). It specifies the precision and the scale of a
numeric value. Only the precision can be specified. Numbers of any magnitude may be
stored up to 38 digits of precision. If precision is omitted values are stored upto maximum
of 38 digits. Example: COST NUMBER(7,2)
This data type is used to represent date and time. It specifies the year, month, and day
value of a date. Date format to represented as DDMON-YY as in 27-MAY-99. Some time
the year is four digits and supports the values 0001 through 9999; the month is two digits
and supports the values 01 through 12; and the day is two digits and supports the values 01
through 31. Time specifies the hour, minute, and second values of a time.Example:
DATE_OF_BIRTH DATE
The Boolean data type is very simple and easy to apply. The data type holds only three
values: true, false, or unknown. A null value valuates to unknown. In Boolean
comparisons, true is greater than false and a comparison involving an unknown (null)
value will return an unknown result.Example: ALLOWED BOOLEAN
This data type is used to store variable length character strings up to 2GB.
Example : Create a table student with following structure:
Column Name
RollNo
Name
DOB
Address
City
Phone
Sol:
CREATE TABLE Student
Data Type Size
Number 4 Character 20 Date
Character 50 Character 15 Number 13
( Rollno number(4) ,
Name varchar2(20),
DOB date,
Address varchar2(50), City char(15), Phone number(13)
);
Example: Create a table Staff with following structure: Column Name
StaffID
Name
DOB
Designation
Department Address
City
Phone
Data Type Size Number 4 Character 20 Date
Character 15 Character 15 Character 50 Character 15 Number 13 Sol:
CREATE TABLE Staff (
StaffID number(4) , Name varcha2r(20), DOB
Designation Department Address
City
Phone
);
date,
varchar2(15), varchar2(15), varchar2(50), char(15),
number(13)
Example : Create a table student_result with following structure:
Column Name Data Type Size RollNo Number 4
Semester Number 1
Marksobt Number 4
Maxmarks Number 4
Remarks Character 15
Sol:
CREATE TABLE Student_result
(
Rollno number(4) ,
Semester number(1) , Marksobt number(4) , Maxmarks number(4) , Remarks char(15));
Creating table with Primary Key or NULL values
A constraint is an option that further defines a table or a column. It will either add more
information to or put certain restrictions on the table or column. The first constraint is
NULL or NOT NULL. This allows you to specify whether or not a column accepts NULL
values. If a column is defined as NOT NULL, some value has to be assigned to that
column or else the database will produce an error. There are also constraints available that
will define primary keys and foreign key relationships. Using these while creating tables
will enable your database to enforce referential integrity. Using the PRIMARY KEY
constraint after a column will designate that column, and that column alone, as the
primary key.
Example : Create a table Staff with Primary Key and NULL values:
Sol:
CREATE TABLE Staff
(
StaffID
Name
DOB
Designation Department Address
City
Phone
);
number(4)
varchar2(20) date
varchar2(15) varchar2(15) varchar2(50), char(15),
char(13)
PRIMARY KEY, NOT NULL,
NOT NULL, NOT NULL,
NOT NULL,
Example : Create a table product_info with Primary Key and NOT NULL Constraints as
per following structure:
Column Name Product_ID
Product_Name Date_of_purchase Qty_on_hand Cost_price
Sell_price
Reorder_limit Specification
Data Type Number
Character Date
Number
Number
Number
Number
Character
Size Constraint
5 PRIMARY KEY
20 NOT NULL
6
7,2
7,2
6
100 Sol:
CREATE TABLE product_info (
Product_ID
Product_Name Date_of_purchase Qty_on_hand Cost_price
Sell_price
Reorder_limit Specification
);
number(5) varchar(20) date,
number(6), number(7,2), number(7,2), number(6), varchar(100) PRIMARY KEY, NOT
NULL,
Exercise: Insert Following data into product_info table
Example: Use
of Commit Statement
Sol:
DELETE OrderItem WHERE Order_no = 132; DELETE Order WHERE order_no = 132;
COMMIT;
Example: undone performed DELETE operation. Sol:
DELETE FROM Staff; ROLLBACK;
Short Answer type Question
1. SQL stands for………………
2. ……………….. statement is used to form a new table.
3. ……………..statement is used to change the name of a table
4. To add record(s) to a table ……………. statement is used.
5. DDL stands for…………..
6. DML stands for……………..
7. NULL operator tests for value for…………..
8. A table may have multiple primary keys
9. DROP COLUMN statement is used to create a new column
10. ALTER TABLE and CREATE TABLE are same statements
11. The SELECT statement is a way to view the data
12. SQL is a procedural language.
13. Self-join joins a table to itself.
14. A subquery within a subquery is called nested query
15. View and table are same.
Long Answer type Question
1. Write various SQL Tools.
2. Explain various Data Types
(True/ False) (True/ False) (True/ False) (True/ False) (True/ False) (True/ False) (True/
False) (True/ False)
3. How can you create tables with Primary Key or NOT NULL values.
4. Explain Modification of tables Structure with examples.
5. How can you retrieve Data from Tables
6. Write various conditional operator.
7. What is difference between IN and BETWEEN operator.
8. Explain Order By, Group By, Having Clause.
9. Explain Aggregate Functions, Numeric Functions and String Functions
10. How can join tables using SQL?
11. What is sub query?
12. How can you update data using SQL?
13. Write short note on following:
i. Trigger ii. View
iii. Index iv. Commit
v. Rollback vi. Transaction
Chapter 8
INTRODUCTION TO PL/SQL
related to SQL. PL/SQL is a programming language in its own right; it has its own syntax,
its own rules, and its own compiler.
Oracle’s PL/SQL language has several defining characteristics: It is a highly structured,
readable, and accessible language.
It is a standard and portable language for Oracle development. It is an embedded
language.PL/SQL was not designed to be used as a
standalone language, but instead to be invoked from within a host environment.
It is a high-performance, highly integrated database language.
8.1.1 Advantages of PL/SQL
PL/SQL is tightly integrated with SQL. With PL/SQL, you can use all SQL data
manipulation, cursor control, and transaction control statements, and all SQL functions,
operators, and pseudo columns.PL/SQL fully supports SQL data types. You need not
convert between PL/SQL and SQL data types. For example, if your PL/SQL program
retrieves a value from a database column of the SQL type VARCHAR2, it can store that
value in a PL/SQL variable of the type VARCHAR2.
Branching, conditional checking and looping is possible in PL/SQL.
Entire block of PL/SQL program is sent to RDBMS engine in single step. This can
drastically reduce network traffic between the database and an application. A user can use
PL/SQL blocks and subprograms (procedures and functions) to group SQL statements
before sending them to the database for execution.
PL/SQL also deals with error generated during execution of code. With PL/SQL user
friendly messages can be displayed.
We can declare variables in PL/SQL blocks of code. These variables are used to store
results of a query.
PL/SQL is also used to perform different kind of calculation without using RDBMS
engine.
PL/SQL stored subprograms move application code from the client to the server, where
user can protect it from tampering, hide the internal details, and restrict who has access.
Applications written in PL/SQL can run on any operating system and platform where the
database runs.
8.1.2 SQL*Plus
SQL*Plus is an interactive program that allows you to type in and execute SQL
statements. It also enables you to type in PL/SQL code and send it to the server to be
executed. SQL*Plus is one of the most common front ends used to develop and create
stored PL/SQL procedures and functions.
What happens when you run SQL*Plus and type in a SQL statement? Where does the
processing take place? What exactly does SQL*Plus do, and what does the database do? If
you are in a Windows environment and you have a database server somewhere on the
network, the following things happen:
1. SQL*Plus transmits your SQL query over the network to the database server.
2. SQL*Plus waits for a reply from the database server.
3. The database server executes the query and transmits the results back to SQL*Plus.
4. SQL*Plus displays the query results on your computer screen.
The important thing is that SQL*Plus does not execute your SQL queries. SQL*Plus also
does not execute your PL/SQL code. SQL*Plus simply serves as your window into the
Oracle database, which is where the real action takes place.
8.2 PL/SQL Block Structure
The smallest meaningful grouping of code is known as a block. A block is a unit of code
that provides execution and scoping boundaries for variable declarations and exception
handling. PL/SQL allows us to create without name blocks and named blocks, which are
either procedures or functions. A PL/SQL block has up to four different sections.
Header: Used only for named blocks. The header determines the way the named block or
program must be called. It is optional.
Declaration section: Identifies, variables, cursors, and other objects are declared in this
section those are referenced in the execution and exception sections. It is optional
Example:
DECLARE fname lname
cost
VARCHAR2(30); VARCHAR2(30); NUMBER := 0;
Execution section : This section contains executable statements (SQL and PL/ SQL) that
allow user to manipulate the variables that have been declared in the declaration section. It
is compulsory section.
Example 1:
BEGIN
SELECT firstname, lastname
INTO fname, lname
FROM student
WHERE studentID = 163;
DBMS_OUTPUT.PUT_LINE (‘Student name: ‘||fname|| ‘ ‘||lname); END;
Exception section : This section contains statements that are executed when a runtime
error occurs within the block. Errors can occur due to syntax, logic or validation rule
violation. It is optional section.
Example 2:
BEGIN
SELECT tname, lastname
INTO fname, lname
FROM Student
WHERE studentID = 163;
DBMS_OUTPUT.PUT_LINE (‘Student name: ‘||fname|| ‘ ‘||lname); EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE (‘ no student found with ‘|| ‘Student ID163’); END;
8.3 The PL/SQL Character Set
A PL/SQL program made of a several statements. The precise characters available to
uswill depend on what database character set we are using. For example, following table
illustrates the available characters:
Type Characters
Letters A-Z, a-z
Digits 0-9
Symbols ~ ! @ # $ % * ( ) _ - + = | : ; “ ‘ < > , . ? / ^
Whitespace Tab, space, newline, carriage return
Characters are grouped together into lexical units, also called atomics of the language
because they are the smallest individual components. A lexical unit in PL/ SQL is any of
the following:
Identifier
Literal
Delimiter
Comment
8.4 PL/SQL Terminology
PL/SQL handles with the database and with the procedural world. Here are a few concepts
and terms we want to know.
Keyword: This book uses the term keyword to mean a word that the language recognizes.
In PL/SQL, keywords include BEGIN, END, IF, and RETURN.
Identifier: An identifier is a name for a PL/SQL object, including any of the following:
Constant or variable
Exception
Cursor
Program name: procedure, function, package, object type, trigger, etc. Reserved word
Label
Default properties of PL/SQL identifiers are summarized below:
Up to 30 characters in length
Must start with a letter
Can include $ (dollar sign), _ (underscore), and # (pound sign) Cannot contain any
“whitespace” characters
Some examples of invented identifiers: Total_balance, Total_Cost.
Datatype : A name for a class of values. PL/SQL’s built-in datatypes include NUMBER,
DATE, and VARCHAR2 .
Variable: Variables are named temporary storage locations that support a particular data
type in your PL/SQL program. Some variables can hold only a single thing, like the
number of people who live in Portugal, and some can hold a list of things, like the birth
dates of my family members.
Variable Naming
Like a SQL or database data type, PL/SQL variables must follow the identifier naming
rules:
• A variable name must be less than 31 characters in length.
• A variable name must start with an uppercase or lowercase ASCII letter: A–Z or a–z.
PL/SQL is not case-sensitive.
• A variable name may be composed of 1 letter, followed by up to 29 letters, numbers, or
the underscore (_) character. You can also use the number (#) and dollar sign ($)
characters.
Declaring, declaration, declaration section: Declaring a variable means naming it and
defining its datatype. With few exceptions, variables must be declared prior to use. In
PL/SQL, these designations most often occur in a separate section of the program called
the declaration section. Declarations are not, strictly speaking, “statements” themselves.
String: Some amount of textual data—that is, characters, words, spaces, punctuation, and
sometimes numerals. A string can contain zero, one, or more individual characters. String
values can be stored in variables with the appropriate datatype, such as VARCHAR2.
String values are bounded by single quotes, as in ‘Hello Everybody’.
NULL :A special value that represents the absence of a real value. Let’s further define
NULL:
• NULL is not equal to anything, not even NULL.
• NULL is not less than or greater than anything else, not even NULL.
• NULL means nothing knows, not even NULL.
Boolean : A class of variables and commands for working with the “truth values” of true
and false. Oracle Booleans, which are available in PL/SQL but not SQL, actually have
three possible values, TRUE, FALSE, and NULL.
Literal : A literal is a value that is not represented by an identifier; it is simply a value..
Literals may be string, numeric, or Boolean values. Examples: 106700, TRUE, ‘ Ajit
Singh’
Expression : A formula that evaluates some value at runtime based on one or more other
values. Examples: b + c, NOT done.
Operator : A character or phrase that the language uses to represent some particular
arithmetic, logical, or other function. Examples: +, -, AND, BETWEEN, :=.
Statement: A programmatic instruction to the computer to do something. Every statement
is composed of up to five main elements: literal values, keywords, programmersupplied
identifiers, operators, and a mandatory terminator. Some statements such as IF-THEN-
ELSE incorporate other statements inside them.
Terminator: A special character that you must put after each complete statement and each
declaration. In PL/SQL, the terminator is the semi-colon (;). The terminator announces
“okay, I’m through with this part.” It’s important to realize that the terminator goes only at
the very end of the entire statement, and that the statement may span several lines in the
file.
Block: A sequence of code that includes executable statements and that is bounded by
certain keywords. Virtually all PL/SQL programs incorporate one or more blocks, and
every block encloses one or more statements. Blocks can even be nested inside one
another.
8.5 PL/SQL Input and Output
Most PL/SQL input and output (I/O) is through SQL statements that store data in database
tables or query those tables. All other PL/SQL I/O is done through APIs, such as the
PL/SQL package DBMS_OUTPUT.
DBMS_OUTPUT: Is a collection of procedure and functions, used to collect data in a
system buffer. This data can be retrieve later on. The DBMS_OUTPUT package enables
us to send messages from stored procedures, packages, and triggers.
PUT_LINE: PUT_LINE procedures in this package enable a user to place information in a
buffer that can be read by another trigger, procedure, or package.
Writing first PL/SQL Program
BEGIN
DBMS_OUTPUT.PUT_LINE(‘Hello Everybody’);
END;
This is called an anonymous block, a block with no name. only one statement is
executabled by calling a procedure PUT_LINE, supplied in Oracle’s built-in package
named DBMS_OUTPUT. PUT_LINE is used to print message or data.
Entering PL/SQL Statements into SQL*Plus
SQL> BEGIN
2 DBMS_OUTPUT.PUT_LINE(‘Hello Everybody’);
3 END;
4/
Hello Everybody
PL/SQL procedure successfully completed.
8.6 Common Operators
An operator is a symbol or keyword that the language provides to perform an arithmetic,
logical, or other function . Following table shows common PL/SQL operators Operator
Category
Assignment Arithmetic
Logical
Comparison (of non-nulls)
Comparison (of nulls)
String
Notation Meaning Example
:=
+
-
*
/
**
AND
OR
NOT
=
!=
<
>
<=
>=
IN
BETWEEN
IS NULL
IS NOT NULL
LIKE
Store the value
Addition
Subtraction
Multiplication
Division
Exponentiation
Conjunction
Disjunction
Negation
Equality
Inequality
Less than
Greater than
Less than or equal Greater than or equal Equality disjunction Range test
Nullity test
Non-nullity test
Matching wildcard
|| Concatenation C := b;
c := a + b;
c := a - b;
c := a * b;
c := a / b;
c := a ** b;
a AND b
a OR b
a NOT b
b=c
b!=c
b<c
b>c
b <= c
b >= c
b IN (a, c [, d, … ] )
b BETWEEN a AND c
a IS NULL
a IS NOT NULL
IF student_name LIKE ‘Su%’
name := ‘Ajit ‘ || ‘Singh’;
8.7 Conditional and Sequential Control
8.7.1 IF Statements
The IF statement allows us to design conditional logic into programs. For example take a
following case where we have to decide when one is to be executed.
If the salary is between ten and twenty thousand, then apply a bonus of Rs1,500. If the
salary is between twenty and forty thousand, apply a bonus of Rs1,000. If the salary is
over forty thousand, give the employee a bonus of Rs500.
Some constructs are required in our programming language so that they can respond to all
sorts of situations and requirements, including conditional behavior, such as: “if a is true,
then do b, otherwise do c.”
PL/SQL supports conditional logic with the IF statement:
IF condition THEN Statement 1;
……………
………….….
Statement N;
END IF;
When an IF-THEN statement is executed, a condition is evaluated to either TRUE or
FALSE. If the value of condition is TRUE, control is transferred to the first executable
statement of the IF-THEN construct. If the value of condition is to FALSE, control is
passed to the first executable statement after the END IF statement.
Example 3:
DECLARE
num1 NUMBER := 15;
num2 NUMBER := 10;
temp NUMBER;
BEGIN
IF num1 > num2 THEN
temp := num1;
num1 := num2;
num2 := temp;
END IF;
DBMS_OUTPUT.PUT_LINE (‘num1 = ‘||num1);
DBMS_OUTPUT.PUT_LINE (‘num2 = ‘||num2);
END;
8.7.2 IF-THEN-ELSE Statement
IF-THEN-ELSE format is used when we want to choose between two mutually exclusive
actions. An IF-THEN-ELSE statement allows us to specify two groups of statements.
When the value of condition is TRUE, first group of statements is executed. When the
condition evaluates to FALSE another group of statements is executed. This is shown as
follows:
IF condition THEN
statement 1;
ELSE
statement 2;
END IF;
statement 3;
When the value of condition is TRUE, control is passed to statement 1; when the value of
condition is FALSE, control is transferred to statement 2; After the IFTHEN-ELSE
construct has completed, statement 3; is executed
Example 4:
DECLARE
num1 NUMBER := 15;
num2 NUMBER := 10;
BEGIN
IF num1 > num2 THEN
DBMS_OUTPUT.PUT_LINE (‘ Greater = ‘||num1); ELSE
DBMS_OUTPUT.PUT_LINE (‘ Greater = ‘||num2);
END IF;
END;
8.7.3 ELSIF Statements
An ELSIF statement has the following structure:
IF condition1 THEN
Statement1;
ELSIF condition2 THEN
statements 2;
ELSIF condition THEN
Statements 3;
……………
ELSE
last_statement;
END IF;
Example 5:
DECLARE
num NUMBER := &inputnum;
BEGIN
IF num < 0 THEN
DBMS_OUTPUT.PUT_LINE (num||’ is a negative number’);
ELSIF num = 0 THEN
DBMS_OUTPUT.PUT_LINE (num||’ is equal to zero’);
ELSE
DBMS_OUTPUT.PUT_LINE (num||’ is a positive number’); END IF;
END;
8.7.4 CASE Statements
CASE statement is an understandable and efficient alternative to a long series of
IF tests on the same expression. There are two forms of the CASE statement: simple and
searched. Syntax of the so-called simple CASE statement is:
CASE selector
WHEN expression1 THEN statement1;
WHEN expression2 THEN statements2;
…
WHEN expression m THEN statement m; ELSE statement m+1;
END CASE;
Example 6:
DECLARE
num NUMBER := &input_num; num2 NUMBER;
BEGIN
Num2 := MOD(num,2);
CASE num2
WHEN 0 THEN
DBMS_OUTPUT.PUT_LINE (num||’ is an even number’); ELSE
DBMS_OUTPUT.PUT_LINE (num||’ is an odd number’); END CASE;
DBMS_OUTPUT.PUT_LINE (‘Good Bye’);
END;
8.8 Looping using PL/SQL
When a statement or group of statements is executed several times, is called looping. In
PL/SQL, there are four types of loops simple loops, WHILE loops, numeric FOR loops,
and cursor FOR loops. While there are differences among the three loop constructs, every
loop has two parts: the loop boundary and the loop body:
Loop boundary: This is composed of the reserved words that initiate the loop, the
condition that causes the loop to terminate, and the END LOOP statement that ends the
loop.
Loop body: This is the sequence of executable statements inside the loop boundary that
execute on each iteration of the loop.
8.8.1 Simple (Infinite) Loop
This loop has simplest loop structure. This is also called an infinite loop. It has the
following syntax:
LOOP
statement 1;
statement 2;
…………….
………….
statement n;
END LOOP;
The EXIT statement is used to terminate a loop when the EXIT condition evaluates to
TRUE. An IF statement is used to evaluated EXIT condition. No it will not be an infinite
loop. It has the following syntax:
LOOP
Statement1;
Statement2;
IF Condition THEN
EXIT;
END IF;
END LOOP;
8.8.2 WHILE Loops
The WHILE loop executes as long as the mentioned Boolean condition evaluates to
TRUE. It has the following syntax:
WHILE condition LOOP
statement 1;
statement 2;
………………
statement n;
END LOOP;
The reserved word WHILE is used to start a loop construct. Then condition is evaluated to
TRUE or FALSE. The result of evaluation decides whether the loop is executed or not.
Statements 1 through n, are executed repeatedly. The END LOOP is a reserved phrase
used to terminate loop construct.
Example 7: Print numbers from 1 to 10
DECLARE
counter NUMBER := 1;
BEGIN
WHILE counter <= 10 LOOP
DBMS_OUTPUT.PUT_LINE (‘ ‘||counter);
counter := counter + 1;
END LOOP;
END;
8.8.3 FOR Loop
A numeric FOR loop is called numeric because it needs an integer value to terminate loop.
The numeric FOR loop is the traditional and familiar “counted” loop. The number of
iterated of the FOR loop is known when the loop starts; it is specified in the range scheme
found between the FOR and LOOP keywords in the boundary. Do not declare the loop
index. PL/SQL automatically and implicitly declares it as a local variable with datatype
INTEGER. It has the following syntax:
FOR loop_counter IN [REVERSE] lowest_number ….highest_number LOOP
statement 1;
statement 2;
…………….
statement n;
END LOOP;
The word FOR indicates the beginning of a FOR loop. loop_counter, is a variable, defines
index variable. This variable is defined by the loop construct. lowest_number and
highest_number are two integer numbers that define the number of repetitions for the
loop. The values of the lowest_number and highest_number are evaluated once, for the
first execution of the loop. It is determined how many times the loop will be repeated.
Statements 1 through N are a sequence of statements that is executed repeatedly. END
LOOP is a reserved phrase that indicates the end of the loop.
Example 8: Print numbers from 1 to 10
BEGIN
FOR counter IN 1..10 LOOP
DBMS_OUTPUT.PUT_LINE (‘ ‘||counter);
END LOOP;
END;
8.9 SQL in PL/SQL
A transaction in Oracle is a series of SQL statements that have been bundled together into
a logical unit.. PL/SQL is tightly coulped with the Oracle database via the SQL language.
From within PL/SQL, a user can execute any Data Manipulation Language statements like
INSERTs, UPDATEs, DELETEs, and, of course, queries.
INSERT statement
We have the syntax of the two basic types of INSERT statements: Inserting a single row
with list of values
INSERT INTO table [(column 1, column 2, …, column n)]
VALUES (value 1, value 2, …, value n);
Inserting one or more rows into a table as received by a SELECT statement against one or
more other tables:
INSERT INTO table [(column 1, column 2, ………….., column n)] AS
SELECT ……..;
Example:
BEGIN
INSERT INTO Staff VALUES(289,’Rajiv’,’7-May-78’,’Lab Astt.’, ’ECE’, ’H. No 75 JP
Nag.’, ’Amritsar’, ’’);
UPDATE statement
One or more columns can be updated in one or more rows using UPDATE. It
has the following syntax:
UPDATE tablename
SET column = val1
[,column2 = val2, … columnN = valN]
[WHERE where clause];
DELETE statement
DELETE is used to remove one, some, or all the rows in a table. It has the
following basic syntax:
DELETE FROM table
[WHERE where-clause];
Example9:
DECLARE
Rollnum NUMBER := 110;
IS
BEGIN
DELETE FROM Student WHERE RollNo = Rollnum;
END;
Variables Initialization with SELECT INTO
SELECT INTO statement is used to initialize variables. It has the following syntax:
SELECT itemname INTO variablename
FROM tablename;
Example10:
DECLARE
studentname VARCHAR2(20);
BEGIN
SELECT Name INTO studentname
FROM student WHERE RollNo = 101;
DBMS_OUTPUT.PUT_LINE(‘The name of student is ‘|| studentname );
9.10 Stored Procedure
SQL acts as the interface to the database. A client program, whether it exists on the same
computer or on another, makes a connection to the database, sends a request in the form of
SQL to the server, and in return gets back structured data,
So a stored procedure is a program that resides inside an Oracle database that manipulates
data in the database before the data is used outside the database. A procedure is a module
performing one or more actions; it does not need to return any values.
Procedure is made up of:
1. A declarative part
2. An executable part
3. An optional exception handling part
Declarative part: It may include the declarations of variables, constants, cursors,
subprograms and exceptions. These are local to procedure and no existence out side a
procedure.
Executable part: this part includes SQL and PL/SQL statements. This block manipulates
data and result is to be returned back to the calling portion.
Exception handling part: PL/SQL provides a feature to handle the Exceptions which occur
in a PL/SQL Block known as exception Handling. Using Exception Handling we can test
the code and avoid it from exiting abruptly. When an exception occurs a messages which
explains its cause is received. When an exception is raised, Oracle searches for an
appropriate exception handler in the exception section.
Use of Stored Procedures
Here is a list of reasons to use stored procedures:
They eliminate the network.
They allow us to more accurately model the real world in database. They provide us with
access to functionality that is not available through the standard database interface: SQL.
Using PL/SQL, you can write stored procedures for the following:
Data processing
Data migration
Entity behavior, including so-called business rules
Interfaces
Reports
The general format of a PL/SQL procedure is as follows:
CREATE OR REPLACE PROCEDURE name
[(parameter[, parameter, …])]
AS
local declarations
BEGIN
executable statements
[EXCEPTION
exception handlers }
END [name];
8.11 Functions
Functions are another type of stored code. They are very similar to procedures.
Function is a PL/SQL block that returns a single value. Because a function returns a
value, it is said to have a datatype and the return value datatype must be declared in the
header of the function. The function does not necessarily have any parameters, but it
must have a RETURN value declared in the header.
Function is made up of:
1. A declarative part
2. An executable part
3. An optional exception handling part
Here are a few more differences between a procedure and a function: A function MUST
return a value
A procedure cannot return a value
Procedures and functions can both return data in OUT and IN OUT parameters
The return statement in a function returns control to the calling program and returns the
results of the function
The return statement of a procedure returns control to the calling program and cannot
return a value
Functions can be called from SQL, procedure cannot
Functions are considered expressions, procedure are not
The syntax for creating a function is:
CREATE [OR REPLACE] FUNCTION function_name (parameter list) RETURN
datatype
IS
BEGIN
<body of the function>
RETURN (return value);
END;
Example11:
CREATE OR REPLACE FUNCTION staff_func
RETURN VARCHAR(20);
IS
staff_name VARCHAR(20);
BEGIN
SELECT Name INTO staff_name
FROM Staff WHERE StaffID = ‘101’;
RETURN staff_name ;
END;
Execution of PL/SQL Function
A function can be executed in the following ways. 1) Since a function returns a value we
can assign it to a variable.
employee_name := staff_func ;
If ‘employee_name’ is of datatype varchar we can store the name of the employee by
assigning the return type of the function to it.
2) As a part of a SELECT statement
SELECT staff_func FROM dual;
3) In a PL/SQL Statements like,
dbms_output.put_line(staff_func);
This line displays the value returned by the function.
Short Answer type question
Fill in the blanks
1. PL/SQL stands for ………….
2. …………. is used to display messages to the user.
3. The EXIT statement causes a loop to …………. when the EXIT condition evaluates to
TRUE.
4. The reserved word WHILE marks the …………. of a loop.
5. DBMS_OUTPUT.PUT_LINE is used to ………….
State True or False
1. SQL statements combined into PL/SQL blocks cause an increase in the network traffic
2. PUT_LINE is one of the procedures from the DBMS_OUTPUT package.
3. DBMS_OUTPUT.PUT_LINE writes information to the buffer for storage before it is
displayed on the screen.
4. When a condition of the IF-THEN-ELSE construct is evaluated to NULL, control is
passed to the first executable statement after END IF.
5. CASE statements cannot be nested one inside the other.
6. What value must the test condition evaluate to in order for the loop to terminate?
Multiple type questions
1. Which of the following sections is mandatory for a PL/SQL block? a) Exception-
handling section
b) Executable section
c) Declaration section
d) All
2. How many actions can you specify in an IF-THEN-ELSE statement? a) One
b) Two
c) Four
d) As many as you require
3. A CASE construct is a control statement for which of the following? a) Sequence
structure
b) Iteration structure
c) Selection structure
d) All
Long Answer type question
1. Why does PL/SQL have so many different types of characters? What are they used for?
2. What is the difference between SQL and PL/SQL?
3. What are the components of a PL/SQL code block?
4. Write a PL/SQL block that will insert a new student in the student table.
5. Explain different types of loop in PL/SQL.
6. Explain IF , IF-THEN-ELSE , CASE Statements
7. How can you use SQL within PL/SQL?
8. What the difference between a procedure and a function?