Complete Dbms Notes
Complete Dbms Notes
net
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Transaction Management:
A transaction is a collection of operations that performs
a single logical function in a database application
Transaction-management component ensures that the
database remains in a consistent (correct) state despite
system failures (e.g., power failures and operating
system crashes) and transaction failures.
Concurrency-control manager controls the interaction
among the concurrent transactions, to ensure the
consistency of the database.
A database transaction is a unit of interaction with a
database management system or similar system that is treated
in a coherent and reliable way independent of other
transactions that must be either entirely completed or
aborted.
In some systems, transactions are also called LUW for Logical
Units of Work.
In database products the www.jntuworld.com
ability to handle transactions allows
www.jntuworld.com www.jwjobs.net
Storage Management:
Storage management is a program module that provides the
interface between the low-level data stored in the
database and the application programs and queries
submitted to the system.
The storage manager is responsible to the following
tasks:
interaction with the file manager
efficient storing, retrieving and updating of data
Database Administrator:
A database administrator (DBA) is a person who is responsible
for the environmental aspects of a database. In general, these
include:
Recoverability - Creating and testing Backups
Integrity - Verifying or helping to verify data integrity
Security - Defining and/or implementing access controls
to the data
Availability - Ensuring maximum uptime
Performance - Ensuring maximum performance given
budgetary constraints
Development and testing support - Helping programmers and
engineers to efficiently utilize the database.
The role of a database administrator has changed according to
the technology of database management systems (DBMSs) as well
as the needs of the owners of the databases.
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Database Users:
o Database administrators: responsible for authorizing
access to the database, for co-ordinating and monitoring
its use, acquiring software, and hardware resources,
controlling its use and monitoring efficiency of
operations.
o Database Designers: Responsible to define the content,
the structure, the constraints, and functions or
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Data Independence :
When a schema at a lower level is changed, only the mappings
between this schema and higher-level schemas need to be
changed in a DBMS that fully supports data independence. The
higher-level schemas themselves are unchanged. Hence, the
application programs need not be changed since they refer to
the external schemas
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Chapter 02
The database design process can be divided into six steps. The
ER model is most relevant to the first three steps.
1. Requirement Analysis:
The very first step in designing a database application
is to understand what data is to be stored in the database,
what application must be built in top of it, and what
operations are most frequent and subject to performance
requirements. In other words, we must find out what the users
want from the database.
Beyond ER Design
4. Schema Refinement:
This step is to analyze the collection of relations in
our relational database schema to identify potential problems,
and refine it.
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Types of Attributes:
Simple (Atomic) Vs. Composite
Single Valued Vs. Multi Valued
Stored Vs. Derived
Null Values
Null Values
In some cases a particular entity may not have an
applicable value for an attribute. For example, a college
degree attribute applies only to persons with college degrees.
For such situation, a special value called null is created.
Degree of a Relationship:
The degree of a relationship is the number of
participating entity types. Hence the above work_for
relationship is of degree two. A relationship type of degree
two is called Binary, and one of degree three is called
Ternary. An example of Ternary relationship is given below.
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Relationship of degree:
o two is binary
o three is ternary
o four is quaternary
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
1. Cardinality Ratio
Describes maximum number of possible relationship
occurrences for an entity participating in a given
relationship type.
2. Participation:
Determines whether all or only some entity occurrences
participate in a relationship.
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Types of Entity:
1. Strong Entity
a. Entity which has a key attribute in its attribute
list.
2. Weak Entity
a. Entity which doesn’t have the Key attribute.
ER Diagram
Notations for ER Diagram
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Identifying Relationship:
It is a relationship between Strong entity and weak
entity.
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Specialization:
For Example,
{SECRETARY, ENGINEER, TECHNICIAN}
is a specialization of EMPLOYEE based upon job type.
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Generalization:
FIGURE Generalization.
(a) Two entity types, CAR and TRUCK.
(b) Generalizing CAR and TRUCK into the superclass VEHICLE.
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
1. Predicate Defined
If we can determine exactly those entities that will
become members of each subclass by a condition, the
subclasses are called predicate-defined (or condition-
defined) subclasses
2.Attribute Defined:
If all subclasses in a specialization have membership
condition on same attribute of the super class,
specialization is called an attribute defined-
specialization
3. User Defined
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
4. Disjointness Constraint:
5. Completeness Constraint:
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Chapter 03
Relational Model
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Database Relations
Relation schema
– Named relation defined by a set of attribute and
domain name pairs.
Properties of Relations
Relation name is distinct from all other relation names
in relational schema.
Each cell of relation contains exactly one atomic
(single) value.
Each attribute has a distinct name.
Values of an attribute are all from the same domain.
Each tuple is distinct; there are no duplicate tuples.
Order of attributes has no significance.
Order of tuples has no significance, theoretically.
Relational Keys
Superkey
– An attribute, or a set of attributes, that uniquely
identifies a tuple within a relation.
Candidate Key
– Superkey (K) such that no proper subset is a
superkey within the relation.
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Primary Key
– Candidate key selected to identify tuples uniquely
within relation.
Alternate Keys
– Candidate keys that are not selected to be primary
key.
Foreign Key
– Attribute, or set of attributes, within one relation
that matches candidate key of some (possibly same)
relation.
Relational Integrity
Null
– Represents value for an attribute that is currently
unknown or not applicable for tuple.
– Deals with incomplete or exceptional data.
– Represents the absence of a value and is not the
same as zero or spaces, which are values.
Entity Integrity
– In a base relation, no attribute of a primary key
can be null.
Referential Integrity
– If foreign key exists in a relation, either foreign
key value must match a candidate key value of some
tuple in its home relation or foreign key value must
be wholly null.
Enterprise Constraints
– Additional rules specified by users or database
administrators.
Views
Base Relation
– Named relation corresponding to an entity in
conceptual schema, whose tuples are physically
stored in database.
View
– Dynamic result of one or more relational operations
operating on base relations to produce another
relation.
A virtual relation that does not necessarily actually
exist in the database but is produced upon request, at
time of request.
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Purpose of Views
Updating Views
All updates to a base relation should be immediately
reflected in all views that reference that base relation.
If view is updated, underlying base relation should
reflect change.
There are restrictions on types of modifications that can
be made through views:
Updates are allowed if query involves a single base
relation and contains a candidate key of base
relation.
Updates are not allowed involving multiple base
relations.
Updates are not allowed involving aggregation or
grouping operations.
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Chapter 05
Introduction
Relational Algebra
Relational algebra operations work on one or more
relations to define another relation without changing the
original relations.
Both operands and results are relations, so output from
one operation can become input to another operation.
Allows expressions to be nested, just as in arithmetic.
This property is called closure.
Five basic operations in relational algebra: Selection,
Projection, Cartesian product, Union, and Set
Difference.
These perform most of the data retrieval operations
needed.
Also have Join, Intersection, and Division operations,
which can be expressed in terms of 5 basic operations.
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
(R)
predicate
– Works on a single relation R and defines a relation
that contains only those tuples (rows) of R that
satisfy the specified condition (predicate).
–
Example - Selection (or Restriction)
Projection
col1, . . . , coln(R)
– Works on a single relation R and defines a relation
that contains a vertical subset of R, extracting the
values of specified attributes and eliminating
duplicates.
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Example - Projection
Union
R S
– Union of two relations R and S defines a relation
that contains all the tuples of R, or S, or both R
and S, duplicate tuples being eliminated.
– R and S must be union-compatible.
Example - Union
city(Branch) city(PropertyForRent)
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Set Difference
R – S
– Defines a relation consisting of the tuples that are
in relation R, but not in S.
– R and S must be union-compatible.
Intersection
R S
– Defines a relation consisting of the set of all
tuples that are in both R and S.
– R and S must be union-compatible.
Expressed using basic operations:
R S = R – (R – S)
Example – Intersection
city(Branch) city(PropertyForRent)
Cartesian product
R X S
– Defines a relation that is the concatenation of
every tuple of relation R with every tuple of
relation S.
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Join Operations
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
R FS
– Defines a relation that contains tuples satisfying
the predicate F from the Cartesian product of R and
S.
– The predicate F is of the form R.ai S.bi where
may be one of the comparison operators (<, , >, ,
=, ).
Can rewrite Theta join using basic Selection and
Cartesian product operations.
R FS = F(R S)
Example - Equijoin
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Natural join
R S
– An Equijoin of the two relations R and S over all
common attributes x. One occurrence of each common
attribute is eliminated from the result.
Outer join
R S
– (Left) outer join is join in which tuples from R
that do not have matching values in common columns
of S are also included in result relation.
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
R S
F
– Defines a relation that contains the tuples of R
that participate in the join of R with S.
– Can rewrite Semijoin using Projection and Join:
– R F S = A(R F S)
Example - Semijoin
List complete details of all staff who work at the branch
in Glasgow.
Division
R S
– Defines a relation over the attributes C that consists
of set of tuples from R that match combination of every
tuple in S.
Example - Division
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Relational Calculus
Query-by-Example (QBE)
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Chapter : 06
SQL
Objectives of SQL
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
History of SQL
Importance of SQL
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
SELECT Statement
FROM Staff;
Use of DISTINCT
SELECT propertyNo
FROM Viewing;
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Calculated Fields
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Set Membership
Pattern Matching
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Use of COUNT(DISTINCT)
– column names
– aggregate functions
– constants
– expression involving combinations of the above.
SELECT branchNo,
COUNT(staffNo) AS count,
SUM(salary) AS sum
FROM Staff
GROUP BY branchNo
ORDER BY branchNo;
For each branch with more than 1 member of staff, find number
of staff in each branch and sum of their salaries.
SELECT branchNo,
COUNT(staffNo) AS count,
SUM(salary) AS sum
FROM Staff
GROUP BY branchNo
HAVING COUNT(staffNo) > 1
ORDER BY branchNo;
Subqueries
Subquery Rules
Multi-Table Queries
If result columns come from more than one table must use
a join.
Simple Join
List names of all clients who have viewed a property along
with any comment supplied.
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Sorting a join
For each branch, list numbers and names of staff who manage
properties, and properties they manage.
Computing a Join
Outer Joins
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
– Required data.
– Domain constraints.
– Entity integrity.
– Referential integrity.
– Enterprise constraints.
Required Data
position VARCHAR(10) NOT NULL
Domain Constraints
(a) CHECK
sex CHAR NOT NULL
CHECK (sex IN (‘M’, ‘F’))
CREATE DOMAIN
CREATE DOMAIN DomainName [AS] dataType
[DEFAULT defaultOption]
[CHECK (searchCondition)]
For example:
PRIMARY KEY(staffNo)
PRIMARY KEY(clientNo, propertyNo)
Can only have one PRIMARY KEY clause per table. Can still
ensure uniqueness for alternate keys using UNIQUE:
UNIQUE(telNo)
Data Definition
CREATE TABLE
ALTER TABLE
DROP TABLE
View
Dynamic result of one or more relational operations
operating on base relations to produce another relation.
For example:
Restrictions on Views
SELECT COUNT(cnt)
FROM StaffPropCnt;
SELECT *
FROM StaffPropCnt
WHERE cnt > 2;
(b) Grouped view may never be joined with a base table or a
view.
Advantages of Views
Data independence
Currency
Improved security
Reduced complexity
Convenience
Customization
Data integrity
Disadvantages of Views
Update restriction
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Performance
Transactions
Privileges
GRANT
Example
GRANT SELECT
ON Branch
TO PUBLIC;
REVOKE
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
REVOKE SELECT
ON Branch
FROM PUBLIC;
Revoke all privileges given to Director on Staff table.
Chapter 07
Introduction:
The collection of data that makes up a computerized
database must be stored physically on some computer storage
medium. The DBMS software that can then retrieve, update, and
process this data as needed. Computer storage media from a
storage hierarchy that includes two main categories,
Primary Storage
o The category includes storage media that can be
operated on directly by the computer Central
Processing Unit(CPU), such as the computer main
memory and smaller but faster cache memories.
Primary storage usually provides fast access to data
but is of limited storage capacity.
Secondary Storage
o This category includes magnetic disks, optical
disks, and tapes. These devices usually have a
larger capacity, cost less, and provide slower
access to data than do primary storage devices. Data
in secondary storage can not be processed directly
by the CPU: it must first be copied into primary
storage.
Cache
Main Memory
Flash memory
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Magnetic Disk
Optical Disk
Magnetic Tapes
Magnetic Disks :
Records:
Data is usually stored in the form of records. Each
record consists of a collection of related data values or
items, where each value is formed of one or more bytes and
corresponds to a particular field of the record.
FIGURE
Types of record organization. (a) Unspanned. (b) Spanned.
Figure : www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Hashing Technique:
A type of primary file organization is based on hashing,
which provides very fast access to records on certain search
conditions. This organization is usually called hash file.
The search condition is must be an equality condition on a
single field, called the hash field of the file. In most
cases, the hash field is also a key field of the file, in
which case it is called hash Key. The idea behind hashing is
to provide a function h, called a hash function or
randomizing function that is applied to the hash field value
of a record and yields the address of the disk block in
which the record is stored. A search for the record within
the block can be carried out in a main memory buffer.
Internal Hashing:
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
block of the data file and the keys of its anchor record
rather than for every search values( or every record).
Clustering Indexes:
If records of a file are physically ordered on a non key
field- which does not have a distinct value for each record-
that field is called the clustering field. We can create a
different type of index, called clustering index, to speed up
the retrieval of records that have the same value for the
clustering field. This differs from a primary index, which
requires that the ordering field of the data file have a
distinct value for each record. A clustering index is also an
ordered file with two fields.
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Multilevel Indexes:
The idea behind the multilevel index is to reduce the
part of the index that we continue to search the blocking
factor is larger than two. Hence the search space is reduced
mush faster.
The following figure explains this concept
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Chapter 08
Introduction
Query Processing
Query Optimization
SELECT *
FROM Staff s, Branch b
WHERE s.branchNo = b.branchNo AND
(s.position = ‘Manager’ AND b.city = ‘London’);
Assume:
– 1000 tuples in Staff; 50 tuples in Branch;
– 50 Managers; 5 London branches;
– no indexes or sort keys;
– results of any intermediate operations stored on
disk;
– cost of the final write is ignored;
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Cost Comparison
Database Statistics
nBlocks(R) = [nTuples(R)/bFactor(R)]
Rule-based
15 rules, ranked in order of efficiency. Particular
access path for a table only chosen if statement contains
a predicate or other construct that makes that access
path available.
Score assigned to each execution strategy using these
rankings and strategy with best (lowest) score selected.
SELECT propertyNo
FROM PropertyForRent
WHERE rooms > 7 AND city = ‘London’
Single-column access path using index on city from WHERE
condition (city = ‘London’). Rank 9.
Unbounded range scan using index on rooms from WHERE
condition (rooms > 7). Rank 11.
Full table scan - rank 15.
Although there is index on propertyNo, column does not
appear in WHERE clause and so is not considered by
optimizer.
Based on these paths, rule-based optimizer will choose to
use index based on city column.
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
QO in Oracle – Cost-Based
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Chapter 9
Transaction Processing:
Transaction:
Action, or series of actions, carried out by user or
application, which accesses or changes contents of database.
It Transforms database from one consistent state to another,
although consistency may be violated during transaction.
Properties of Transactions
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Concurrency control:
Processes of managing simultaneous operations on the
database without having them interfere with one another.
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
FIGURE
Some problems that occur when concurrent execution is
uncontrolled. (c) The incorrect summary problem.
Serializability
Schedule
Sequence of reads/writes by set of concurrent
transactions.
Serial Schedule
Schedule where operations of each transaction are
executed consecutively without any interleaved operations from
other transactions.
Nonserial Schedule
Serializability
In serializability, ordering of read/writes is important:
(a) If two transactions only read a data item, they do not
conflict and order is not important.
(b) If two transactions either read or write completely
separate data items, they do not conflict and order is not
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Serializability
Precedence Graph
Create:
– node for each transaction;
– a directed edge Ti Tj, if Tj reads the value of an
item written by TI;
– a directed edge Ti Tj, if Tj writes a value into
an item after it has been read by Ti.
If precedence graph contains cycle schedule is not
conflict serializable.
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
View Serializability
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Recoverability
Locking
Deadlock
An impasse that may result when two (or more) transactions are
each waiting for locks held by the other to be released.
Timeouts
Transaction that requests lock will only wait for a
system-defined period of time.
If lock has not been granted within this period, lock
request times out.
In this case, DBMS assumes transaction may be deadlocked,
even though it may not be, and it aborts and
automatically restarts the transaction.
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Deadlock Prevention
Several issues:
– choice of deadlock victim;
– how far to roll a transaction back;
– avoiding starvation.
Timestamping
Timestamp
A unique identifier created by DBMS that indicates
relative starting time of a transaction.
Optimistic Techniques
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Three phases:
– Read
– Validation
– Write
Tradeoff:
– coarser, the lower the degree of concurrency;
– finer, more locking information that is needed to be
stored.
Best item size depends on the types of transactions
Hierarchy of Granularity
Database Recovery
Types of Failures
Example
DBMS starts at time t0, but fails at time tf. Assume data
for transactions T2 and T3 have been written to secondary
storage.
T1 and T6 have to be undone. In absence of any other
information, recovery manager has to redo T2, T3, T4, and
T5.
Recovery Facilities
Log File
Checkpoint
Point of synchronization between database and log file.
All buffers are force-written to secondary storage.
Recovery Techniques
– Deferred Update
– Immediate Update
– Shadow Paging
Deferred Update
Updates are not written to the database until after a
transaction has reached its commit point.
If transaction fails before commit, it will not have
modified database and so no undoing of changes required.
May be necessary to redo updates of committed
transactions as their effect may not have reached
database.
Immediate Update
Shadow Paging
Chapter 10
Normalization
Data Redundancy
Data Redundancy
Update Anomalies
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Functional Dependency
Functional Dependency
– Describes relationship between attributes in a
relation.
– If A and B are attributes of relation R, B is
functionally dependent on A (denoted A B), if each
value of A in R is associated with exactly one value
of B in R.
Property of the meaning (or semantics) of the attributes
in a relation.
Diagrammatic representation:
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
UNF to 1NF
1NF to 2NF
2NF to 3NF
Identify the primary key in the 2NF relation.
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
4NF - Example
5NF - Example
More Notes:
Reflexive Rule :
if X ≤ Y, then XY
Augmentation Rule :
{XY} = XZ
Transitive Rule:
{XY, YZ} = XZ
Decomposition or Projective Rule
{XYZ } = XY
Union or additive Rule :
{XY , X Z} = XYZ
Pseudo Transitive Rule:
{XY, WYZ} = WXZ
Minimal sets of FD
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Introduction to PL/SQL
1. It acts as a support for SQL. Since it supports SQL data manipulation statement,
SQL transaction processing statement, SQL functions and SQL predicates we can
access the ORACLE database and manipulate its data flexibly and easily.
2. PL/SQL allows to declare variables and constants and use them in SQL and
procedural statements, any where an expression can be used. PL/SQL variables and
constants have attributes (%Type, %Rowtype) by which we can reference the data
type and structure of an object with out repeating its definition.
3. Control structures are the most important PL/SQL extension of SQL. It allows you
process the data using the conditional control statement(IF-THEN-ELSE), interative
control statement (LOOP END LOOP, FOR-LOOP and WHILE-LOOP) and
sequential control statement (GOTO), with the help of these statements we can
handle any situation.
4. A PL/SQL cursor gives you a way to fetch and process database information. There
are two types of cursors SXPLICIT and IMPLICIT CURSORS. PL/SQL declares
cursor implicitly for all SQL manipulation statements including queries that returns
one row. FOR queries that returns more than one row an explicit cursor has to be
declared.
5. Modularity is promoted because PL/SQL lets you break an application down into
manageable, well-defined logic modules.
6. Errors are easily detected and handled.
You can enter three kinds of commands from the SQL*Plus command prompt:
SQL*Plus commands – for formatting query results, setting options, and editing and
storing SQL commands and PL/SQL blocks. Eg.
SELECT*FROM TAB;
BEGIN
DBMS_OUTPUT.PUT_LINE(‘Hello World”);
END;
/
SQL*Plus Basics
Oracle’s SQL*Plus is a command line tool that allows a user to type SQL statements to
be executed directly against an Oracle database. SQL*Plus has the ability to format
database output, save often used commands and can be invoked from other Oracle tools
or from the operating system prompt.
PL/SQL is a block structured language. A block lets you group logically related
declarations and statements. The declarations are local to the block and cease to exist
when the block completes. A block has three parts: a declarative part, and executable
part, and an exception handling part (error handling).
DECLARE
<declaration>
BEGIN
<executable statements>
EXCEPTION
<exception handlers>
END;
The declarative part comes first in which the objects can be declared. Once declared
the objects can be manipulated in the executable part. Exceptions raised during
execution can be handled in the exception-handling part. We can nest sub-blocks in the
executable, exception part and not in declarative part. You can define subprograms
(Functions, Procedures) in the declarative part of any block. But it can be called with in
the block only. See example:
DECLARE
<declaration>
BEGIN
SUB-BLOCK1
DECLARE
<declarations>
BEGINwww.jntuworld.com
www.jntuworld.com www.jwjobs.net
EXCEPTION
<Exception handlers>
END;
SUB-BLOCK2
DECLARE
<declarations>
BEGIN
<executable statements>
<EXCEPTION>
<exception handlers>
END;
END;
Referring to the following sample PL/SQL block we have the following example.
DECLARE
Num_in_stock NUMBER(5);
BEGIN
SELECT quantity INTO num-in-stock FROM inventory_table
WHERE product = ‘TENNIS RACQUET’;
IF num_in_stock>0 THEN
END IF;
COMMIT;
END;
Advantages of PL/SQL
PL/SQL lets us to use all SQL data manipulation, cursor control and transaction
control commands as well as SQL functions, operators, and pseudocolumns.
Higher Productivity:-
Better Performance:-
With our PL/SQL Oracle must process SQL statements one at a time. It increases
network traffic. But with PL/SQL an entire block of SQL statements (more than one)
can be sent to Oracle at one time. Also with the procedural capabilities in enhances
performance.
Portability:-
Applications written in PL/SQL are portable to any operating system and platform in
which Oracle runs.
Character Set
PL/SQL is not case sensitive, so lower-case letters are equivalent to the corresponding
upper-case letters except within string (when surrounded by single quotes) or represent
the value of a character variable.
Delimiters:-
; statement terminator
% Attribute indicator (cursor attributes like % is open and indirect declaration
attributes like % Rowtype
- Single underscore: (single byte wildcard symbol as in SQL.
: Host variable indicator
<<and>>Label delimiters
:= Alignment operator
__ Single line comment
/* and */ Beginning and ending multilane comment block delimiters.
Identifiers:-
Binary Integer:-
It allows to stroe signed integers (-2^31 –1 through 2 ^31- Natural and positive are both
subtypes of Binary-integer
Number
Use the number data type to store fixed or floating point numbers of any size. The
maximum precision of a variable with Number type is 38 digits. While declaring we can
optionally specify the valuable precision as follows:
The precision of a Number is the total number of digits. The scale dictates the number
of digits to the right or left of the decimal point at which rounding occurs. The
remaining data types in number are all sub types of number. They have the same range
of values as their base type. The remaining data types in number are all sub types of
number. They have the same range of values as their base type.
Subtype Datatype
Char
Variables with character data types store text and are manipulated by character
functions. The CHAR data type takes an optional parameter that lets you specify a
maximum length upto 32767 bytes. The syntax is:-
CHAR (maximum_length)
Char Subtypes
The character subtypes have the same rang of values as their base type.
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Character
Varchar 2
It has the same syntax as Char. But the difference is, if we assign a character value to a
Char variable and if the length is shorter than the declared length of the variable
PL/SQL blankpads the value to the declared length. The VARCHAR is a subset of
VARCHAR2.
If we assign a character value to a Varchar2 variable, and if the value is shorter than
the declared length of the variable, PL/SQL neither blankpads the value nor strips
trailing blanks.
If we give name1 and name2 as Frank, name 1 will be stored internally as ‘Frank’ and
name2 as ‘Frank’. So even though the names are same since the data types are different
they are not same.
Long:-
The variable LONG can store variable-length strings of up to 32760 bytes which is
seven fewer bytes longer than allowed in Varchar2 type variables.
Date:-
The Date data type is to store fixed length data values. It also takes no parameters.
Valid dates include from Jan 1,4712 BC to December 31,4712 AD. When stored in a
database column, date values include to the first day of the current month; the time
portion defaults to midnight.
Declare Variable:-
Variable are declared in the DECLARE section of the PL/SQL block. Declaration
involves the name of the variable followed by its data type. All statements must end
with a semicolon. Initial values can also be assigned at the time of declaration.
Constants are declared by specifying the key work CONSTANT before the data type.
The syntax is:-
Example:
Declare Number
Count Number (9,2)
Secs_Per_Day Constant Number:= 60*60*24
First_Name Char
Last Name Varchar2
Birth_Day Date
Available Boolean := Null;
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
……………..
……………..
Comparisions
PL/SQL supports the comparison of variables and constants in SQL and PL/SQL
statements. These comparisons called Boolean expressions, generally consists of simple
expressions separated by Relational operators (=,!=,<,>, >=, <=). Boolean expressions
are often connected by the logical operators AND, OR, NOT. In PL/SQL a Boolean
expression always evaluates to TRUE, FALSE OR NULL. In a SQL statement Boolean
expression allow you to control which rows in a table are affected by the statement. In a
non SQL statement, Boolean expressions are the basis for conditional control.
Boolean Expression:-
ename>empname
ename != ‘frank’
Operator Meaning
= Is the Same As
!= Is Not The Same As
< Comes Alphabetically before
> Comes Alphabetically After
<= Comes Alphabetical Before
PL/SQL supports a variety of data types that you can use for declaring variables and
constants. You can assign values to variables as you declare them and you can change
the value of a variable through further assignments.
You must assign the value of a constant to it when you declare it, this value is fixed and
cannot be changed at run time.
DECLARE
V_NUM1 NUMBER NOT NULL:=10109;
NUM8 NUMBER(3,1);
XYZ NUMBER(2,2):=31.8;
ABC12 NUMBER(9,2):=XYZ*131;
V_CHR1 CHAR(89);
V_CHR2 VARCHAR2(12):= “JANUARY”;
TODAY DATE:= SYSDATE; www.jntuworld.com
www.jntuworld.com www.jwjobs.net
DECLARE
When you declare PL/SQL variables to hold column values you must ensure that the
variable type is the same as the column type else you will get a run time error at
execution. You can use the %TYPE attribute to base a variable upon the column
definition as defined within the Oracle data dictionary. The attribute is prefixed with
the schema, table and column name and used where the datatype is required in the
DECLARE SECTION. PL/SQL determines the datatype and size of the variable when
the block is complied and so is always compatible with the column used to populate it.
An example follows:-
DECLARE
V_NUM1 JD11.BOOK.COST%TYPE;
PL/SQL Editor:-
PL/SQL Editor is nothing but where you type all the pl/sql programs. In the following
sections we see how to write different types of programs using the standard structures
available in PL/SQL.
Pl/SQL Structures
Using SQL statements, we can retrieve or manipulate data present in a table. Using
SQL statements above it is not possible to gain the power of procedural language
constructs. This aspect has been taken care of by PL/SQL, which is of a procedural
extension of SQL.
A PL/SQL block can contain DML & DCL statements, but not DDL statements – but
not DDL statements. A PL/SQL block can also contain any number of SQL statements
integrated with flow of control statements. Using PL/SQL we can also trap runtime
errors.
With PL/SQL, you can use SQL statements to manipulate Oracle data and flow control
statements to process data to meet all your requirements. PL/SQL combines the data
manipulating power of SQL with the data-processing power of procedural languages.
PL/SQL provides many different structures to control the flow of your statement
execution and data handling.
Control structures are the most important PL/SQL extensions to SQL. Not only does
PL/SQL let you manipulate data, it lets you process the data using conditional, iterative,
sequential, and unconditional flow-control statements such as if-then-else, for loop,
while-loop, exit-when and goto.
Control Structures:-
There are three types of control statements. Conditional control, Iterative control and
Sequential control. The conditional control returns a Boolean value. The iterative
control executes a sequence of statements repeatedly. The sequential statements execute
a sequence of statements in the order in which they occur.
Conditional Control:-
The IF statement lets you execute a series of statements conditionally. There are three
forms IF-THEN, IF-THEN-ELSE, and IF-THEN-ELSIF.
If-then
IF condition THEN
Sequence of statements;
END IF;
Example:
IF Sales>Quata THEN
Combute_bonus(empid);
UPDATE payrole SET pay + bonus WHERE EMPNO = EMP_ID;
END IF;
If-then-else
The second form of IF statements adds the keywords ELSE followed by alternative
sequence of statements. The sequence of statements in the ELSE clause will be executed
only when the condition evaluates to FALSE.
IF condition THEN
Sequence of statement
ELSE
Sequence of statements
END IF;
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Example:-
The third form introduces the keyword ELSIF to introduce additional conditions. If
any condition evaluates to TRUE then that sequence of statements get executed. We
can have any number of ELSIF clause but the last one is optional.
If conditiona 1 THEN
Sequence of statements;
ELSIF
Sequence of statements;
ELSIF
Sequence of statements;
END IF;
SQL>declare
2 length number(3):=10;
3 breadth number(3):=12;
4 area number(5);
5 begin
6 if length>=0 then
7 if breadth <=0 then
8 dbms_output.put_line(‘Breadth cant be less than 0’);
9 else
10 area:=.5 * length * breadth;
11 dbms_output.put_line(‘Breadth cant be less than 0’);
12 end if;
13 else
14 dbms_output.put_line(‘Length cant be less than 0’);
15 end if;
16 end;
17/
Area is 60
PL/SQL procedure successfully completed.
Iterative Control
Loop statements lets you use the iterative type of control. There are three forms of
LOOP statements. LOOP, WHILE-LOOP and FOR-LOOP.
Loop www.jntuworld.com
www.jntuworld.com www.jwjobs.net
The simplest form is the infinite LOOP, WHICH encloses sequence of statements
between the key words LOOP and END LOOP.
LOOP
Sequence of statements;
END LOOP;
Exit
The EXIT statement is used to complete the loop. You can place one or more EXIT
statement inside a LOOP. The EXIT-WHEN statement allows a loop to complete
conditionally when the condition in the WHEN clause is evaluated.
Loop
If..then
Exit; - Exit Loop
End If;
End Loop;
Loop
Fetch C1 Into …
Exit When C1% Notfound…
End Loop;
Example
SQL>declare
2 counter binary_integer:=1;
3 begin
4 loop
5 dbms_output.put_line(‘Counter values is’ || counter);
6 demb_output.put_line( “);
7 counter:=counter+1;
8 exit when counter>5;
9 end loop;
10 end;
/
Counter values is 1
Counter values is 2
Counter values is 2
Counter values is 3
Counter values is 5
Loop Labels
Like PL/SQL blocks LOOPS can be labeled. The label, an undeclared identifier enclsed
by double angle brackets, must appear at the beginning of the LOOP statement as
follows:
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Loop
……….
End Loop Label_Name;
<<Outer Block>>
While-loop
Consider the following example. This block uses a simple WHILE loop to insert 5 rows
into a table. The values of a counter variable, and either of two character strings are
inserted. Which string is inserted depends on the value of the loop index.
Table created.
<SQL>DECLARE
2 x NUMBER: = 100;
3 BEGIN
4 WHILE x<501 LOOP
5 INSERT INTO TEMP VALUES (X);
6 x:= x+100;
7 END LOOP;
8 COMMIT;
9 END;
10 /
For-loop
For example consider the following example which will check the value I is even or odd
and inserts the data accordingly.
Table created
SQL>DECLARE
2 x NUMBER:=100;
3 BEGIN
4 FOR I IN 1..5 LOOP
5 IF MOD(I,2) =0 THEN – I is even
6 INSERT INTO temp VALUES(i,x, ‘i(even)’;
7 ELSE
8 INSERT INTO temp VALUES(i,x, ‘i(odd)’;
9 END IF;
10 x:=x+100;
11 END LOOP;
12 COMMIT;
13 END;
14/
Loop
Sequential Control
Goto
The GOTO statement branches to a label unconditionally. The label must be unique
within its scope and must precede an executable statement or a PL/SQL block. When
executed, the GOTO statement transfers control to the labeled statement or block. The
syntax is below:-
BEGIN
……
GOTO test_line;
…...
<<test line>>
……
END;
NULL STATEMENT
The NULL statement specified inaction, it does nothing other than pass control to the
next statement. It can, however, improve readability. In a construct allowing
alternative actions, the NULL statement serves as a place holder.
If
Score>100 Then
Compute_Bonus(Batsma_Id);
Else
Null;
End If:
Cursors
A cursor is a variable that runs through the tuples of some relation. This relation can
be a stored table, or it can be the answer to some query. By fetching into the cursor
each tuple of the relation, we can write a program to read and process the value of each
such tuple. If the relation is stored, we can also update or delete the tuple at the current
cursor position.
To process a SQL statement, PL/SQL opens work are called private SQL area. PL/SQL
allows user to name the private work areas and access the stored information. The
PL/SQL construct to identify each and every work area used is called CURSOR. There
are two types of cursors namely IMPLICIT and EXPLICIT.
Explicit Cursor
The set of rows returned by a query can consist of Zero, one or many rows, depending
upon the number of rows that meet the query’s search condition. When a query returns
multiple rows, a cursor can be explicitly defined to:
Declare Cursor
Declare the cursor to associate its name with a select statement. Forward references are
not allowed in PL/SQL. So we must declare cursor before referencing in other
statements.
DECLARE
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Example:
Open Cursor
Opening the cursor executes the query and identifies the active set which consists of all
rows that meet the query search criteria.
OPEN<cursor_name>;
Fetch Cursor
The fetch statement retrieves the rows in the active set one at a time. Each time the
fetch is executed the cursor and advances to the next row in the active set.
FETCH<cursor_name>INTO<var, var2..>;
For each column value returned by the query associated with the cursor, there must be
a corresponding variable in the INTO list. Their datatypes must also be compatible.
Close Cursor
Close the cursor to free up the resources. The close statement disables the cursor and
the active set becomes undefined. No more rows can be fetched from a closed cursor.
CLOSE<cursor_name>;
Example
SQL>DECLARE CURSOR c1 IS
2 SELECT ename, sal FROM emp;
3 name emp.ename%type;
4 salary emp.sal%type;
5 BEGIN
6 OPEN
7 for I in 1..5
8 LOOP
9 FETCH c1 INTO name, salary;
10 dbms_output.put_line(‘Name is’ || name || ‘Salary is’|| salary);
11 end loop;
12 close c1;
13 end;
14/ www.jntuworld.com
www.jntuworld.com www.jwjobs.net
1) DECLARE
/* Output variables to hold the result of the query:*/
2) a T1.e%TYPE;
3) b T1.f%TYPE;
/*cursor declaration:*/
4) CURSOR T1Cursor IS
5) SELECT e,f
6) FROM T1
7) WHERE e<f
8) FOR UPDATE;
9) BEGIN
10 OPEN T1Cursor;
11 LOOP
/* retrieve each row of the result of the above query
into PL/SQL variables:*/
12) FETCH T1Cursor INTO a,b;
/* If there are no more rows to fetch, exit the loop:*/
13) EXIT WHEN T1 CURSOR%NOTFOUNT;
14) /DELETE FROM T1 WHERE CURRENT OF T1Cursor;
/* Insert the reverse tuple:*/
15) INSERT INTO T1 VALUES (b,a);
16) END LOOP;
/*Free cursor used by the query.*/
17) CLOSE T1 Cursor;
18) END;
19) .
20) run;
Subprograms
The PL/SQL programs can be stored in the database as stored programs and can be
invoked whenever required. This avoids repassing when multiple users invoke it. This
also provides security and integrity control by allowing access on the sub program and
not on the database objects directly. Actually subprograms are named PL/SQL blocks
that can take parameters and be invoked.
What Is A Subprogram?
Subprograms are PL/SQL blocks that can take parameter and can be invoked.
Provides extensibility
Provides modularity
Promotes reusability and manageability
Using Subprograms
Executable statements
[EXCEPTIONS]
END [name];
Where parameter stands for
Var_name [IN/OUT/IN OUT] datatype
[{:=!DEFAULT} value]
A procedure has two parts the SPECIFICATION and the BODY. A specification
begins with the keyword PROCEDURE and ends with the procedure name or
parameter list. A body begins with the keywords IS and ends with the keyboard END.
A body has three parts a DECLARATIVE PART, an EXECUTABLE part, and an
optional EXCEPTION handling part.
PL/SQL procedures behave very must like procedures in other programming language.
Here is an example of a PL/SQL PROCEDURE addtuple1 that, given an integer I,
inserts the tuple (i, ‘xxx’) into the following example relation:
CREATE TABLE T2 (
a INTEGER,
b CHAR(10)
CREATE Procedure addtuple1 (i IN NUMBER) AS
BEGIN
INSERT INTO T2 VALUES(i. ‘xxx’);
END addtuple1;
be a different procedure of the same name, you will not be warned, and the old
procedure will be lost.
There can any number of parameters, each followed by a mode and a type. The
possible modes are IN (read-only), OUT(write-only), and INOUT(read and write).
BEGIN
Addtyple1(99);
END;
The following procedure also inserts a tuple into T2, but it takes both components as
arguments:
CREATE TABLE T3 (
a INTEGER,
b INTEGER
);
Note that assigning values to parameters declared as OUT or INOUT causes the
corresponding input arguments to be written. Because of this, the input argument for
an OUT or INOUT parameter should be something with an “lvaluse”, such as a
variable like v in the example above. A constant or a literal argument should not be
passed in for an OUT/INOUT parameter.
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
Procedure created.
The procedure named MYPROC1 is defined in the first line. CREATE OR REPLACE
asks Oracle to create a new procedure or if a procedure with this name already exists in
this schema to replace it. You may leave out the OR REPLACE if you don’t want this
to happen. The DECLARE section is now implicitly the section between the procedure
definition and the BEGIN statement – it is declared after the procedure declaration.
The END statement now ends a named block rather than an unnamed block. Nothing
else is required for a procedure to run. To execute the stored procedure simply do the
fallowing.
SQL>EXEC MYPROC1;
PL/SQL procedure successfully completed.
Functions:
A function has two parts SPECIFICATION and Body. The specification begins with
the keywords FUNCTION and ends with the RETURN clause which specified the
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
the keyword END with an optional name. BODY has three parts as that of the
procedure.
The function below demonstrates the syntax of a PL/SQL function block, note that as
with a procedure the OR REPLACE clause can be left out if you don’t want the
replacement of an existing function with the same name. Function definition vary from
procedure definitions in that you must explicitly name a variable to return and you
must return a value in the variable via the RETURN statement.
If the salary is out of range sal_ok is set to false; otherwise, sal_ok is set to true. A
function is called as a part of an expression. The function sal_ok is called as
Introduction to Triggers:-
ORACLE allows you to define procedures that are implicitly executed when an insert,
update, delete statement is issued against the associated table. These procedures are
called database triggers. Triggers can be defined only on tables and not on views. The
triggers which we use in FORMS are different since they are fired only when a trigger
point is executed with in a specific application in FORMS. The database trigger is
executed against a table, no matter what user or application issues the statement (insert,
update, delete). So the triggering event is either a INSERT, DELETE, or UPDATE
command.
A trigger event or statement is the SQL statement that causes a trigger to be fired. A
trigger event can be an insert, update or delete statement for a specific table.
A trigger restriction specifies a BOOLEAN expression that must be run for the trigger
to fire. The trigger action wont take place if it evaluates to false. For example, it will
fire when the condition is true.
Quantity_On_Hand<Reorder_Level
A trigger action is the procedure that contains the SQL statements and PL/SQL code to
be executed when a triggering statement is issued and the trigger restriction evaluates to
true.
You can create only BEFORE and AFTER triggers for tables. (INSTEAD OF
triggers are only available for views; typically they are used to implement view
updates.)
You may specify up to three triggering events using the keyword OR.
Furthermore, UPDATE canwww.jntuworld.com
be optionally followed by the keyword OF a list of
www.jntuworld.com www.jwjobs.net
… INSERT ON R …
… INSERT OR DELETE OR UPDATE ON R …
…UPDATE OF A,B OR INSERT ON R…
If FOR EACH ROW option is specified, the trigger is row-level; otherwise, the
trigger is statement-level.
For a row-level trigger, a trigger restriction can be specified in the WHEN
clause, enclosed by parentheses. The trigger restriction is a SQL condition that
must be satisfied in order for ORACLE to fire the trigger. This condition cannot
contain subqueries. Without the WHEN clause, a trigger is fired by every
triggering event.
<trigger_body> is a PL/SQL block, rather than sequence of SQL statements.
Oracle has placed certain restrictions on what you do in <trigger_body>, in
order to avoid situations where one trigger performs an action that triggers a
second trigger, which then triggers a third, and so on, which could potentially
create an infinite loop.
You cannot modify the same relation whose modifiction is the event triggering
the trigger.
You cannot modify a relation connected to the triggering relation by another
constraint such as a foreign-key constraint.
Types of Triggers
In the case of DML triggers you can write triggers for insert, update or delete
operations on a detabase table. In the case of instead-of triggers you can define triggers
even on views. This kind of triggers can be defined on views only.
In the above syntax trigger name refers to the name of the trigger, triggering event
specifies the event that fires the trigger. The referencing clause is used to refer to the
data in the row currently being modified, trigger condition is a valid condition in the
when clause and trigger_body is the main code of the trigger.
www.jntuworld.com
www.jntuworld.com www.jwjobs.net
There are two levels of triggers namely ROW level and STATEMENT level. A row
trigger is fired for each time the table is affected by the triggering statement. A
statement type trigger is fired once on behalf of the triggering statement regardless of
the number of rows in the table affected.
TRIGGER TIMING
BEFORE triggers execute the trigger action before the triggering statement. AFTER
triggers execute the action after the triggering statement is executed. So with these
combinations we can create four types as follows:
www.jntuworld.com