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

Information: Database Management System Unit - 1

The document discusses database management systems and information processing. It provides information on how data is collected and stored, then processed to create output in the form of useful information. This information can then be used by decision makers. The document also discusses important attributes of high quality information like accuracy, timeliness, and relevancy. It describes how databases help organize information and the characteristics and components of database management systems.

Uploaded by

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

Information: Database Management System Unit - 1

The document discusses database management systems and information processing. It provides information on how data is collected and stored, then processed to create output in the form of useful information. This information can then be used by decision makers. The document also discusses important attributes of high quality information like accuracy, timeliness, and relevancy. It describes how databases help organize information and the characteristics and components of database management systems.

Uploaded by

Subhashini
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 62

DATABASE MANAGEMENT SYSTEM

UNIT – 1

Information

 Information is refined data.


 Information is data that have been put into meaningful and useful form.
 It is used by the recipient to make decisions.
 Information is the backbone of any organization.
 Information helps the managers to take decisions very quickly.

INPUT
PROCESS OUTPUT
(DATA)
(INFORMATION)

DATABASE

DATA CAPTURE USER

RESULTS ACTION DECISION

The above diagram represents the cycle of information:


 Various data are collected and stored as input
 This input data has been processed using different models.
 After processing, it gives output (information)
 Now the user uses this information to take decision.
 Result of this particular decision have been analyzed and these results are stored as
data.
Quality of information

Information quality is the quality of the content of information systems.

The three key attributes of information are:


(i) Accuracy
(ii) Timeliness
(iii) Relevancy
(i) Accuracy:
 Accuracy means that the information is free from mistakes and errors.
 It means that information is clear and accurate.
 Accuracy means that information is free from bias.
(ii) Timeliness:
 Timeliness means providing the information to the recipient within the needed time
frame.
 For e.g.: yesterday newspaper or yesterday’s stock details are of little value today.
 Timeliness means the user can get the information within the time frame.
(iii) Relevancy:
 Relevancy means the use of a piece of information for a particular person.
 An information relevant for one person, may not be relevant for another person.
 Only relevant information can be used by users to take decisions.

Information Processing
 Information processing is acquisition, storage, organization, retrieval, display and
distribution of information.
 Few decades back, when the computers were not invented, data processing was done
manually.
 But manual processing can be done only when the amount of information is very less.
 Now in companies, the amount of data has been increased.So manual processing takes
a lot of time to complete the work.
 After inventing the computers, the information processing was done within seconds.
 The information processing using computers were clear and accurate.
 Also, the information will be processed within the needed time frame.
 For this information processing, we need a large amount of data.
 So, Now-a-days we started to use the data base approach. That is, database means a
large amount of data.
Information and Enterprise
 An enterprise is the group of people with a common goal, which has certain resources
to achieve this goal.
 In traditional approach, the organization is divided into different units like production
department, sales department, etc.
 Each of these department has different goals and objectives.
 So, each department functions in isolation.
 So, the information created by various departments are available only to the top
management. But no other department can access the information.

PRODUCTION FINANCIAL MARKETING

R&D SALES DISTRIBUTION

TRADITIONAL APPROACH
 But in modern approach, the enterprise is considered as one system and all the
departments as subsystem.
 So, the information about all the aspects of the organization are stored centrally and
made available to all the departments.

FINANCIAL MARKETING

CENTRAL DATABASE

PRODUCTION DISTRIBUTION
SALES R&D

MODERN APPROACH

Database and Characteristics of a Database


A collection of data designed to be used by different people is called a database.
A database consists of four elements:

 Data are binary computer representations of stored logical entities.


 Relationship represent a correspondence between various data elements.
 Constraints are predicates that define correct database states.
 Schema describes the organization of data and relationship with the database.

A database is organized as follows:


 Internal schema defines how and where data are stored in physical storage.
 Conceptual schema tells the database models used.
 External schema defines different views of the database for different users.

Why a database?
(Characteristics of Database)

1. Redundancy can be reduced: In non-database system, each department has its own private
files. So, storage space is wasted. But in database systems, by having a centralized database,
Redundancy can be reduced.
2. Inconsistency can be avoided: Two different entries regarding same data will be avoided in
database.
3. Data can be shared in a database.
4. Standards can be enforced by a Database Administrator (DBA).
5. Security restrictions can be applied to a database by a DBA.
6. Integrity i.e., Accuracy of data can be maintained in a database.
7. Conflicting requirements can be balanced by creating a best database design.
8. Persistence: Data in a database exist permanently until deleted by the user.
9. Independence: The three levels of schema should be independent of each other.
DatabaseManagement System
A DBMS is a collection of programs that helps to store, modify, retrieve information from
database.
There are various DBMS software like oracle, Access, database, foxbase etc.,
A DBMS software is used in many applications like:
 Computerized library systems.
 Railway Reservation systems.
 Banking systems.
 Government database like E-services.
 Smart card systems.
 Postal system.

Services Provided by DBMS / (Major Components of a DBMS)


The major components of a DBMS are:

(i) Transaction management:


A transaction is a sequence of database operation that access database and transforms from
one state to another.
(ii) Concurrency control:
It is a procedure in DBMS for managing simultaneous operations without conflicting with each
other.
(iii) Recovery management:
This procedure brings the original state if it was deleted unknown by the user.
(iv) Security management:
This procedure makes only authorized users can access the database.
(v) Language interface:
DBMS provides a language interface like SQL for table creation and manipulation.
(vi) Storage management:
A DBMS provides a mechanism for permanent storage of data.
(vii) Data catalog management:
 It is a system database that contain description of database.
 Data catalog is also called as data dictionary.

Types of DBMS

A database model is an approach that specifies particular mechanism for data storage and
retrieval. The different database model is:
a) Hierarchical Model
b) NetworkModel
c) RelationalModel
d) Object orientedModel
e) ObjectrelationalModel
f) DeductiveModel

a) Hierarchical Model:
 It is one of the oldest database models.
 Information management system [IMS] was the first hierarchical database.
 It was developed by North American Rockwell company and IBM.
 This database model is organized into a tree like structure.
 It has parent and child relationship.
 It has one parent record and many children.
For e.g.:
Advantages:
 The design of hierarchical database is very simple.
 Hierarchical model gives security for the database.
 This promotes parent and child relationship. Therefore, it has data integrity.
 This model is considered as very efficient.

Disadvantages:
 This model was easy to design but difficult to implement.
 Maintaining a database in hierarchical model was difficult.
 It has programming complexity.
 Only one to one and one to many relationships was possible but many to
many relationships can’t be implemented in hierarchical model.
(b) Network model:
 This database model is organized as a graph.
 This model has the ability to handle many to many relationships.
 It allows a record to have more than one parent.
 It has owner-member relationship.
 Suppose an employee works in more than one company.

Advantages:
 Network model was conceptually simple and easy to design.
 This model can have one to one, one to many and many to many relationships.
 This model promotes data integrity because it has owner member relationships.
 Changes in data do not require changes in application programs.
 Network model is based on standards formulated by DBTG (Data Base Task Group).
Disadvantage:
 This model was easy to design but difficult to implement.
 This model has difficulty in making structural changes in database.
(c) Relational Model:
 This model is organized as a table.
 Each table is called as entity and each row is called as an instance.
 This is the most popular database model.

Advantages:
 This model is conceptually simple.
 Database design, implementation, maintenance and usage were much easier
than other models.
 It has very powerful, flexible and easy to use query capabilities.
 Database Structures do not affect the data access.
Disadvantages:
 Relational database system needs more powerful hardware to run smoothly.
 Relational database easy to design but sometimes this easiness leads to a bad
design.
 Since relational database was easy to design so many people or departments
create their own database.
(d) Object-oriented Model:
 A data model that closely represents the real world.
 Both data and relationships are contained in single structure called object.
 An object is a real-world entity.
 Attributes describe the properties of an object.
 Methods describe the object’s behavior.
 For e.g.: An object called PERSON includes the attributes like name, date of
birth, Aadhar ID etc.
 Any type of data can be stored in OODBMS such as data, text, picture, voice and
video.
Advantages:
 This object-oriented model can have large number of the different datatypes.
 This model combines the object-oriented programming concept with database
technology.
 Object oriented features like inheritance and dynamic binding improves productivity.
Disadvantages:
 Object oriented database have greater challenge in handling schema migration.
 This object-oriented model was not suited for all applications.

(e) Object Relational Model:


 This model has the features of object-oriented model and relational model.
 It supports objects, classes and inheritance.
 ORDBMS has a feature that allows developers to build their own data types and
methods

Advantages:
 New data types and methods can be added in this model.
 This model allows the use of inheritance that is reuse and sharing.
 Polymorphism in ORDBMS allows same methods names to have different
meanings.
Disadvantages:
 Programming in object relational model was difficult.
 This model was expensive.

(f) Deductive Model:


 This model is also called as inference model.
 It is a logic-based extension of relational model
 Data is stored as facts and rules.
 Relations are refined through facts and rules.
 A deductive database is a collection of facts and rules.
 By applying the rules of a deductive database to the facts,it is possible to obtain
additional facts.
 This data model is used as a new trend in DBMS for decision support systems. It is also
used in Artificial intelligence Technology.

Comparison Between Various Database Models


Models Data Element Relationship Identity Access language
organization Organization
Hierarchical Files, records Tree structure, Record based Procedural
Parent-child
relationship
Network Files, records Graph structure, Record based Procedural
owner &
member.
Relational Tables Tables, entities, Value based Non-procedural
attributes.
Object oriented Objects Objects are Record based Procedural
related
Object Objects Objects are Value based Non-procedural
Relational related
Deductive Facts & rules Rules applied on Valued based Non-procedural
the facts

UNIT-2
Entity Relationship Modeling

Entity Relationship Modeling

Entities Attributes Relationship


Introduction:

 ER model is a high-level conceptual data model.


 It is developed by chen in 1976.
 This model is used to facilitate database design.
 It supports user perception of the data.
 It deals with more technical aspects.
 It was independent of particular DBMS & hardware platform.
Components of ER Model
An entity relationship model has three components:

ER Model

Entities Attributes Relationships

(1) Entities:

 It is a fundamental item in any data model.


 Entity is viewed as a real world item.
 Each uniquely identifiable instance of an entity is called as entity occurrence or entity
instance.
 We identify each entity by a name and list of properties.
 A database normally contains many different entity types.
 For e.g.: STUDENT, BOOK, EMPLOYEE, CUSTOMER etc. are entities.
 In ER model, entities are written in uppercase characters.
(2) Attributes:

 An attribute is a single atomic unit of information that describes about an entity.


 For e.g. The entity BOOK has the attributes bookno., title, author, publisher etc.
 Attribute are written in lowercase characters and primary keys are underlined.
 Example: BOOK (bookno, Title, Author, publisher)
 Each attribute is associated with a set of values called domain.
 Attributes are classified as
(i) Simple attribute
(ii) Composite attribute
(iii) Single valued attribute
(iv) Multi valued attribute
(v) Derived attribute.
(i) Simple Attribute:

 Composed of a single component.


 Cannot be further subdivided.
 E.g.: Age, Salary.
 Also called as atomic attributes.
(ii) Composite Attribute:

 Composed of multiple components.


 Can be further subdivided.
 E.g.: Address attribute can be divided as Door No., Area, City, PIN code.
(iii) Single valued attribute:

 Holds a single value for a single entity.


 E.g.: Roll No has a single value.
(iv) Multi valued attribute:

 Holds a multiple value for a single entity


 E.g. Hobby has multiple values like reading, listening music, watching TV etc.
(v) Derived attribute:
 An attribute whose value can be derived from another attribute is called as derived
attribute.
 For e.g. Age can be calculated from date of birth.
(3) Relationship:

 A relationship is an association between entities.


 Usually the relationship name is an active verb.
 Relationships are represented by diamond shaped symbols.
 Two sides of the diamond are connected to the entities.
 For e.g.:

Publishes

PUBLISHER BOOK

 The terms associated with entities and relationships are:


(i) Degree
(ii) Connectivity
(iii) Cardinality
(iv) Participation
(v) Dependency.
(i) Degree:

 Degree of a relationships indicates number of associated entities


 Unary relationship exists when only one entity is associated.
 Binary relationship exists when two entities are associated.
 Ternary relationship exists when three entities are associated.
 Quaternary relationship exists when four entities are associated.
Unary relationship:
e.g.:
Binary Relationship:
e.g.:
publishes
PUBLISHER BOOK

Ternary Relationship:

TEACHER

Teaches
SUBJECT STUDENT

Quaternary Relationship:

TEACHER

Studies
SUBJECT COURSE-MATERIAL

STUDENT
(ii) Connectivity:

 Connectivity is used to describe the relationship classification.


 Relationship can be classified as one to one, one to many and many to many.
For e.g.:
1 manages 1
MANAGER DEPARTMENT

1 N
Has
DEPARTMENT EMPLOYEES

N N
Joins
EMPLOYEE COURSE

(iii) Cardinality:
Expresses the specific number of entity occurrence associated with the occurrence of the
related entity.
For e.g.:

Has
DEPARTMENT EMPLOYEES
(1, 100) (1,1)
One department can have a minimum of one employee and a maximum of 100 employees.
(iv) Participation:

 If an entity’s occurrence requires the occurrence of another entity, then it is called total
participation.
 If an entity’s occurrence doesn’t require the occurrence of another entity, then it is
called partial participation.
 For e.g.:
Enrolled in
COURSES
STUDENT

Partial Total
(v) Dependency:

 Entities are classified as strong or weak.


 Strong entity:
- Has a primary key.
- Independent of any other entity.
- Denoted by single rectangle.
 Weak entity:
- Has no primary key.
- Dependent of any other entity.
- Denoted by double rectangle.

 For e.g.

Cust address Loan name Loan date


Cust_ID Cust name

Borrows
CUSTOMER LOAN

ER Diagram Conventions
 Entities are reprresented by a rectangular box.

CUSTOMER
 Attributes are represented by an ellipse.

Cust_name
 Entities names are written in upper case letters.

STUDENT
 Attributes names are written in lower case letters.

Address

 Primary keys are underlined.

Roll no.

 Derived attributes are represented by dotted lines.

Age

 Multivalued attributes represented by double lines.

Hobby Phone no.

 Relationship can be classified as one to one, one to many and many to many.
1 1
manages DEPARTMENT
MANAGER

1 N
Has
DEPARTMENT EMPLOYEES

Joins
EMPLOYEE COURSE
N N

Relational Data Structure (RDBMS)


The relational model represents the database as a collection of relations. A relation is nothing
but a table of values.

Some popular Relational Database management systems are:

 DB2 and Informix Dynamic Server - IBM


 Oracle and RDB – Oracle
 SQL Server and Access – Microsoft

RDBMS Terminology

1. Relation: In the Relational model, each table is referred as relations.


2. Attribute: Each column in a Table are called as attributes.
E.g., Student_Rollno, NAME,etc.
3. Tuple – It is a single row of a table, which contains a single record.
4. Degree: The total number of attributes in the relation is called the degree of the
relation.
5. Cardinality: Total number of rows present in the Table is called cardinality.
6. Primary key - Every row has one unique identifier called primary key.
7. Attribute domain – Each attribute is associated with a set of values called domain.

Relational Data Structure

Attributes

Emp_ID Name Age Dept

Tuples
E0101 M.hari 32 Production
E0102 R.kumar 36 operation
E0103 S.pooja 31 human resoruce
E0104 N.varsha 34 production

Domain
DEGREE

 The data in RDBMS is stored as tables & this tables are called as relations.
 Every table is broken up into columns called attributes.
 A tuple is row of data. In this table, we have 4 employee records that is 4 tuples.
 Number of attributes in a relation is called degree.
 A relation with one degree is called unary relation. A relation with two degree is called
binary relation, etc.
 Number of tuples in a relation is called cardinality.
 Most of the relations have an attibute which can uniquely identify each tuple in the
relation. This attribute is callled as primary key.
 In some cases, there can be more than one attribute which can uniquely identify each
tuple in the relation. These attributes are called as canidate keys.
 One candiate key is designated as primary key and other candiates keys are called
alternate keys.
 A foregin key is a field in a table that refers to the primary key of another table.
 Foregin key act as a cross_referance between the tables.

For eg:

Person ID Name Age


P1 Hari 32
Order_ID Order.no Person ID
P2 manoj 25
OR1 1001 P1
P3 Rekha 26
OR2 1002 P2
OR3 1003 P3

 Person ID column in PERSON table is primary key.


 But Person ID column in orders table is foreign key.
Relational Data Manipulation

SQL Statements are divided into the following categories:

1. Data Definition Language(DDL) -Create, Alter, Drop


2. Data Manipulation Language(DML) – Insert, Update, Delete
3. Data Query language(DQL) - Select
4. Data Control Language(DCL) – Grant and Revoke

Four basic update operations performed on relational database model are

Insert, update, delete and select.

 Insert is used to insert data into the relation


 Delete is used to delete tuples from the table.
 Modify allows you to change the values of some attributes in existing tuples.
 Select allows us to choose a specific range of data.

Whenever one of these operations are applied, integrity constraints specified on the relational
database schema must never be violated.

Insert Operation

The insert operation gives values of the attribute for a new tuple which should be inserted into
a relation.

Update Operation
You can see that in the below-given relation table CustomerName= 'Apple' is updated from
Inactive to Active.
Query: Update table customer set Status=’active’ where CustomerName=’Apple’;

Delete Operation
To specify deletion, a condition on the attributes of the relation selects the tuple to be deleted.

Query:
Delete from customer where CustomerName=’Apple’;
In the above-given example, CustomerName= "Apple" is deleted from the table.
The Delete operation could violate referential integrity if the tuple which is deleted is
referenced by foreign keys from other tuples in the same database.

Select Operation

Query: Select * from Customer where CustomerID=2;

In the above-given example, CustomerName="Amazon" is selected

Relational Data Integrity Constraints


Relational Integrity constraints is referred to conditions which must be present for a valid
relation. These integrity constraints are derived from the rules in the mini-world that the
database represents.
There are many types of integrity constraints. Constraints on the Relational database
management system is mostly divided into 4 main categories are:
1. Domain Constraints
2. Entity Integrity
3. Referential Integrity
4. Operational Constraints

Domain Constraints:
All the values that appear in a column of a relation(table) must be taken from the same
domain. A domain is a set of values that may be assigned to an attribute.
A domain consists of the following components:
a) Domain Name
b) Meaning
c) Data type
d) Size of Length
e) Allowable values or Allowable range
Entity Integrity:
This rule is designed to assure that every relation has a primary key that the data values for
that primary key are all valid, no null value enter for the primary key. Every primary key
attribute is non-null.
Null value occurs in two situations:
1. There is no applicable data value. Example: If we don’t have a fax machine, we don’t
have the fax number.
2. Applicable data value is not known when the values are assigned. Example: If we don’t
know the melting point of Nickel, but it has value.
Referential Integrity:
Referential integrity constraints are based on the concept of Foreign Keys. A foreign key
is an important attribute of a relation which should be referred to in other relationships.
A foreign key is matching with the primary key.
Referential integrity constraint state happens where relation refers to a key attribute of
a different or same relation. However, that key element must exist in the table.
Operational Constraints:
These are the constraints enforced in the database by the business rules or real
worldlimitations.
Example: I the retirement age of the employees in an organization is 60, then the age column of
the employee table can have a constraint “Age should be less than or equal to 60”.
These kinds of constraints, enforced by the business and the environment are called
operational constraints.

Codd’s Rules
Rule 1: Information Rule
The data stored in a database, may it be user data or metadata, must be a value of some table
cell. Everything in a database must be stored in a table format.
Rule 2: Guaranteed Access Rule
Every single data element (value) is guaranteed to be accessible logically with a combination of
table-name, primary-key (row value), and attribute-name (column value). No other means, such
as pointers, can be used to access data.
Rule 3: Systematic Treatment of NULL Values
The NULL values in a database must be given a systematic and uniform treatment. This is a very
important rule because a NULL can be interpreted as one the following − data is missing, data is
not known, or data is not applicable.
Rule 4: Active Online Catalog Based on the Relational Model
The structure description of the entire database must be stored in an online catalog, known as
data dictionary, which can be accessed by authorized users. Users can use the same query
language to access the catalog which they use to access the database itself.
Rule 5: Comprehensive Data Sub-Language Rule
A database can only be accessed using a language having linear syntax that supports data
definition, data manipulation, and transaction management operations. This language can be
used directly or by means of some application. If the database allows access to data without
any help of this language, then it is considered as a violation.
Rule 6: View Updating Rule
All the views of a database, which can theoretically be updated, must also be updatable by the
system.
Rule 7: High-Level Insert, Update and Delete Rule
A database must support high-level insertion, updation, and deletion. This must not be limited
to a single row, that is, it must also support union, intersection and minus operations to yield
sets of data records.
Rule 8: Physical Data Independence
The data stored in a database must be independent of the applications that access the
database. Any change in the physical structure of a database must not have any impact on how
the data is being accessed by external applications.
Rule 9: Logical Data Independence
The logical data in a database must be independent of its user’s view (application). Any change
in logical data must not affect the applications using it. For example, if two tables are merged or
one is split into two different tables, there should be no impact or change on the user
application. This is one of the most difficult rule to apply.
Rule 10: Integrity Independence
A database must be independent of the application that uses it. All its integrity constraints can
be independently modified without the need of any change in the application. This rule makes a
database independent of the front-end application and its interface.
Rule 11: Distribution Independence
The end-user must not be able to see that the data is distributed over various locations. Users
should always get the impression that the data is located at one site only. This rule has been
regarded as the foundation of distributed database systems.
Rule 12: Non-Subversion Rule
If a system has an interface that provides access to low-level records, then the interface must
not be able to subvert the system and bypass security and integrity constraints.

Unit 3

Normalization

 Normalization is the process of organizing the data in the database.

 Normalization is used to minimize the redundancy from a relation or set of relations.


 It is also used to eliminate the undesirable characteristics like Insertion, Update and
Deletion Anomalies.

 Normalization divides the larger table into the smaller table and links them using
relationship.

 The normal form is used to reduce redundancy from the database table.

Normal Description
Form
1NF A relation is in 1NF if it contains an atomic value. The multi-valued
attributes should be removed, that is elimination of repeating groups.
2NF The partial functional dependencies have to be removed, that is
elimination of redundant data.
3NF The transitive dependencies have to be removed, that is
eliminatingcolumns not dependent on the key.
BCNF The remaining anomalies that result from functional dependencies are
removed.
4NF Multi-valued dependencies are removed, that is isolation of
independentmultiple relationships.
5NF Any remaining anomalies are removed. In this normal form, we isolate
semantically related multiplerelationships.

First Normal Form (1NF)

 A relation will be 1NF if it contains an atomic value.


 It states that an attribute of a table cannot hold multiple values. It must hold only
single-valued attributes.
 First normal form disallows the multi-valued attributes, composite attributes, and
their combinations.
Example: Relation EMPLOYEE is not in 1NF because of multi-valued attribute
EMP_PHONE.

EMPLOYEE Table:

EMP_ID EMP_NAME EMP_PHONE EMP_STATE


14 John 7272826385, Delhi
9064738238
20 Harry 8574783832 Tamilnadu
12 Sam 7390372389, Punjab
8589830302

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

EMP_ID EMP_NAME EMP_PHONE EMP_STATE


14 John 7272826385 Delhi
14 John 9064738238 Delhi
20 Harry 8574783832 Tamilnadu
12 Sam 7390372389 Punjab
12 Sam 8589830302 Punjab

Second Normal Form (2NF)

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

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

Example:Suppose a school wants to store the data of teachers and the subjects they teach.
They create a table that looks like this: Since a teacher can teach more than one subjects, the
table can have multiple rows for a same teacher.

TEACHER Table

TEACHER_ID SUBJECT TEACHER_AGE


25 Chemistry 30
25 Biology 30
47 English 35
83 Math 38
83 Computer 38
Candidate Keys: {teacher_id, subject}
Non prime attribute: teacher_age

The table is in 1 NF because each attribute has atomic values. However, it is not in 2NF because
non prime attribute teacher_age is dependent on teacher_id alone which is a proper subset of
candidate key. This violates the rule for 2NF.

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

TEACHER_DETAIL Table:

TEACHER_ID TEACHER_AGE
25 30
47 35
83 38

TEACHER_SUBJECT Table:
TEACHER_ID SUBJECT
25 Chemistry
25 Biology
47 English
83 Math
83 Computer
Third Normal Form (3NF)

A table design is said to be in 3NF if both the following conditions hold:

 Table must be in 2NF


 Transitive functional dependency of non-prime attribute on any super key should be
removed.

An attribute that is a part of one of the candidate keys is known as prime attribute.
An attribute that is not part of any candidate key is known as non-prime attribute.

In other words 3NF can be explained like this: A table is in 3NF if it is in 2NF and for each
functional dependency X-> Y at least one of the following conditions hold:
 X is a super key of table
 Y is a prime attribute of table

Example:

EMPLOYEE_DETAIL Table:

EMP_ID EMP_NAME EMP_PIN EMP_STATE EMP_CITY


222 Harry 201010 UP Noida
333 Stephan 02228 US Boston
444 Leon 60007 US Chicago
555 Karthik 06389 UK Norwich
666 John 462007 MP Bhopal

Super key in the table above:

{EMP_ID}, {EMP_ID, EMP_NAME}, {EMP_ID, EMP_NAME, EMP_PIN}

Candidate key: {EMP_ID}

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

Here, EMP_STATE & EMP_CITY dependent on EMP_PIN and EMP_PIN dependent on


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

EMPLOYEE Table:

EMP_ID EMP_NAME EMP_PIN


222 Harry 201010
333 Stephan 02228
444 Leon 60007
555 Karthik 06389
666 John 462007

EMPLOYEE_PINTable:

EMP_PIN EMP_STATE EMP_CITY


201010 UP Noida
02228 US Boston
60007 US Chicago
06389 UK Norwich
462007 MP Bhopal

Boyce Codd Normal Form (BCNF)

o BCNF is the advance version of 3NF. It is stricter than 3NF.

o A table is in BCNF if every functional dependency X → Y, X is the super key of the


table.
o For BCNF, the table should be in 3NF, and for every Functional Dependency, Left
hand side is super key.

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

EMPLOYEE Table:

EMP_ID EMP_COUNTRY EMP_DEPT DEPT_TYPE EMP_DEPT_NO


264 India Designing D394 283
264 India Testing D394 300
364 UK Stores D283 232
364 UK Developing D283 549

In the above table Functional dependencies are as follows:

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

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

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

EMP_COUNTRY Table:
EMP_ID EMP_COUNTRY
264 India
364 UK

EMP_DEPT Table:
EMP_DEPT DEPT_TYPE EMP_DEPT_NO
Designing D394 283
Testing D394 300
Stores D283 232
Developing D283 549

EMP_DEPT_MAPPING Table:
EMP_ID EMP_DEPT
D394 283
D394 300
D283 232
D283 549

Functional dependencies:

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

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

Fourth normal form (4NF)

o A relation will be in 4NF if it is in Boyce Codd normal form and has no multi-valued
dependency.
o For a dependency A → B, if for a single value of A, multiple values of B exists, then
the relation will be a multi-valued dependency.

Example :

STUDENT Table:

STU_ID COURSE HOBBY


21 Computer Dancing
21 Math Singing
34 Chemistry Dancing
74 Biology Cricket
59 Physics Hockey
The given STUDENT table is in 3NF, but the COURSE and HOBBY are two independent
entity. Hence, there is no relationship between COURSE and HOBBY.

In the STUDENT relation, a student with STU_ID, 21 contains two courses, Computer and
Math and two hobbies, Dancing and Singing. So there is a Multi-valued dependency on
STU_ID, which leads to unnecessary repetition of data.

So to make the above table into 4NF, we can decompose it into two tables:

STU_ID HOBBY
21 Dancing
21 Singing
34 Dancing
74 Cricket
59 Hockey

STUDENT_COURSESTUDENT_HOBBY
STU_ID COURSE
21 Computer
21 Math
34 Chemistry
74 Biology
59 Physics

Fifth Normal Form (5NF)

o A relation is in 5NF if it is in 4NF and not contains any join dependency and joining
should be lossless.
o 5NF is satisfied when all the tables are broken into as many tables as possible in order
to avoid redundancy.
o 5NF is also known as Project-join normal form (PJNF).
Example

SUBJECT LECTURER SEMESTER


Computer Anshika Semester 1
Computer John Semester 1
Math John Semester 1
Math Akash Semester 2
Chemistry Praveen Semester 1

In the above table, John takes both Computer and Math class for Semester 1 but he doesn't
take Math class for Semester 2. In this case, combination of all these fields required to
identify a valid data.

Suppose we add a new Semester as Semester 3 but do not know about the subject and who
will be taking that subject so we leave Lecturer and Subject as NULL. But all three columns
together acts as a primary key, so we can't leave other two columns blank.

So to make the above table into 5NF, we can decompose it into three relations P1, P2 & P3:

P1 P2

SUBJECT LECTURER
SEMESTER SUBJECT
Computer Anshika
Semester 1 Computer Computer John
Semester 1 Math Math John
Semester 1 Chemistry Math Akash
Semester 2 Math Chemistry Praveen

P3

SEMESTER LECTURER
Semester 1 Anshika
Semester 1 John
Semester 1 John
Semester 2 Akash
Semester 1 Praveen
Unit 4

TABLES
Tables are the basic building blocks in any database system. They contain the rows and columns
of data. We can create, modify and delete tables using sql commands.
Creating a Table
Creating a table involves table name, column definitions and each column's data type. The
CREATE TABLE statement is used to create a new base table.
The CREATE TABLE statement has two formats.
Format1 :
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
Primary Key definition,
Alternate Key definitions,
Foreign Key definitions
);

The column definition takes the form


Column-name datatype [ NULL | NOT NULL | WITH DEFAULT | UNIQUE ]
Example:
CREATE TABLE BOOK(
BookID CHAR(10) NOT NULL,
Title CHAR(10) NOT NULL WITH DEFAULT,
Author CHAR(10) NOT NULL WITH DEFAULT,
Publisher CHAR(10) NOT NULL WITH DEFAULT,
Year INTEGER NOT NULL WITH DEFAULT,
Price INTEGER NULL,
PRIMARY KEY (BookID)
);
This statement will create an empty base table named BOOK. The table will have 6 columns and
the primary key will be BookID.

Format2 :
CREATE TABLE table-name LIKE base-table-name;
Example :
CREATE TABLE CATALOG LIKE BOOK;
This statement will create a table called CATALOG with the same structure as BOOK.

Modifying a Table

The ALTER TABLE command is used to add, delete or modify columns in an existing table.

ALTER TABLE table_name ADD column_name datatype;

ALTER TABLE table_name DROP COLUMN column_name;

ALTER TABLE table_name MODIFY COLUMN column_name datatype;

ALTER TABLE table_name RENAME COLUMN old_name to new_name;


Example:
ALTER TABLE BOOK ADD discount int;
ALTER TABLE BOOK DROP COLUMN year;
ALTER TABLE BOOK MODIFY COLUMN title varchar(20);
ALTER TABLE BOOK RENAME COLUMN Author to Writer;

Deleting a Table

The DROP TABLE statement is used to delete a table. The basic syntax of this DROP TABLE
statement is as follows:

DROP TABLE table_name;


Example:
DROP TABLE BOOK;

JOINS
Join is a query in which data is retrieved from more than one table.
Join has the capability of retrieving data from multiple tables.
It is one of the most powerful and useful feature in RDBMS.
Why do we need Joins?
 For data analysis, we must assemble data from several tables.
 Joins are used to retrieve data from more than one table.

Let's look at "Orders" table:


OrderI CustomerID OrderDate
D
10308 2 02/03/2019
10309 3 05/04/2019
10310 1 06/05/2019
Then, look at "Customers" table:
CustomerID CustomerName ContactName Country
1 Manoj Arun India
2 Kavitha Geetha India
3 Praveen Subash India
Then, we can create the following SQL statement (that contains an INNER JOIN), that selects
records that have matching values in both tables:
Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

and it will produce the result as follows:


OrderI CustomerName OrderDate
D
10308 Kavitha 02/03/2019
10309 Praveen 05/04/2019
10310 Manoj 06/05/2019

Use of Aliases
Giving aliases to tables can make this job easier. Using aliases improves the readability of the
SQL. Aliases can be letters, numbers or combination.
Example:
Select Name, Pay from Employee E, Salary S
Where E.empid=S.empid;
Qualities of a Good Join
Use of primary key and foreign key makes a good join.
Columns compared in joins should have similar values.
Different Types of SQL JOINs
1. INNER JOIN: Returns records that have matching values in both tables.
2. LEFT JOIN: Returns all records from the left table, and the matched records from the
right table.
3. RIGHT JOIN: Returns all records from the right table, and the matched records from
the left table.
4. FULL OUTER JOIN: Returns all records when there is a match in either left or right
table.
Theta Joins, EquiJoins and Non-EquiJoins
Theta Join is a join query using comparison operators. (=, > =, < =, >, <, <>)
If the comparison operator is equality, then the join is called an equijoin. 
If the comparison operator is not the equal sign, then the join is called annon equijoin. 
Natural Join :
The equijoin produce a result containing two identical columns. But a natural join produce
a result that does not contain identical columns.
Self Join :
If a table is joined to itself, then it is called self-join.

UNIONS

 The Union is used to combine two separate select statements and produce the result as a
union of both the select statements.
 The fields to be used in both the select statements must be in same order, same number
and same data type.
 The UNION produces distinct values in the result.
 The UNIONALL produces the duplicate values.
UNION Syntax
The UNION operator selects only distinct values by default.

SELECTcolumn_name(s)FROMtable1
UNION
SELECTcolumn_name(s)FROMtable2;

UNION ALL Syntax

The UNION ALL operator allows duplicate values.

SELECTcolumn_name(s)FROMtable1
UNIONALL
SELECTcolumn_name(s)FROMtable2;

Below is a selection from the "Customers" table:

CustomerI CustomerNam Address City


D e
1 M.Manoj 2, KK Nagar Chennai

2 R.Naveen 12, West Street Trichy


3 K.Subash 21/3, RR Nagar Madurai

And a selection from the "Suppliers" table:

SupplierID SupplierName Address City


1 S.Deepak 11, East Street Madurai
2 M.Chandran 26/5, MGK Nagar Chennai
3 R.Ravi 13, South Street Coimbatore

SQL UNION Example

SELECT City FROM Customers


UNION
SELECT City FROM Suppliers
ORDERBY City;
The output for the above query :

City
Chennai
Coimbatore
Madurai
Trichy

SQL UNION ALL Example

SELECT City FROM Customers


UNIONALL
SELECT City FROM Suppliers
ORDERBY City;

The output for the above query :

City
Chennai
Trichy
Madurai
Madurai
Chennai
Coimbatore

INDEXES

What is an Index?

 An index is a structure that provides faster access to the rows of a table based on the
values of one or more columns.
 An index is a pointer to data in a table.
 An index in a database is similar to an index in the book.
 The RDBMS can quickly search the index to find a particular data value.

Creating an Index
Indexes are created using the CREATE INDEX statement. The general form is :

CREATE INDEX index_name ON table_name(column1 order, column2 order,….);

Each order specification is ASC (ascending) or DESC (descending).

But ASC is the default.

Example :

i) CREATE INDEX Index1


ON STUDENT(Rollno);

ii) CREATE INDEX Index2


ON EMPLOYEE(Firstname, Lastname);

Types of Indexes

1. Composite Indexes
2. Unique Indexes
3. Clustered Indexes
4. Non Clustered Indexes

Composite Indexes

When an index is made up of more than one column, it is called a composite index.

Example:

CREATE INDEX Index2


ON EMPLOYEE(Firstname, Lastname);

Unique Indexes

A unique index is an index in which no duplicate values are allowed. Unique indexes are usually
created based on the primary key.
Example:

CREATE UNIQUE INDEX Index1


ON STUDENT ( Rollno );

Clustered Indexes

Clustered Index is an index in which the rows of a table will be in the same order as that of the
index.

Non Clustered Indexes

Clustered Index is an index in which the rows of a table will not be in the same order as that of
the index.

Dropping an Index

An index can be deleted using DROP INDEX command.

The basic syntax is as follows −


DROP INDEX Index_name;

Example: DROP INDEX Index1;

Once the command is executed, the Index1 is removed from the catalog.
Uses of Indexes
 If there are no indexes for a table, the RDBMS process the query sequentially row by
row.
 For large tables containing millions of records, the processing of a query without an
index takes a lot of time.
 Indexes speed up the execution of SQL statements.

AGGREGATE FUNCTIONS
The aggregate functions greatly enhance the power of sql statements. It helps us to summarize
the data from the tables.

SQL provides six aggregate functions.

1. COUNT()
2. COUNT(*)
3. SUM()
4. AVG()
5. MAX()
6. MIN()

1. COUNT()

COUNT() is used to count the number of values in a column.

Example: Get the number of employees in the HR Department.

Select COUNT(name) from EMPLOYEE

Where Dept = 'HR';

2. COUNT(*)

COUNT(*) is used to count the number of rows.

Example: Get the number of rows in the EMPLOYEE table

Select COUNT(*) from EMPLOYEE;

3. SUM()

SUM() is used to find the sum of values in a column.

Example: Find the total basic pay for all the employees

SELECT SUM(BASIC) FROM EMPLOYEE;

Example: Find the total basic pay for all the employees in the 'HR' department

SELECT SUM(BASIC) FROM EMPLOYEE


Where Dept = 'HR';

4. AVG()

AVG() is used to find the average of the values in a column.

Example: Find the average BASIC of an employee.

SELECT AVG(BASIC) FROM EMPLOYEE;

Example: Find the average basic pay for all the employees in the 'HR' department

SELECT AVG(BASIC) FROM EMPLOYEE

Where Dept = 'HR';

5. MAX()

MAX() is used to find the maximum value in a column.

Example: Find the maximum BASIC of an employee.

SELECT MAX(BASIC) FROM EMPLOYEE;

Example: Find the maximum basic pay in the 'HR' department

SELECT MAX(BASIC) FROM EMPLOYEE

Where Dept = 'HR';

6. MIN()

MIN() is used to find the minimum value in a column.

Example: Find the minimum BASIC of an employee.

SELECT MIN(BASIC) FROM EMPLOYEE;

Example: Find the minimum basic pay in the 'HR' department

SELECT MIN(BASIC) FROM EMPLOYEE

Where Dept = 'HR';


QUERIES (SELECT STATEMENT)

The SQL SELECT statement is used to retrieve records from one or more tables in your SQL
database. The records retrieved are known as a result set.

Syntax:

The syntax for the SELECT statement in SQL is:

SELECT expressions

FROM tables

[WHERE conditions]

[ORDER BY expression [ ASC | DESC ]];

Expressions :The columns or calculations that you wish to retrieve. Use * if you wish to select
all columns.

Tables :The tables that you wish to retrieve records from. There must be at least one table listed
in the FROM clause.

WHERE conditions :Optional. The conditions that must be met for the records to be selected. If
no conditions are provided, then all records will be selected.

ORDER BY expression :Optional. The expression used to sort the records in the result set. If
more than one expression is provided, the values should be comma separated.

ASC :Optional. ASC sorts the result set in ascending order by expression. This is the default
behavior, if no modifier is provider.

DESC :Optional. DESC sorts the result set in descending order by expression.

Example:

CUSTOMER TABLE

Customer_Id Last_Name First_Name Favorite_Website


4000 Jackson John techonthenet.com
5000 Smith Jane digminecraft.com
6000 Franklin Sam bigactivities.com
7000 Reynolds Allen checkyourmath.com
8000 Anderson Harish NULL
9000 Johnson David techonthenet.com

SELECT Statement:

SELECT *FROM CUSTOMER


WHERE Favorite_Website = 'techonthenet.com'
ORDER BY Last_Name ASC;

Output:

Customer_Id Last_Name First_Name Favorite_Website


4000 Jackson John techonthenet.com
9000 Johnson David techonthenet.com

SELECT with AND


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

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

SELECT with NOT


The following SQL statement selects all fields from "Customers" where country is NOT
"Germany":
SELECT * FROM Customers
WHERE NOT Country='Germany';
SELECT with LIKE
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
The following SQL statement selects all customers with a CustomerName starting with "a":
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';
The following SQL statement selects all customers with a CustomerName ending with "a":
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';

SELECT with BETWEEN


The BETWEEN operator selects values within a given range.
The following SQL statement selects all products with a price BETWEEN 10 and 20:
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;

SUBQUERIES

 A subquery is a SQL query within a query.


 Subqueries are nested queries that provide data to the enclosing query.
 Subqueries can return individual values or a list of records
 Subqueries must be enclosed with parenthesis
 The outer query is called as main query and inner query is called as subquery.
 The subquery generally executes first, and its output is used to complete the query
condition for the main or outer query.
 Subqueries can be used with SELECT, UPDATE, INSERT, DELETE statements along
with comparison operator.
 The comparison operator may be =, >, =, <= and Like operator.

Syntax:
SELECT column_name
FROM table_name
WHERE column_name comparison operator
( SELECT COLUMN_NAME from TABLE_NAME WHERE ... );

Sample Table:

DATABASE Table
NAME ROLL_NO LOCATIO PHONE_NUMBER
N
Ram 101 Chennai 9988775566
Raj 102 Coimbatore 8877665544
Sasi 103 Madurai 7766553344
Ravi 104 Salem 8989898989
Sumathi 105 Kanchipura 8989856868
m

STUDENT Table
NAME ROLL_NO SECTION
Ravi 104 A
Sumathi 105 B
Raj 102 A

Sample Queries

To display NAME, LOCATION, PHONE_NUMBER of the students from DATABASE table


whose section is A

Select NAME, LOCATION, PHONE_NUMBER from DATABASE


WHERE ROLL_NO IN
(SELECT ROLL_NO from STUDENT where SECTION=’A’);

Explanation :

First subquery executes “ SELECT ROLL_NO from STUDENT where SECTION=’A’ ” returns
ROLL_NO from STUDENT table whose SECTION is ‘A’.
Then outer-query executes it and return the NAME, LOCATION, PHONE_NUMBER from the
DATABASE table of the student whose ROLL_NO is returned from inner subquery.

Output:

NAME ROLL_NO LOCATION PHONE_NUMBER


Ravi 104 Salem 8989898989
Raj 102 Coimbatore 8877665544

NULLS
 The SQL NULL is the term used to represent a missing value.
 A NULL value in a table is a value in a field that appears to be blank.
 A field with a NULL value is a field with no value.
Syntax:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR(20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) NULL ,
SALARY DECIMAL (18, 2) NULL,
PRIMARY KEY (ID));

 NOT NULL signifies that column should always accept a value.


 NULLmeans these columns could be blank.

IS NULL OR IS NOT NULL:

We use the IS NULL or IS NOT NULL operators to check for a NULL value.

Example:

ID NAME AGE ADDRESS SALARY


1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kolkata 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP
7 Karthik 24 Tamilnadu

a) IS NOT NULL operator:


SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM CUSTOMER
WHERE SALARY IS NOT NULL;

This would produce the following result

ID NAME AGE ADDRESS SALARY


1 Ramesh 32 Ahmedabad 2000
2 Khilan 25 Delhi 1500
3 Kaushik 23 Kolkata 2000
4 Chaitali 25 Mumbai 6500
5 Hardik 27 Bhopal 8500

b)IS NULL operator:


SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM CUSTOMER
WHERE SALARY IS NULL;

This would produce the following result –

ID NAME AGE ADDRESS SALARY


6 Komal 22 MP
7 Karthik 24 Tamilnadu

VIEWS IN SQL
 Views in SQL are considered as a virtual table. A view also contains rows and columns.
 To create the view, we can select the fields from one or more tables present in the
database.
 A view can either have specific rows based on certain condition or all the rows of a table.

Example:

Student_Detail
STU_ID NAME ADDRESS
1 Stephan Delhi
2 Kathrin Noida
3 David Ghaziabad
4 Raja Madurai

Student_mark
STU_ID NAME MARKS AGE
1 Stephan 97 19
2 Kathrin 86 21
3 David 74 18
4 Raja 90 20
5 John 96 18


Creating view
A view can be created using the CREATE VIEW statement. We can create a view from a single
table or multiple tables.
Syntax:
1. CREATE VIEW view_name AS
2. SELECT column1, column2.....
3. FROM table_name
4. WHERE condition;
Creating View from a single table
In this example, we create a View named DetailsView from the table Student_Detail.
Query:
1. CREATE VIEW DetailsView AS
2. SELECT NAME, ADDRESS
3. FROM Student_Details
4. WHERE STU_ID < 4;
Just like table query, we can query the view to view the data.
1. SELECT * FROM DetailsView;
Output:
NAMEADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad
3. Creating View from multiple tables
View from multiple tables can be created by simply include multiple tables in the SELECT
statement.
In the given example, a view is created named MarksView from two tables Student_Detail and
Student_Marks.
Query:
1. CREATE VIEW MarksView AS
2. SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student_Marks.MARKS
3. FROM Student_Detail, Student_Mark
4. WHERE Student_Detail.NAME = Student_Marks.NAME;
To display data of View MarksView:
1. SELECT * FROM MarksView;
NAMEADDRESS MARKS
Stephan Delhi 97
Kathrin Noida 86
David Ghaziabad 74
Alina Gurugram 90
4. Deleting View
A view can be deleted using the Drop View statement.
Syntax
1. DROP VIEW view_name;
Example:
If we want to delete the View MarksView, we can do this as:
1. DROP VIEW MarksView;

PL/SQL Cursor
Cursor - Introduction
 When an SQL statement is processed, Oracle creates a memory area known as context
area.
 A cursor is a pointer to this context area.
 It contains all information needed for processing the statement.
 In PL/SQL, the context area is controlled by Cursor.
 A cursor contains information on a select statement and the rows of data accessed by it.
 A cursor is used to referred to a program to fetch and process the rows returned by the
SQL statement, one at a time.
 There are two types of cursors:
1. Implicit Cursors
2. Explicit Cursors
1) Implicit Cursors
The implicit cursors are automatically generated by Oracle while an SQL statement is executed.
These are created by default to process the statements when DML statements like INSERT,
UPDATE, DELETE etc. are executed.
Orcale provides some attributes known as Implicit cursor's attributes to check the status of DML
operations.
Some of them are: %FOUND, %NOTFOUND, %ROWCOUNT and %ISOPEN.

Attribute Description
%FOUND Return value is TRUE if SELECT statement returned one or
more rows.
%NOTFOUND Return value is TRUE if SELECT statement return no rows.
%ISOPEN Always returns FALSE for implicit cursors.
%ROWCOUNT Returns number of rows returned by a SELECT statement.

2) Explicit Cursors
 The Explicit cursors are defined by the programmers.
 These cursors should be defined in the declaration section.
 It is created on a SELECT statement which returns more than one row.

Syntax of Explicit Cursor


CURSOR cursor_name IS select_statement;;
Steps:
1. Declare the cursor to initialize in the memory.
2. Open the cursor to allocate memory.
3. Fetch the cursor to retrieve data.
4. Close the cursor to release allocated memory.

Example
Customers Table
ID NAME AGE ADDRESS SALARY
1 Ramesh 23 Allahabad 20000
2 Suresh 22 Kanpur 22000
3 Mahesh 24 Ghaziabad 24000
4 Chandan 25 Noida 26000
5 Alex 21 Paris 28000
6 Sunita 20 Delhi 30000

DECLARE
total_rowsnumber(2);
BEGIN
UPDATE customers
SET salary = salary + 5000;
IF sql%notfound THEN
dbms_output.put_line('no customers updated');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers updated ');
END IF;
END;
/

Output:
ID NAME AGE ADDRESS SALARY
1 Ramesh 23 Allahabad 25000
2 Suresh 22 Kanpur 27000
3 Mahesh 24 Ghaziabad 29000
4 Chandan 25 Noida 31000
5 Alex 21 Paris 33000
6 Sunita 20 Delhi 35000

PL/SQL Trigger
Triggers - Introduction
 Trigger is invoked by Oracle engine automatically whenever a specified event occurs.
 Trigger is stored into database and invoked repeatedly, when specific condition match.
 Triggers are stored programs, which are automatically executed or fired when some event
occurs.
 Triggers are written to be executed in response to any of the following events.
 A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).
 A database definition (DDL) statement (CREATE, ALTER, or DROP).
 A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
 Triggers could be defined on the table, view, schema, or database with which the event is
associated.
Advantages of Triggers
 Trigger generates some derived column values automatically
 Enforces referential integrity
 Event logging and storing information on table access
 Auditing
 Synchronous replication of tables
 Imposing security authorizations
 Preventing invalid transactions

Creating a Trigger:
CREATE TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT | UPDATE | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
PL/SQL Trigger Example:
In this example, we are using the following CUSTOMERS table:
ID NAME AGE ADDRESS SALARY
1 Ramesh 23 Allahabad 20000
2 Suresh 22 Kanpur 22000
3 Mahesh 24 Ghaziabad 24000
4 Chandan 25 Noida 26000
5 Alex 21 Paris 28000
6 Sunita 20 Delhi 30000

CREATE OR REPLACE TRIGGER salary_changes


BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/

After the execution of the above code at SQL Prompt, it produces the following result.
Trigger created.

PL/SQL Procedure
Introduction to Procedures

A Procedure is a PL/SQL block which performs one or more specific tasks.


The procedure contains a header and a body.
1. Header: The header contains the name of the procedure and the variables passed to the
procedure.
2. Body: The body contains a declaration section, execution section and exception section.

How to pass parameters in procedure:

There are three ways to pass parameters in procedure:


1. IN parameters: The IN parameter can be referenced by the procedure or function.
2. OUT parameters: The OUT parameter cannot be referenced by the procedure or function,
but the value of the parameter can be overwritten by the procedure or function.
3. INOUT parameters: The INOUT parameter can be referenced by the procedure or
function and the value of the parameter can be overwritten by the procedure or function.
A procedure may or may not return any value.

Syntax for creating procedure:


CREATE [OR REPLACE] PROCEDURE procedure_name
[ (parameter [,parameter]) ]
IS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [procedure_name];
Example:
create table user(id number(10) primary key,name varchar2(100));
Now write the procedure code to insert record in user table.
create or replace procedure "INSERTUSER"
(id IN NUMBER,
name IN VARCHAR2)
is
begin
insert into user values(id,name);
end;
PL/SQL Program to Call Procedure:
BEGIN
insertuser(101,'Rahul');
dbms_output.put_line('record inserted successfully');
END;
/
Now, see the "USER" table, you will see one record is inserted.
ID Name
101 Rahul

PL/SQL Drop Procedure

Syntax for drop procedure is:


DROP PROCEDURE procedure_name;

Example of drop procedure


DROP PROCEDURE pro1;

Exception
What is Exception?
An error occurs during the program execution is called Exception in PL/SQL.
PL/SQL facilitates programmers to catch such conditions using exception block in the program
and an appropriate action is taken against the error condition.
There are two type of exceptions:
 System-defined Exceptions
 User-defined Exceptions
Syntax for Exception Handling:
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
WHEN others THEN
exception3-handling-statements
END;
Example of Exception Handling
CUSTOMERS table
ID NAME AGE ADDRESS SALARY
1 Ramesh 23 Allahabad 20000
2 Suresh 22 Kanpur 22000
3 Mahesh 24 Ghaziabad 24000
4 Chandan 25 Noida 26000
5 Alex 21 Paris 28000
DECLARE
c_idcustomers.id%type := 8;
c_namecustomers.name%type;
c_addrcustomers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
The above program should show the name and address of a customer as result whose ID is given.
But there is no customer with ID value 8 in our database, so the program raises the run-time
exception NO_DATA_FOUND, which is captured in EXCEPTION block.
Following is a list of some important pre-defined exceptions:
Exception Description
LOGIN_DENIED It is raised when s program attempts to log on to the database
with an invalid username or password.
NO_DATA_FOUND It is raised when a select into statement returns no rows.
PROGRAM_ERROR It is raised when PL/SQL has an internal problem.
ROWTYPE_MISMATC It is raised when a cursor fetches value in a variable having
H incompatible data type.
STORAGE_ERROR It is raised when PL/SQL ran out of memory or memory was
corrupted.
TOO_MANY_ROWS It is raised when a SELECT INTO statement returns more than
one row.
VALUE_ERROR It is raised when an arithmetic, conversion, truncation, or size-
constraint error occurs.
ZERO_DIVIDE It is raised when an attempt is made to divide a number by zero.

You might also like