0% found this document useful (0 votes)
16 views54 pages

ADBMS Unit1 2

The document provides an overview of transaction management and distributed databases, focusing on the definition of transactions, their ACID properties (Atomicity, Consistency, Isolation, Durability), and various states of transactions (Active, Partially Committed, Committed, Failed, Aborted). It also discusses recovery methods, failure classifications, and the Two-Phase Commit protocol for ensuring consistency across distributed systems. Additionally, it highlights the challenges and disadvantages associated with these processes, particularly in multi-user environments.

Uploaded by

ompatel4624
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views54 pages

ADBMS Unit1 2

The document provides an overview of transaction management and distributed databases, focusing on the definition of transactions, their ACID properties (Atomicity, Consistency, Isolation, Durability), and various states of transactions (Active, Partially Committed, Committed, Failed, Aborted). It also discusses recovery methods, failure classifications, and the Two-Phase Commit protocol for ensuring consistency across distributed systems. Additionally, it highlights the challenges and disadvantages associated with these processes, particularly in multi-user environments.

Uploaded by

ompatel4624
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Ganpat University

Department of Computer Science

B.Sc.IT(Data Science)-Sem-3

U73A2ADS:Advance Database Management System

UNIT-1 Transaction Management and Distributed


Database:
What is Transaction in DBMS?
We can define a transaction as a group of tasks in DBMS. Here a single
task refers to a minimum processing unit, and we cannot divide it further.
Now let us take the example of a certain simple transaction. Suppose any
worker transfers Rs 1000 from X’s account to Y’s account. This given small
and simple transaction involves various low-level tasks.
X’s Account
Open_Account(X)
Old_Bank_Balance = X.balance
New_Bank_Balance = Old_Bank_Balance – 1000
A.balance = New_Bank_Balance
Close_Bank_Account(X)
Y’s Account
Open_Account(Y)
Old_Bank_Balance = Y.balance
New_Bank_Balance = Old_Bank_Balance + 1000
B.balance = New_Bank_Balance
Close_Bank_Account(Y)

ACID Properties
The transaction refers to a small unit of any given program that consists
of various low-level tasks. Every transaction in DBMS must maintain ACID
– A (Atomicity), C (Consistency), I (Isolation), D (Durability). One must
maintain ACID so as to ensure completeness, accuracy, and integrity of
data.

1. Atomicity

The property of atomicity states that we must treat any given transaction
as an atomic unit. It means that either all or none of its operations need
to be executed. One must ensure that there is no state in the database in
which a transaction happens to be left partially completed. One must
either define the states before or after the execution/failure/abortion of
the transaction.

2. Consistency

The property of consistency states that the database must always remain
in a consistent state after any transaction. Thus, a transaction must never
have any damaging effect on the data and information that resides in the
database. In case, before the execution of a transaction, the database
happens to be in a consistent state, then it has to remain consistent even
after the transaction gets executed.

3. Durability

The property of durability states that any given database must be durable
enough to all of its latest updates, and it must happen even if the system
suddenly restarts or fails. The database would hold the modified data in
case a transaction updates and commits some chunk of information in the
database. In case a transaction commits and yet the system fails before we
write the data on the disk, then the information would be actually updated
after the system springs back into action.
4. Isolation

The property of isolation states that when multiple transactions are being
simultaneously executed and in parallel in a database system, then the
carrying out and execution of the transaction would occur as if it is the
only transaction that exists in the system. None of the transactions would
affect any other transaction’s existence.

States of Transaction

In a database, the transaction can be in one of the following states -

Active state
o The active state is the first state of every transaction. In this state,
the transaction is being executed.
o For example: Insertion or deletion or updating a record is done here.
But all the records are still not saved to the database.

Partially committed
o In the partially committed state, a transaction executes its final
operation, but the data is still not saved to the database.
o In the total mark calculation example, a final display of the total
marks step is executed in this state.
Committed

A transaction is said to be in a committed state if it executes all its


operations successfully. In this state, all the effects are now permanently
saved on the database system.

Failed state
o If any of the checks made by the database recovery system fails, then
the transaction is said to be in the failed state.
o In the example of total mark calculation, if the database is not able
to fire a query to fetch the marks, then the transaction will fail to
execute.

Aborted
o If any of the checks fail and the transaction has reached a failed state
then the database recovery system will make sure that the database
is in its previous consistent state. If not then it will abort or roll back
the transaction to bring the database into a consistent state.
o If the transaction fails in the middle of the transaction then before
executing the transaction, all the executed transactions are rolled
back to its consistent state.
o After aborting the transaction, the database recovery module will
select one of the two operations:
1. Re-start the transaction
2. Kill the transaction

Recovery

DBMS is a highly complex system with hundreds of transactions being


executed every second. The durability and robustness of a DBMS depends
on its complex architecture and its underlying hardware and system
software. If it fails or crashes amid transactions, it is expected that the
system would follow some sort of algorithm or techniques to recover lost
data.
Failure Classification

To see where the problem has occurred, we generalize a failure into


various categories, as follows −
Transaction failure
A transaction has to abort when it fails to execute or when it reaches a
point from where it can’t go any further. This is called transaction failure
where only a few transactions or processes are hurt.
Reasons for a transaction failure could be −
• Logical errors − Where a transaction cannot complete because it
has some code error or any internal error condition.
• System errors − Where the database system itself terminates an
active transaction because the DBMS is not able to execute it, or it
has to stop because of some system condition. For example, in case
of deadlock or resource unavailability, the system aborts an active
transaction.
System Crash
There are problems − external to the system − that may cause the system
to stop abruptly and cause the system to crash. For example, interruptions
in power supply may cause the failure of underlying hardware or software
failure.
Examples may include operating system errors.
Disk Failure
In early days of technology evolution, it was a common problem where
hard-disk drives or storage drives used to fail frequently.
Disk failures include formation of bad sectors, unreachability to the disk,
disk head crash or any other failure, which destroys all or a part of disk
storage.
Types of recovery
Log-Based Recovery
o The log is a sequence of records. Log of each transaction is maintained in some stable
storage so that if any failure occurs, then it can be recovered from there.
o If any operation is performed on the database, then it will be recorded in the log.
o But the process of storing the logs should be done before the actual transaction is
applied in the database.

Let's assume there is a transaction to modify the City of a student. The following logs
are written for this transaction.

o When the transaction is initiated, then it writes 'start' log.


1. <Tn, Start>
o When the transaction modifies the City from 'Noida' to 'Bangalore', then another log
is written to the file.
1. <Tn, City, 'Noida', 'Bangalore' >
o When the transaction is finished, then it writes another log to indicate the end of the
transaction.
1. <Tn, Commit>

There are two approaches to modify the database:

1. Deferred database modification:


o The deferred modification technique occurs if the transaction does not modify the
database until it has committed.
o In this method, all the logs are created and stored in the stable storage, and the
database is updated when a transaction commits.

2. Immediate database modification:


o The Immediate modification technique occurs if database modification occurs while
the transaction is still active.
o In this technique, the database is modified immediately after every operation. It follows
an actual database modification.

Recovery using Log records


When the system is crashed, then the system consults the log to find which
transactions need to be undone and which need to be redone.
1. If the log contains the record <Ti, Start> and <Ti, Commit> or <Ti, Commit>, then the
Transaction Ti needs to be redone.
2. If log contains record<Tn, Start> but does not contain the record either <Ti, commit>
or <Ti, abort>, then the Transaction Ti needs to be undone.

Checkpoint
o The checkpoint is a type of mechanism where all the previous logs are removed from
the system and permanently stored in the storage disk.
o The checkpoint is like a bookmark. While the execution of the transaction, such
checkpoints are marked, and the transaction is executed then using the steps of the
transaction, the log files will be created.
o When it reaches to the checkpoint, then the transaction will be updated into the
database, and till that point, the entire log file will be removed from the file. Then the
log file is updated with the new step of transaction till next checkpoint and so on.
o The checkpoint is used to declare a point before which the DBMS was in the consistent
state, and all transactions were committed.

Recovery using Checkpoint


In the following manner, a recovery system recovers the database from this failure:
o The recovery system reads log files from the end to start. It reads log files from T4 to
T1.
o Recovery system maintains two lists, a redo-list, and an undo-list.
o The transaction is put into redo state if the recovery system sees a log with <Tn, Start>
and <Tn, Commit> or just <Tn, Commit>. In the redo-list and their previous list, all the
transactions are removed and then redone before saving their logs.
o For example: In the log file, transaction T2 and T3 will have <Tn, Start> and <Tn,
Commit>. The T1 transaction will have only <Tn, commit> in the log file. That's why
the transaction is committed after the checkpoint is crossed. Hence it puts T1, T2 and
T3 transaction into redo list.
o The transaction is put into undo state if the recovery system sees a log with <Tn, Start>
but no commit or abort log found. In the undo-list, all the transactions are undone,
and their logs are removed.
o For example: Transaction T4 will have <Tn, Start>. So T4 will be put into undo list since
this transaction is not yet complete and failed amid.

Two phase commit


o Consider we are given with a set of grocery stores where the head of all store
wants to query about the available sanitizers inventory at all stores in order to
move inventory store to store to make balance over the quantity of sanitizers
inventory at all stores. The task is performed by a single transaction T that’s
component Tn at the nth store and a store S0 corresponds to T0 where the
manager is located. The following sequence of activities are performed
by T are below:
o a) Component of transaction( T ) T0 is created at the head-site(head-office).
o b) T0 sends messages to all the stores to order them to create components Ti.
o c) Every Ti executes a query at the store “i” to discover the quantity of
available sanitizers inventory and reports this number to To.
o d) Each store receives instruction and update the inventory level and made
shipment to other stores where require.
o But there are some problems that we may face during the execution of
this process:
o 1) Atomicity property may be violated because any store(Sn) may be
instructed twice to send the inventory that may leave the database in an
inconsistent state. To ensure atomicity property Transaction T must either
commit at all the sites, or it must abort at all sites.
o 2) However, the system at store Tn may crash, and the instructions
from T0 are never received by Tn because of any network issue and any other
reason. So the question arises what will happen to the distributed transaction
running whether it abort or commit? Whether it recover or not?
o Two-Phase Commit Protocol: This protocol is designed with the core intent
to resolve the above problems, Consider we have multiple distributed
databases which are operated from different servers(sites) let’s say S1, S2, S3,
….Sn. Where every Si made to maintains a separate log record of all
corresponding activities and the transition T has also been divided into the
subtransactions T1, T2, T3, …., Tn and each Ti are assigned to Si. This all
maintains by a separate transaction manager at each Si. We assigned anyone
site as a Coordinator.
o Some points to be considered regarding this protocol:
o a) In a two-phase commit, we assume that each site logs actions at that site,
but there is no global log.
o b) The coordinator(Ci), plays a vital role in doing confirmation whether the
distributed transaction would abort or commit.
o c) In this protocol messages are made to send between
the coordinator(Ci) and the other sites. As each message is sent, its logs are
noted at each sending site, to aid in recovery should it be necessary.
o The two phases of this protocol are as follow:
o Phase-1st–
o a) Firstly, the coordinator(Ci) places a log record <Prepare T> on the log
record at its site.
o b) Then, the coordinator(Ci) sends a Prepare T message to all the sites
where the transaction(T) executed.
o c) Transaction manager at each site on receiving this message Prepare
T decides whether to commit or abort its component(portion) of T. The site
can delay if the component has not yet completed its activity, but must
eventually send a response.
o d) If the site doesn’t want to commit, so it must write on log record <no
T>, and local Transaction manager sends a message abort T to Ci.
o e) If the site wants to commit, it must write on log record <ready T>, and
local Transaction manager sends a message ready T to Ci. Once the ready T
message at Ci is sent nothing can prevent it to commit its portion
of transaction T except Coordinator(Ci).
o
o Messaging in Phase- 1st

o Phase- 2nd–
o The Second phase started as the response abort T or commit T receives
by the coordinator(Ci) from all the sites that are collaboratively executing
the transaction T. However, it is possible that some site fails to respond; it
may be down, or it has been disconnected by the network. In that case, after
a suitable timeout period will be given, after that time it will treat the site as if
it had sent abort T. The fate of the transaction depends upon the following
points:
o a) If the coordinator receives ready T from all the participating sites of T, then
it decides to commit T. Then, the coordinator writes on its site log
record <Commit T> and sends a message commit T to all the sites involved
in T.
o b) If a site receives a commit T message, it commits the component of T at
that site, and write it in log records <Commit T>.
o c) If a site receives the message abort T, it aborts T and writes the log
record <Abort T>.
o d) However, if the coordinator has received abort T from one or more sites, it
logs <Abort T> at its site and then sends abort T messages to all sites
involved in transaction T.
o
o Messaging in Phase- 2nd

o Disadvantages:
o a) The major disadvantage of the Two-phase commit protocol is faced when
the Coordinator site failure may result in blocking, so a decision either to
commit or abort Transaction(T) may have to be postponed until coordinator
recovers.
o b) Blocking Problem: Consider a scenario, if a Transaction(T) holds locks
on data-items of active sites, but amid the execution, if the coordinator fails
and the active sites keep no additional log-record except <readt
T> like <abort> or <commit>. So, it becomes impossible to determine what
decision has been made(whether to <commit> /<abort>). So, In that case,
the final decision is delayed until the Coordinator is restored or fixed. In some
cases, this may take a day or long hours to restore and during this time period,
the locked data items remain inaccessible for other transactions(Ti). This
problem is known as Blocking Problem.

Concurrent Execution in DBMS


o In a multi-user system, multiple users can access and use the same database at one
time, which is known as the concurrent execution of the database. It means that the
same database is executed simultaneously on a multi-user system by different users.
o While working on the database transactions, there occurs the requirement of using the
database by multiple users for performing different operations, and in that case,
concurrent execution of the database is performed.
o The thing is that the simultaneous execution that is performed should be done in an
interleaved manner, and no operation should affect the other executing operations,
thus maintaining the consistency of the database. Thus, on making the concurrent
execution of the transaction operations, there occur several challenging problems that
need to be solved.

Problems with Concurrent Execution


In a database transaction, the two main operations are READ and WRITE operations.
So, there is a need to manage these two operations in the concurrent execution of the
transactions as if these operations are not performed in an interleaved manner, and
the data may become inconsistent. So, the following problems occur with the
Concurrent Execution of the operations:

Problem 1: Lost Update Problems (W - W Conflict)


The problem occurs when two different database transactions perform the read/write
operations on the same database items in an interleaved manner (i.e., concurrent
execution) that makes the values of the items incorrect hence making the database
inconsistent.

00:00/04:28

Consider the below diagram where two transactions TX and TY, are performed on
the same account A where the balance of account A is $300.
o At time t1, transaction TX reads the value of account A, i.e., $300 (only read).
o At time t2, transaction TX deducts $50 from account A that becomes $250 (only
deducted and not updated/write).
o Alternately, at time t3, transaction TY reads the value of account A that will be $300
only because TX didn't update the value yet.
o At time t4, transaction TY adds $100 to account A that becomes $400 (only added but
not updated/write).
o At time t6, transaction TX writes the value of account A that will be updated as $250
only, as TY didn't update the value yet.
o Similarly, at time t7, transaction TY writes the values of account A, so it will write as
done at time t4 that will be $400. It means the value written by TX is lost, i.e., $250 is
lost.

Hence data becomes incorrect, and database sets to inconsistent.

Dirty Read Problems (W-R Conflict)


The dirty read problem occurs when one transaction updates an item of the database,
and somehow the transaction fails, and before the data gets rollback, the updated
database item is accessed by another transaction. There comes the Read-Write Conflict
between both transactions.

For example:

Consider two transactions TX and TY in the below diagram performing read/write


operations on account A where the available balance in account A is $300:

o At time t1, transaction TX reads the value of account A, i.e., $300.


o At time t2, transaction TX adds $50 to account A that becomes $350.
o At time t3, transaction TX writes the updated value in account A, i.e., $350.
o Then at time t4, transaction TY reads account A that will be read as $350.
o Then at time t5, transaction TX rollbacks due to server problem, and the value changes
back to $300 (as initially).
o But the value for account A remains $350 for transaction TY as committed, which is the
dirty read and therefore known as the Dirty Read Problem.

Unrepeatable Read Problem (W-R Conflict)


Also known as Inconsistent Retrievals Problem that occurs when in a transaction, two
different values are read for the same database item.

For example:
Consider two transactions, TX and TY, performing the read/write operations on
account A, having an available balance = $300. The diagram is shown below:

o At time t1, transaction TX reads the value from account A, i.e., $300.
o At time t2, transaction TY reads the value from account A, i.e., $300.
o At time t3, transaction TY updates the value of account A by adding $100 to the
available balance, and then it becomes $400.
o At time t4, transaction TY writes the updated value, i.e., $400.
o After that, at time t5, transaction TX reads the available value of account A, and that will
be read as $400.
o It means that within the same transaction TX, it reads two different values of account A,
i.e., $ 300 initially, and after updation made by transaction TY, it reads $400. It is an
unrepeatable read and is therefore known as the Unrepeatable read problem.

Thus, in order to maintain consistency in the database and avoid such problems that
take place in concurrent execution, management is needed, and that is where the
concept of Concurrency Control comes into role.

Locking
Lock guaranties exclusive use of data items to a current transaction. It first accesses
the data items by acquiring a lock, after completion of the transaction it releases the
lock.
Types of Locks
The types of locks are as follows −
1. Shared Lock [Transaction can read only the data item values]
It is also known as a Read-only lock. In a shared lock, the data item can only
read by the transaction.
It can be shared between the transactions because when the transaction holds
a
lock, then it can't update the data on the data item.
2. Exclusive Lock [Used for both read and write data item values]
In the exclusive lock, the data item can be both reads as well as written by
the transaction.
This lock is exclusive, and in this lock, multiple transactions do not modify
the same data simultaneously.

Two-phase locking (2PL)

➢ The two-phase locking protocol divides the execution phase of the


➢ transaction into three parts.
➢ In the first part, when the execution of the transaction starts, it seeks
➢ permission for the lock it requires.
➢ In the second part, the transaction acquires all the locks. The third phase is
➢ started as soon as the transaction releases its first lock.
➢ In the third phase, the transaction cannot demand any new locks. It only
➢ releases the acquired locks.
There are two phases of 2PL:

Growing phase: In the growing phase, a new lock on the data item may be acquired by

the transaction, but none can be released.

Shrinking phase: In the shrinking phase, existing lock held by the transaction may be

released, but no new locks can be acquired.

In the below example, if lock conversion is allowed then the following phase can

happen:

1. Upgrading of lock (from S(a) to X (a)) is allowed in growing phase.

2. Downgrading of lock (from X(a) to S(a)) must be done in shrinking phase.

Deadlock in DBMS
A deadlock is a condition where two or more transactions are waiting indefinitely for
one another to give up locks. Deadlock is said to be one of the most feared
complications in DBMS as no task ever gets finished and is in waiting state forever.

For example: In the student table, transaction T1 holds a lock on some rows and needs
to update some rows in the grade table. Simultaneously, transaction T2 holds locks on
some rows in the grade table and needs to update the rows in the Student table held
by Transaction T1.

Now, the main problem arises. Now Transaction T1 is waiting for T2 to release its lock
and similarly, transaction T2 is waiting for T1 to release its lock. All activities come to a
halt state and remain at a standstill. It will remain in a standstill until the DBMS detects
the deadlock and aborts one of the transactions.
Deadlock Avoidance
o When a database is stuck in a deadlock state, then it is better to avoid the database
rather than aborting or restating the database. This is a waste of time and resource.
o Deadlock avoidance mechanism is used to detect any deadlock situation in advance. A
method like "wait for graph" is used for detecting the deadlock situation but this
method is suitable only for the smaller database. For the larger database, deadlock
prevention method can be used.

Deadlock Detection
In a database, when a transaction waits indefinitely to obtain a lock, then the DBMS
should detect whether the transaction is involved in a deadlock or not. The lock
manager maintains a Wait for the graph to detect the deadlock cycle in the database.

Wait for Graph


o This is the suitable method for deadlock detection. In this method, a graph is created
based on the transaction and their lock. If the created graph has a cycle or closed loop,
then there is a deadlock.
o The wait for the graph is maintained by the system for every transaction which is
waiting for some data held by the others. The system keeps checking the graph if there
is any cycle in the graph.
The wait for a graph for the above scenario is shown below:

Deadlock Prevention
o Deadlock prevention method is suitable for a large database. If the resources are
allocated in such a way that deadlock never occurs, then the deadlock can be
prevented.
o The Database management system analyzes the operations of the transaction whether
they can create a deadlock situation or not. If they do, then the DBMS never allowed
that transaction to be executed.

Wait-Die scheme
In this scheme, if a transaction requests for a resource which is already held with a
conflicting lock by another transaction then the DBMS simply checks the timestamp of
both transactions. It allows the older transaction to wait until the resource is available
for execution.

Let's assume there are two transactions Ti and Tj and let TS(T) is a timestamp of any
transaction T. If T2 holds a lock by some other transaction and T1 is requesting for
resources held by T2 then the following actions are performed by DBMS:

1. Check if TS(Ti) < TS(Tj) - If Ti is the older transaction and Tj has held some resource,
then Ti is allowed to wait until the data-item is available for execution. That means if
the older transaction is waiting for a resource which is locked by the younger
transaction, then the older transaction is allowed to wait for resource until it is available.
2. Check if TS(Ti) < TS(Tj) - If Ti is older transaction and has held some resource and if Tj
is waiting for it, then Tj is killed and restarted later with the random delay but with the
same timestamp.

Wound wait scheme


o In wound wait scheme, if the older transaction requests for a resource which is held by
the younger transaction, then older transaction forces younger one to kill the
transaction and release the resource. After the minute delay, the younger transaction
is restarted but with the same timestamp.
o If the older transaction has held a resource which is requested by the Younger
transaction, then the younger transaction is asked to wait until older releases it.

What is Encryption?
Encryption helps us to secure data that we send, receive, and store. It can
consist text messages saved on our cell-phone, logs stored on our fitness
watch, and details of banking sent by your online account.

It is the way that can climb readable words so that the individual who has the
secret access code, or decryption key can easily read it. For diplomatic
information to help in providing data security.

A large volume of personal information is handled electronically and


maintained in the cloud or on servers connected to the web on an ongoing
basis. Without our distinctive data bending up in the networked systematic
system of a company, it's almost not possible to go on with the business of
any, which is why it is crucial to know how to help in keeping the information
private.

How does it work?


It is the procedure of taking ordinary text, such as a text or email, and climbing
it into an unreadable type of format known as "cipher text." It helps to protect
the digital information either saved on or spread through a network such as the
internet on computer systems.

The cipher text is converted back to the real form when the calculated recipient
accesses the message which is known as decryption.
"Secret" encryption key, a lining up of algorithms that climbed and unscramble
info. back to a readable type, must be worked by both the sender and the
receiver to get the code.

Introduction to Database Security:


There are three main objectives when designing a secure database application:
1. Secrecy: Information should not be disclosed to unauthorized users. For example, a
student
should not be allowed to examine other students' grades.
2. Integrity: Only authorized users should be allowed to modify data. For example,
students may
be allowed to see their grades, yet not allowed (obviously) to modify therm.
3. Availability: Authorized users should not be denied access. For example, an
instructor who wishes to change a grade should be allowed to do so.

To achieve these objectives, a clear and consistent security policy should


be developed to describe what security measures must be enforced. determine what
part of the data is to be protected and which users get access to which portions of the
data. Next, the security mechanisms of the underlying DBMS and operating system.

ACCESS CONTROL:
A database for an enterprise contains a great deal of information and usually has several
groups of users. Most users need to access only a small part of the database to carry out
their tasks.

User’s unrestricted access to all the data can be undesirable, and a DBMS should provide
to control access to data .A DBMS offers two main approaches to access control.
Discretionary access control is based on the concept of access rights, or privileges, and
mechanisms for giving users such privileges. A privilege allows a user to access Borne data
object (e.g., to read or Modify). A user, who creates a database object such as a table or a
vie\v automatically, gets all applicable privileges on that object.

Mandatory access control is based on system wide policies that cannot be changed by
individual users. In this approach each databal.'3e object is assigned a security class, each
user is assigned clearance for a security class, and rules are imposed on reading and writing
of database objects by users.

DISCRETIONARY ACCESS CONTROL

SQL supports discretionary access control through the GRANT and REVOKE commands.
The GRANT command gives users privileges to base tables and views. The syntax of this
command is as follows

GRANT privileges ON object TO users [WITH GRANT OPTION]

For our purposes object is either a base table or a views. Several privileges can be
specified,including these:

SELECT: The right to access (read) all columns of the table specified as the object,

including columns added later through ALTER TABLE commands.

INSERT( column-name): The right to insert rows with (non-null or non default) values in
the column of the table named as object. If this right is to be granted with respect to all
columns, including columns that might be added later, we can simply use INSERT. The
privileges UPDATE( column name) and UPDATE are similar.

DELETE: The right to delete rows from the table named as object.
REFERENCES(column-name): The right to define foreign keys (in other tables) that

refer to the specified column of the table object. REFERENCES without a column name
specified denotes this right with respect to all columns, including any that are added later.

GRANT AND REVOKE ON VIEWS AND INTEGRITY CONSTRAINTS

The privileges held by the creator of a view change over time as he or she gains or loses

privileges on the underlying tables. If the creator loses a privilege held 'with the grant
option,

users who where given that privilege on the view lose it as well. 'There are some subtle
aspects to the GRANT and REVOKE commands when they involve views or integrity
constraints. We

consider some examples that highlight the following important points

1) A view may be dropped because a SELECT privilege is revoked from the user who

created the view.

2) If the creator of a view gains additional privileges on the underlying tables, he or she

automatically gains additional privileges on the view.

3) The distinction between the REFERENCES and SELECT privileges are important.

MANDATORY ACCESS CONTROL

Discretionary access control mechanisms, while generally effective, have certain


weaknesses. In particular they are susceptible to Trojan horse schemes whereby a devious
unauthorized user can trick an authorized user into disclosing sensitive data.

The popular model for mandatory access control is described in terms of objects (e.g.,
tables, views, rows, columns), subjects (e.g., users,programs), security classes, and
clearances.

Each database object is assigned a security class, and each subject is assigned clearance
for security class; we denote the class of an object or subject A as class(A).
The model imposes two restrictions on all reads and writes of database objects:

1) Simple Security Property: Subject S is allowed to read object 0 only if class(8) > class

(()). For example, a user with TS clearance can read a table with C clearance, but a user

with C clearance is not allowed to read a table with TS classification.

2) *-Property: Subject S is allowed to write object 0 only if class(S) <class (O). For

example, a user with S clearance can write only objects with S or TS classification.

Distributed Database:
A distributed database is a collection of multiple interconnected databases, which are
spread physically across various locations that communicate via a computer network.

Distributed Database Management System


A distributed database management system (DDBMS) is a centralized software
system that manages a distributed database in a manner as if it were all stored in
a single location.
The Twelve Objectives
(1) Local autonomy
The sites in a distributed system should be autonomous. In this context, autonomy
means that:

• local data is locally owned and managed;


• local operations remain purely local;
• all operations at a given site are controlled by that site.

(2) No reliance on a central site


There should be no one site without which the system cannot operate. This implies
that there should be no central servers for services such as transaction management,
deadlock detection, query optimization, and management of the global system
catalog.

(3) Continuous operation


Ideally, there should never be a need for a planned system shutdown, for operations
such as: n adding or removing a site from the system; n the dynamic creation and
deletion of fragments at one or more sites.

(4) Location independence


Location independence is equivalent to location transparency. The user should be
able to access the database from any site. Furthermore, the user should be able to
access all data as if it were stored at the user’s site, no matter where it is physically
stored.

(5) Fragmentation independence


The user should be able to access the data, no matter how it is fragmented.

(6) Replication independence


The user should be unaware that data has been replicated. Thus, the user should not
be able to access a particular copy of a data item directly, nor should the user have
to specifically update all copies of a data item.

(7) Distributed query processing


The system should be capable of processing queries that reference data at more than
one site.

(8) Distributed transaction processing


The system should support the transaction as the unit of recovery. The system should
ensure that both global and local transactions conform to the ACID rules for
transactions, namely: atomicity, consistency, isolation, and durability.

(9) Hardware independence


It should be possible to run the DDBMS on a variety of hardware platforms.

(10) Operating system independence


As a corollary to the previous rule, it should be possible to run the DDBMS on a
variety of operating systems.

(11) Network independence


Again, it should be possible to run the DDBMS on a variety of disparate
communication networks.

(12) Database independence


It should be possible to have a DDBMS made up of different local DBMSs, perhaps
supporting different underlying data models. In other words, the system should
support heterogeneity. The last four rules are ideals. As the rules are so general, and
as there is a lack of stand- ards in computer and network architectures, we can
expect only partial compliance from vendors in the foreseeable future.

Problems Areas of Distributed Database


Distributed Concurrency Control: - Distributed Concurrency Control specifies that
synchronization of access to the distributed database such that the integrity of the
database is maintained. To maintain Concurrency in distributed database different
locking techniques should used which is based on mutual exclusion of access to data.
Time stamping algorithm also used where transactions are executed in some order.
2) Distributed Deadlock Management :- In distributed database several users are
request for resources from the database if the resources are available at that time ,
then database grant the resources to that user if not available the user has to wait
until the resources are released by other user. Sometimes the users are not released
the resources are blocked by some other user. This situation is known as Deadlock.
Distributed Deadlock is manage using the different algorithm and techniques such
avoidance and detection algorithm.
3) Replication Control: - Replication is a technique that only applies to distributed
systems. A database is said to be replicated if the entire database or a portion of it (a
table, some tables, one or more fragments, etc.) is copied and the copies are stored
at different sites. The issue with having more than one copy of a database is
maintaining the mutual consistency of the copies—ensuring that all copies have
identical schema and data content .
4) Operating Environment: - To Implement Distributed Database Environment a
Specific Operating System is requirement as per Organizational needs. Operating
system plays and important role for managing the distributed database. Some time
Operating system is not supported for Distributed database.
5) Transparent Management: - Transparent management of Data is one of the major
problem area in Distributed database. In Distributed database data is situated in
multiple locations and number of users are used that database. To maintain the
integrity of database transparent management of data is important.
6) Security and privacy: - How to apply the security policies to the interdependent system is
a great issue in distributed system. Since distributed systems deal with sensitive data and
information so the system must have a strong security and privacy measurement. Protection
of distributed system assets, including base resources, storage, communications and user-
interface I/O as well as higher level composites of these resources, like processes, files,
messages, display windows and more complex objects, are important issues in distributed
system
7) Resource management: - In distributed systems, objects consisting of resources are
located on different places. Routing is an issue at the network layer of the distributed system
and at the application layer. Resource management in a distributed system will interact with
its eterogeneous Nature.

UNIT-2 INTRODUCTION TO PL/SQL

What is PL/SQL
PL/SQL is a block structured language. The programs of PL/SQL are logical blocks
that can contain any number of nested sub-blocks. Pl/SQL stands for "Procedural
Language extension of SQL" that is used in Oracle. PL/SQL is integrated with Oracle
database (since version 7). The functionalities of PL/SQL usually extended after each
release of Oracle database. Although PL/SQL is closely integrated with SQL language,
yet it adds some programming constraints that are not available in SQL.

PL/SQL Advantages

PL/SQL offers the following advantages:


▪ Reduces network traffic This one is great advantages of PL/SQL. Because
PL/SQL nature is entire block of SQL statements execute into oracle
engine all at once so it's main benefit is reducing the network traffic.

▪ Procedural language support PL/SQL is a development tools not only for data
manipulation futures but also provide the conditional checking, looping or
branching operations same as like other programming language.

▪ Error handling PL/SQL is dealing with error handling, It's permits the smart
way handling the errors and giving user friendly error messages, when the
errors are encountered.

▪ Declare variable PL/SQL gives you control to declare variables and access
them within the block. The declared variables can be used at the time
of query processing.

▪ Intermediate Calculation Calculations in PL/SQL done quickly and efficiently


without using Oracle engines. This improves the transaction performance.

▪ Portable application Applications are written in PL/SQL are portable in


any Operating system. PL/SQL applications are independence program to
run any computer.

Following are few more PL/SQL advantages:

▪ PL/SQL is a very secure functionality tool for manipulating, controlling,


validating, and restricting unauthorized access data from the SQL database.

▪ Using PL/SQL we can improve application performance. It also allows


to deal with errors so we can provide user friendly error messages.

▪ PL/SQL have a great functionality to display multiple records from the


multiple tables at the same time.

▪ PL/SQL is capable to send entire block of statements and execute it in


the Oracle engine at once.

PL/SQL Block Structure


What is PL/SQL block? PL/SQL block structure divided into three logical blocks.
First, BEGIN block and END; keywords are compulsory. However, the other two
blocks DECLARE and EXCEPTION are optional block. Technically, END; is not a block, it
is only keyword to end of PL/SQL program.
PL/SQL code is not executed in single line format like SQL. It is always executed by a
grouping of code into a single segment called blocks.

PL/SQL block structure follows the divide-and-conquer approach to solve the


problem stepwise.

PL/SQL block Structure

PL/SQL Block Structure


DECLARE
Variables and constants are declared, initialized within this section.

Variables and Constants: In this block, declare and initialize variables (and constants).
You must have to declare variables and constants in the declarative block before
referencing them in a procedural statement.

Declare Variables and Assigning values: You can define a variable name, data type of a
variable, and its size. Date type can be CHAR, VARCHAR2, DATE, NUMBER, INT, or
any other.

BEGIN
BEGIN block is a procedural statement block which will implement the actual
programming logic. This section contains conditional statements (if...else), looping
statements (for, while) and Branching Statements (goto), etc.
EXCEPTION
PL/SQL easily detects a user-defined or predefined error condition. PL/SQL is famous
for smartly handling errors by giving suitable user-friendly messages. Errors can be
rise due to the wrong syntax, bad logical, or not passing validation rules.

You can also define exception in your declarative block, and later you can execute it
by RAISE statement.

Note

1. BEGIN block, and END; keyword are compulsory of any PL/SQL program.
2. Whereas, the DECLARE and EXCEPTION block are optional.

The PL/SQL Character Set

A PL/SQL program consists of a sequence of statements, each made up of one or


more lines of text. The precise characters available to you will depend on what
database character set you’re using.

Characters available to PL/SQL in the character set

Letters A-Z, a-z


Digits 0-9
Symbols ~!@#$%&*()_-+=|[]{}:;"'<>,.?/^
Whitespace Tab, space, newline, carriage return

Every keyword in PL/SQL is made from various combinations of characters in this


character set. Now you just have to figure out how to put them all together!

By default, PL/SQL is a case-insensitive language. That is, uppercase letters are


treated the same way as lowercase letters except when characters are surrounded by
single quotes, which makes them a literal string.

A number of these characters—both singly and in combination with other characters

PL/SQL Literals
Literals are the explicit numeric, character, string or boolean values which are not
represented by an identifier. For example: TRUE, NULL, etc. are all literals of type
boolean. PL/SQL literals are case-sensitive. There are following kinds of literals in
PL/SQL:

o Numeric Literals
o Character Literals
o String Literals
o BOOLEAN Literals

Literals Examples
Numeric 75125, 3568, 33.3333333 etc.
Character 'A' '%' '9' ' ' 'z' '('
String Hello
Boolean TRUE, FALSE, NULL etc.

Introduction to PL/SQL data types


Each value in PL/SQL such as a constant, variable and parameter has a data type that
determines the storage format, valid values, and allowed operations.
PL/SQL divides the scalar data types into four families:

• Number
• Boolean
• Character
• Datetime

Number data types


The numeric data types represent real numbers, integers, and floating-point
numbers. They are stored as NUMBER

Boolean data type


The BOOLEAN datatype has three data values: TRUE, FALSE, and NULL. Boolean values
are typically used in control flow structure such as IF-THEN, CASE, and loop
statements like LOOP, FOR LOOP, and WHILE LOOP.

Char data types


The character data types represent alphanumeric text. PL/SQL uses the SQL character
data types such as CHAR, VARCHAR2, LONG, RAW, LONG RAW, ROWID, and UROWID.

• CHAR(n) is a fixed-length character type whose length is from 1 to 32,767


bytes.
• VARCHAR2(n) is varying length character data from 1 to 32,767 bytes.

Datetime data types


The datetime data types represent dates, timestamp with or without time zone and
intervals. PL/SQL datetime data types are DATE, TIMESTAMP, TIMESTAMP WITH TIME
ZONE, TIMESTAMP WITH LOCAL TIME ZONE, INTERVAL YEAR TO MONTH, and INTERVAL DAY TO
SECOND.

PL/SQL Variables
A variable is a meaningful name which facilitates a programmer to store data
temporarily during the execution of code. It helps you to manipulate data in PL/SQL
programs. It is nothing except a name given to a storage area. Each variable in the
PL/SQL has a specific data type which defines the size and layout of the variable's
memory.

How to declare variable in PL/SQL


You must declare the PL/SQL variable in the declaration section or in a package as a
global variable. After the declaration, PL/SQL allocates memory for the variable's value
and the storage location is identified by the variable name.

Following is the syntax for declaring variable:

1. variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]

Here, variable_name is a valid identifier in PL/SQL and datatype must be valid PL/SQL
data type. A data type with size, scale or precision limit is called a constrained
declaration. The constrained declaration needs less memory than unconstrained
declaration.

Example:

Radius Number := 5;

Date_of_birth date;

Naming rules for PL/SQL variables


The variable in PL/SQL must follow some naming rules like other programming
languages.

o The variable_name should not exceed 30 characters.


o Variable name should not be the same as the table table's column of that block.
o The name of the variable must begin with ASCII letter. The PL/SQL is not case
sensitive so it could be either lowercase or uppercase. For example: v_data and
V_DATA refer to the same variables.
o You should make your variable easy to read and understand, after the first
character, it may be any number, underscore (_) or dollar sign ($).
o NOT NULL is an optional specification on the variable.
Initializing Variables in PL/SQL
Evertime you declare a variable, PL/SQL defines a default value NULL to it. If you want
to initialize a variable with other value than NULL value, you can do so during the
declaration, by using any one of the following methods.

1. counter binary_integer := 0;

Example of initilizing variable


Let's take a simple example to explain it well:

1. DECLARE
2. a integer := 30;
3. b integer := 40;
4. c integer;
5. f real;
6. BEGIN
7. c := a + b;
8. dbms_output.put_line('Value of c: ' || c);
9. f := 100.0/3.0;
10. dbms_output.put_line('Value of f: ' || f);
11. END;

After the execution, this will produce the following result:

Value of c: 70
Value of f: 33.333333333333333333

PL/SQL procedure successfully completed.

PL/SQL Comment>
PL/SQL Comments you can write single line comments or either multiple line
comments,

▪ Multi-line comments and


▪ Single line comments

Multi-line comments are delimited with /*..COMMENT TEXT..*/ and


Single-line comments starts with two dashes --.
PL/SQL Comments can begin in any column on any line. If you are embedding
comments in SQL that will be embedded in PL/SQL you need to be careful for writing
a column.

Comment Syntax
SQL>-- Single Line Comment
SQL>/* Multiline Comment line 1
Multiline Comment line2 */

PL/SQL IF THEN ELSE Statements (Conditional Control)


PL/SQL IF THEN ELSE conditional control statements. PL/SQL Conditional Control two
type: IF THEN ELSE statement

PL/SQL IF statement check condition and transfer the execution flow on that
matched block depending on a condition. IF statement execute or skip a sequence of
one or more statements. PL/SQL IF statement four different type,

1. IF THEN Statement
2. IF THEN ELSE Statement
3. IF THEN ELSIF Statement
4. Nested IF THEN ELSE Statement

IF THEN Statement
IF THEN Statement write in following syntax format:
IF ( condition ) THEN
statement
END IF;

Example

We declare one number with initialize 14 value is equal of condition value,


Comparing 2 values by using IF THEN statement,
DECLARE
no number := 14;
BEGIN
IF ( no = 14 ) THEN
DBMS_OUTPUT.PUT_LINE('condition true');
END IF;
END;

IF THEN ELSE Statement


IF THEN ELSE Statement write in following syntax format:
IF ( condition ) THEN
statement;
ELSE
statement;
END IF;

Example

Same as above example if condition not true then else part will execute.
DECLARE
no number := 14;
BEGIN
IF ( no = 11 ) THEN
DBMS_OUTPUT.PUT_LINE(no || ' is same');
ELSE
DBMS_OUTPUT.PUT_LINE(no || ' is not same');
END IF;
END;
/

IF THEN ELSIF Statement


IF THEN ELSIF Statement write in following syntax format:
IF ( condition-1 ) THEN
statement-1;
ELSIF ( condition-2 ) THEN
statement-2;
ELSIF ( condition-3 ) THEN
statement-3;
ELSE
statement;
END IF;

Example

Here one student result example for archiving grade.


DECLARE
result CHAR(20) := 'second';
BEGIN
IF ( result = 'distinction' ) THEN
DBMS_OUTPUT.PUT_LINE('First Class with Distinction');
ELSIF ( result = 'first' ) THEN
DBMS_OUTPUT.PUT_LINE('First Class');
ELSIF ( result = 'second' ) THEN
DBMS_OUTPUT.PUT_LINE('Second Class');
ELSIF ( result = 'third' ) THEN
DBMS_OUTPUT.PUT_LINE('Third Class');
ELSE
DBMS_OUTPUT.PUT_LINE('Fail');
END IF;
END;

Nested IF THEN ELSE Statement


Logically IF THEN ELSIF Statement and Nested IF THEN ELSE Statement both are
same. Nested IF THEN ELSE Statement write in following syntax format:
IF ( condition-1 ) THEN
statement-1;
ELSE
IF ( condition-2 ) THEN
statement-2;
ELSE
IF ( condition-3 ) THEN
statements-3;
END IF;
END IF;
END IF;

Example

Here check condition students gender male, if not male then finding the result using
nested IF THEN ELSE statement.
DECLARE
gender CHAR(10) := 'female';
result CHAR(20) := 'second';
BEGIN
IF ( gender = 'male' ) THEN
DBMS_OUTPUT.PUT_LINE('Gender Male Record Skip!');
ELSE
IF ( result = 'distinction' ) THEN
DBMS_OUTPUT.PUT_LINE('First Class with Distinction');
ELSIF ( result = 'first' ) THEN
DBMS_OUTPUT.PUT_LINE('First Class');
ELSIF ( result = 'second' ) THEN
DBMS_OUTPUT.PUT_LINE('Second Class');
ELSIF ( result = 'third' ) THEN
DBMS_OUTPUT.PUT_LINE('Third Class');
ELSE
DBMS_OUTPUT.PUT_LINE('Fail');
END IF;
END IF;
END;
/

PL/SQL Loop
PL/SQL Loop Basic Loop, FOR Loop, WHILE Loop repeat a number of block
statements in your PL/SQL program. Loop use when we have a block of statements
for required to repeatedly certain number of times. PL/SQL loop statements 3
different forms:

1. Basic LOOP
2. WHILE LOOP
3. FOR LOOP

Oracle recommended to write a label when use loop statement. It's benefit to
improve readability. label is not compulsory for execute loop. compiler does not
check to label defined or not. Define label before LOOP keyword and after END
LOOP keyword.

Basic LOOP
Basic LOOP write in following syntax format:
[ label_name ]LOOP
statement(s);
END LOOP [ label_name ];

Example
DECLARE
no NUMBER := 5;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE ('Inside value: no = ' || no);
no := no -1;
IF no = 0 THEN
EXIT;
END IF;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Outside loop end');
END;
/

Result
Inside value: no = 5
Inside value: no = 4
Inside value: no = 3
Inside value: no = 2
Inside value: no = 1
Outside loop end

WHILE LOOP
WHILE LOOP write in following syntax format:
[ label_name ] WHILE condition LOOP
statement(s);
END LOOP [ label_name ];

Example
DECLARE
no NUMBER := 0;
BEGIN
WHILE no < 10 LOOP
no := no + 1;
END LOOP;
DBMS_OUTPUT.PUT_LINE('no is :' || no);
END;
/

Result
No is : 10

PL/SQL procedure successfully completed.

FOR LOOP
FOR LOOP write in following syntax format:
[ label_name ] FOR current_value IN [ REVERSE ] lower_value..upper_value LOOP
statement(s);
END LOOP [ label_name ];

Example
BEGIN
FOR no IN 1 .. 5 LOOP
DBMS_OUTPUT.PUT_LINE('Iteration : ' || no);
END LOOP;
END;
/

Result
Iteration : 1
Iteration : 2
Iteration : 3
Iteration : 4
Iteration : 5

PL/SQL procedure successfully completed.

PL/SQL GOTO Statement


PL/SQL GOTO Statements (Sequential Control Statements) are control your iteration
loop. PL/SQL GOTO Statement transfers the program execution flow unconditionally.

GOTO Statement
GOTO statement unconditionally transfer program control. GOTO statement writing
syntax,

Syntax
GOTO code_name
-----------
-----------
<<code_name>>
-----------
-----------

Example
SQL>BEGIN
FOR i IN 1..5 LOOP
dbms_output.put_line(i);
IF i=4 THEN
GOTO label1;
END IF;
END LOOP;
<<label1>>
DBMS_OUTPUT.PUT_LINE('Row Filled');
END;
/

Result
1
2
3
4
Row Filled

PL/SQL procedure successfully completed.

PL/SQL Cursors
Oracle creates a memory area ,known as the context area ,for processing an SQL
statement ,which contains all the information needed for processing the statement;

For example,the number of rows processed,etc.

A cursor is a pointer to this context area.PL/SQL controls the context area througha
cursor. A cursor holds the rows(one or more)returned by a SQL statement.The set of

rows the cursor holds is referred to as the active set.

You can name a cursor so that it could be referred to in a program to fetch and
process

the rows returned by the SQL statement, one at a time.

There are two types of cursors:

How to Use Cursor


In PL/SQL block SELECT statement can not return more than one row at a time. So
Cursor use to some group of rows (more than one row) for implementing certain
logic to get all the group of records.

Classification of CURSORS
Cursors can be classified as:

1. Implicit Cursor or Internal Cursor Manage for Oracle itself or internal process itself.
2. Explicit Cursor or User-defined Cursor Manage for user/programmer or external
processing.

PL/SQL Implicit Cursor

Implicit Cursors

Implicit cursors are automatically created by Oracle whenever an SQL statement is

executed,when there is no explicit cursor for the statement.Programmers cannot

control the implicit cursors and the information in it. Whenever a DML
statement(INSERT,UPDATE and DELETE)is issued, an implicit cursor is associated with
this statement.For INSERT operations,the cursor holds the data that needs to be
inserted.For UPDATE and DELETE operations,the cursor identifies the rows that would
be affected. In PL/SQL,you can refer to the most recent implicit cursor as the SQL
cursor,which always has attributes such as%FOUND,%ISOPEN,%NOTFOUND,
and%ROWCOUNT.

Implicit Cursor Attributes


Following are implicit cursor attributes,

Cursor Cursor Variable Description


Attribute

%ISOPEN SQL%ISOPEN Oracle engine automatically open the cursor


If cursor open return TRUE otherwise return FALSE.

%FOUND SQL%FOUND If SELECT statement return one or more rows or DML statement
(INSERT, UPDATE, DELETE) affect one or more rows
If affect return TRUE otherwise return FALSE.
If not execute SELECT or DML statement return NULL.

%NOTFOUND SQL%NOTFOUND If SELECT INTO statement return no rows and fire no_data_found
PL/SQL exception before you can check SQL%NOTFOUND.
If not affect the row return TRUE otherwise return FALSE.

%ROWCOUNT SQL%ROWCOUNT Return the number of rows affected by a SELECT statement or DML
statement (insert, update, delete).
If not execute SELECT or DML statement return NULL.

Syntax
cursor_attribute ::=
{
cursor_name |
cursor_variable_name |
:host_cursor_variable_name
}
% {FOUND | ISOPEN | NOTFOUND | ROWCOUNT}

Explanation

cursor_name cursor_name identifies the current scope which are previously declared.
cursor_variable_name cursor variable or parameter identifies the current scope which
are previously declared.

host_cursor_variable_name host_cursor_variable_name must be prefixed with a colon.


Host cursor variable datatype must be compatible with the PL/SQL cursor variable.

implicit Cursor Example


Following one emp_information table:

EMP_NO EMP_NAME EMP_DEPT EMP_SALARY

1 Forbs ross Web Developer 45k

2 marks jems Program Developer 38k

3 Saulin Program Developer 34k

4 Zenia Sroll Web Developer 42k

Now above employee information table update the employee name 'Saulin'
department 'Program Developer' update to 'Web Developer'.

Example
implicit_cursor.sql

SQL>set serveroutput on
SQL>edit implicit_cursor
BEGIN
UPDATE demo SET name=’dax’
WHERE id=1;

IF SQL%FOUND THEN
dbms_output.put_line('Updated - If Found');
END IF;
IF SQL%NOTFOUND THEN
dbms_output.put_line('NOT Updated - If NOT Found');
END IF;

IF SQL%ROWCOUNT>0 THEN
dbms_output.put_line(SQL%ROWCOUNT||' Rows Updated');
ELSE
dbms_output.put_line('NO Rows Updated Found');
END;
/

Result
SQL>@implicit_cursor
Updated - If Found
1 Rows Updated

PL/SQL Explicit Cursor


Explicit Cursor which are construct/manage by user itself call explicit cursor.

User itself to declare the cursor, open cursor to reserve the memory and populate
data, fetch the records from the active data set one at a time, apply logic and last
close the cursor.

You can not directly assign value to an explicit cursor variable you have to use
expression or create subprogram for assign value to explicit cursor variable.

Declaring the Cursor

Declaring the cursor defines the cursor withaname and the associated SELECT
statement.For example-

CURSOR c_customers IS SELECT id,name,address FROM customers;

Opening the Cursor

Opening the cursor allocates the memory for the cursor and makes it ready for
fetching the rows returned by the SQL statement into it.For example,we will open the
above defined cursor as follows-
OPEN c_customers;

Fetching the Cursor

Fetching the cursor involves accessing one row atatime.For example,we will fetch rows
from the-opened cursor as follows-

FETCH c_customers INTOc_id,c_name,c_addr;

Closing the Cursor

Closing the cursor means releasing the allocated memory.For example,we will close
the above opened cursor as follows-

CLOSE c_customers;

Step for Using Explicit Cursor


1. Declare cursor

Declare explicit cursor has this syntax,


CURSOR cursor_name [ parameter ] RETURN return_type;
CURSOR cursor_name [ parameter ] [ RETURN return_type ]
IS SELECT STATEMENT;

Declaring explicit cursor example,


CURSOR c RETURN EMP_DEPT%ROWTYPE; -- Declare c

CURSOR c IS -- Define c,
SELECT * FROM emp_information; -- all row return type

CURSOR c RETURN EMP_DEPT%ROWTYPE IS -- Define c,


SELECT * FROM emp_information; -- repeating return type

2. Opening Explicit Cursor


DECLARE block you are already declare CURSOR now you can OPEN CURSOR
by using following way, and allocate some reserve area for process database
query.
OPEN cursor_name [( cursor_parameter )];

3. Loop

Loop iterate until ROW not found. Once found loop exit control goes next
statement (outside loop).

4. Fetching data from cursor

Using FETCH statement you can fetch CURSOR data into explicit variable.
FETCH cursor_name INTO variable;

5.Closing Explicit Cursor

This way you can close opened CURSOR.


CLOSE cursor_name [( cursor_parameter )];

Explicit Cursor Example


Following emp_information table having employee information, We'll update
information using Explicit Cursor,

EMP_NO EMP_NAME EMP_DEPT EMP_SALARY

1 Forbs ross Web Developer 45k

2 marks jems Program Developer 38k

3 Saulin Program Developer 34k

4 Zenia Sroll Web Developer 42k


Now above employee information table update the employee name 'Saulin'
department 'Program Developer' update to 'Web Developer'.

Example
explicit_cursor.sql

SQL>set serveroutput on
SQL>edit explicit_cursor
DECLARE
cursor c is select * from emp_information
where emp_name='bhavesh';
tmp emp_information%rowtype;
BEGIN
OPEN c;
Loop exit when c%NOTFOUND;
FETCH c into tmp;
update emp_information set tmp.emp_dept='Web Developer'
where tmp.emp_name='Saulin';
END Loop;
IF c%ROWCOUNT>0 THEN
dbms_output.put_line(SQL%ROWCOUNT||' Rows Updated');
ELSE
dbms_output.put_line('NO Rows Updated Found');
END IF;
CLOSE c;
END;
/

Result
SQL>@explicit_cursor
1 Rows Updated

PL/SQL procedure successfully completed.


PL/SQL Parameterized Cursor
PL/SQL Parameterized cursor pass the parameters into a cursor and use them in to
query.

PL/SQL Parameterized cursor define only datatype of parameter and not need to
define it's length.

Default values is assigned to the Cursor parameters. and scope of the parameters are
locally.

Parameterized cursors are also saying static cursors that can passed parameter value
when cursor are opened.

Following example introduce the parameterized cursor. following emp_information


table,

EMP_NO EMP_NAME EMP_DEPT EMP_SALARY

1 Forbs ross Web Developer 45k

2 marks jems Program Developer 38k

3 Saulin Program Developer 34k

4 Zenia Sroll Web Developer 42k

Example

Cursor display employee information from emp_information table whose emp_no


four (4).
parameter_cursor_demo.sql

SQL>set serveroutput on
SQL>edit parameter_cursor_demo
DECLARE
cursor c(no number) is select * from emp_information
where emp_no = no;
tmp emp_information%rowtype;
BEGIN
OPEN c(4);
FOR tmp IN c(4) LOOP
dbms_output.put_line('EMP_No: '||tmp.emp_no);
dbms_output.put_line('EMP_Name: '||tmp.emp_name);
dbms_output.put_line('EMP_Dept: '||tmp.emp_dept);
dbms_output.put_line('EMP_Salary:'||tmp.emp_salary);
END Loop;
CLOSE c;
END;
/

Result
SQL>@parameter_cursor_demo
EMP_No: 4
EMP_Name: Zenia Sroll
EMP_Dept: Web Developer
EMP_Salary: 42k

PL/SQL procedure successfully completed.

Important key point you must remember

1. Scope of the parameters are locally


2. You can assign default value to a cursor parameter.

Introduction to PL/SQL cursor FOR LOOP statement


➢ The cursor FOR LOOP statement is an elegant extension of the numeric FOR
LOOP statement.
➢ The numeric FOR LOOP executes the body of a loop once for every integer
value in a specified range. Similarly, the cursor FOR LOOP executes the body of
the loop once for each row returned by the query associated with the cursor.
➢ A nice feature of the cursor FOR LOOP statement is that it allows you to fetch
every row from a cursor without manually managing the execution cycle
i.e., OPEN, FETCH, and CLOSE.
➢ The cursor FOR LOOP implicitly creates its loop index as a record variable with
the row type in which the cursor returns and then opens the cursor.
➢ In each loop iteration, the cursor FOR LOOP statement fetches a row from the
result set into its loop index. If there is no row to fetch, the cursor FOR
LOOP closes the cursor.
➢ The cursor is also closed if a statement inside the loop transfers control
outside the loop, e.g., EXIT and GOTO, or raises an exception.

The following illustrates the syntax of the cursor FOR LOOP statement:

FOR record IN cursor_name


LOOP
process_record_statements;
END LOOP;
Code language: SQL (Structured Query Language) (sql)

1) record

The record is the name of the index that the cursor FOR LOOP statement declares
implicitly as a %ROWTYPE record variable of the type of the cursor.

The record variable is local to the cursor FOR LOOP statement. It means that you can
only reference it inside the loop, not outside. After the cursor FOR LOOP statement
execution ends, the record variable becomes undefined.

2) cursor_name

The cursor_name is the name of an explicit cursor that is not opened when the loop
starts.

Note that besides the cursor name, you can use a SELECT statement as shown below:

FOR record IN (select_statement)


LOOP
process_record_statements;
END LOOP;
Code language: SQL (Structured Query Language) (sql)

In this case, the cursor FOR LOOP declares, opens, fetches from, and closes an implicit
cursor. However, the implicit cursor is internal; therefore, you cannot reference it.
Note that Oracle Database automatically optimizes a cursor FOR LOOP to work
similarly to a BULK COLLECT query. Although your code looks as if it fetched one row at
a time, Oracle Database fetches multiple rows at a time and allows you to process
each row individually.

PL/SQL cursor FOR LOOP examples


Let’s look at some examples of using the cursor FOR LOOP statement to see how it
works.

A) PL/SQL cursor FOR LOOP example

The following example declares an explicit cursor and uses it in the cursor FOR
LOOP statement.

DECLARE
CURSOR c_product
IS
SELECT
product_name, list_price
FROM
products
ORDER BY
list_price DESC;
BEGIN
FOR r_product IN c_product
LOOP
dbms_output.put_line( r_product.product_name || ': $' || r_product.list_price );
END LOOP;
END;
Code language: SQL (Structured Query Language) (sql)

In this example, the SELECT statement of the cursor retrieves data from
the products table. The FOR LOOP statement opened, fetched each row in the result set,
displayed the product information, and closed the cursor.

B) Cursor FOR LOOP with a SELECT statement example

The following example is equivalent to the example above but uses a query in a
cursor FOR LOOP statement.

BEGIN
FOR r_product IN (
SELECT
product_name, list_price
FROM
products
ORDER BY list_price DESC
)
LOOP
dbms_output.put_line( r_product.product_name ||
': $' ||
r_product.list_price );
END LOOP;
END;

You might also like