0% found this document useful (0 votes)
18 views57 pages

PL SQL

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
18 views57 pages

PL SQL

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 57

DATABASE

MANAGEMENT
SYSTEM
Contents
Views

Triggers

Cursor

Transaction Processing
PL/SQL CONSTRUCTS
PL/SQL is a combination of SQL along with the procedural features of programming
languages. It was developed by Oracle Corporation in the early 90's to enhance the
capabilities of SQL.

It is a block structured language that enables developers to combine the power of SQL with
procedural statements. All the statements of blocks are passed to oracle engine all at once
which increases processing speed and decreases the traffic.

DECLARE declaration statements;


BEGIN executable statements;
EXCEPTIONS exception handling statements;
END;
VIEW
• View is a data object which does not contain any data. Contents of the view are the
resultant of a base table. They are operated just like base table but they don’t
contain any data of their own. The programming concepts are very similar to
MySQL.
• The difference between a view and a table is that views are definitions built on top
of other tables.
• If data is changed in the underlying table, the same change is reflected in the view
and vice-versa.
• Advantages of Views are:-
• To achieve logical data independence.
• To improve data security
• To preserves the appearance of original table structure.
CONTINUE…
We can create a view for single table as well as for multiple table.
Types of Views :-
⚫ Simple View: These views can only contain a single base table or can be created
only from one table. Group functions such as MAX(), COUNT(), etc., cannot be
used here

⚫ Complex View: These views can contain more than one base table and they can
contain a group by clause, join conditions, an order by clause.
Syntax:
CREATE <OR REPLACE> VIEW <ViewName>
AS SELECT <ColumnName1 >, <ColumnName2> FROM <TableName>
WHERE <Condition> ;
EXAMPLE OF VIEWS

We are creating a view emp_view on employee table by the following query:


QUERIES APPLICABLE FOR VIEWS
• All the queries which are applicable for table, is also applicable for view
like select, update, delete, drop etc.
• If any modification done in view, it will be reflected in the base table also.
For updating the View we can use only those column name which are
actually present in the View.
For deleting the View we can use only those column name which are actually
present in the View.
For dropping a View, we can use drop command. This command will not
drop the underlying table.
VIEW FOR MULTIPLE TABLE

View from multiple tables can be created by simply include


multiple tables in the SELECT statement.
In the given example, a view is created named region_sale from
two tables location and Store_info.

create view region_sale as select l1.Region_name as Region,


sum(s1.sales) as total_sale from location l1,store_info s1 where
l1.store_Name=s1.store_name group by l1.region_name;
TRIGGERS
Triggers are stored program which automatically fired when some
events occur.
Triggers are written to be executed in response to any of the following
events:
⚫ DML
⚫ DDL
⚫ Database Operations like Server Error, Log on , Log off, Startup
or shut down.
SYNTAX FOR TRIGGERS
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name] ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
CONTINUE…
CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing
trigger with the trigger_name.
{BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed.
view.
{INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
[OF col_name] − This specifies the column name that will be updated.
[ON table_name] − This specifies the name of the table associated with the trigger.
[REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values
for various DML statements, such as INSERT, UPDATE, and DELETE.
[FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be executed
for each row being affected. Otherwise the trigger will execute just once when the SQL
statement is executed, which is called a table level trigger.
WHEN (condition) − This provides a condition for rows for which the trigger would fire.
This clause is valid only for row-level triggers.
EXAMPLE OF TRIGGER
We are considering the same Employee table to understand the Trigger.
EXAMPLE OF TRIGGER
WRITE A TRIGGER TO ENSURE THAT NO EMPLOYEE OF AGE LESS
THAN 20 CAN BE INSERTED IN THE DATABASE.
CREATEA TRIGGER WHICH WILL WORK BEFORE DELETION IN EMPLOYEE
TABLE AND CREATE A DUPLICATE COPY OF THE RECORD IN ANOTHER
TABLE.

• Before creating the Trigger we need to create one emp_backup table so that it
holds the value of those employees who are no more the employee of the
institution.
CONTINUE…
We can drop the trigger by using drop command.
CURSOR
When an SQL statement is processed, Oracle creates a memory
area known as context area. A cursor is a pointer to this context
area. It contains all information needed for processing the
statement.
In PL/SQL, the context area is controlled by Cursor. A cursor
contains information on a select statement and the rows of data
accessed by it.
A cursor can hold more than one row, but can process only one
row at a time.
The set of rows the cursor holds is called the active set.
PROPERTIES CURSOR

Read only
Non-scrollable
Asensitive
TYPES OF CURSOR

There are two types of cursors in PL/SQL:


⚫ Implicit cursor
⚫ Explicit cursor
IMPLICIT CURSOR
If the Oracle engine opened a cursor for its internal processing it
is known as an Implicit Cursor. It is created “automatically” for
the user by Oracle when a query is executed and is simpler to
code.
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.
MOSTLY USED ATTRIBUTES OF IMPLICIT CURSOR
S.No Attribute & Description
%FOUND
Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more
1.
rows or a SELECT INTO statement returned one or more rows. Otherwise, it returns
FALSE.
%NOTFOUND
The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or
2
DELETE statement affected no rows, or a SELECT INTO statement return no rows.
Otherwise, it returns FALSE.
%ISOPEN
3 Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.
%ROWCOUNT
4 Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement,
or returned by a SELECT INTO statement.
EXPLICIT CURSOR

o Explicit cursors are programmer-defined cursors for


gaining more control over the context area.
o An explicit cursor should be defined in the declaration
section of the PL/SQL Block. It is created on a SELECT
Statement which returns more than one row.
o There are four steps in Explicit Cursor.
⚫ DECLARE
⚫ OPEN
⚫ FETCH
⚫ CLOSE
DECLARING THE CURSOR
Declaring the cursor defines the cursor with a name and the associated SELECT
statement. For example −

Declare c_emp cursor for select Name, id, Address from employee [where
id>4];
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_emp;
FETCHING THE CURSOR
Fetching the cursor involves accessing one row at a time. For example, we will
fetch rows from the above-opened cursor as follows −
FETCH c_emp INTO c_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_emp;
COMPLETE EXAMPLE OF EXPLICIT CURSOR
mysql> select * from employee;
+-------+----------+------------+--------+------------+----------+
| EMPNO | EMP_NAME | DEPT | SALARY | DOJ | BRANCH |
+-------+----------+------------+--------+------------+----------+
| 101 | AMIT | PRODUCTION | 45000 | 2000-03-12 | BANGLORE |
| 103 | SUNITA | MANAGER | 120000 | 2001-01-11 | Indore |
| 105 | SUNITA | IT | 67000 | 2001-08-01 | delhi |
| 106 | MAHESH | IT | 145000 | 2003-09-20 | MUMBAI |
+-------+----------+------------+--------+------------+----------+
4 rows in set (0.00 sec)
mysql> create procedure cursordemo(id int)
-> begin
-> declare e_id int;
-> declare e_name varchar(20);
-> declare cur1 cursor for select empno, emp_name
-> from employee where id>101;
-> open cur1;
-> fetch cur1 into e_id,e_name ;
-> select e_id,e_name;
-> close cur1;
-> end $$
Query OK, 0 rows affected (0.01 sec)
DIFFERENCES BETWEEN SQL AND PL/SQL

• SQL is a single query that is used to perform DML and DDL operations while
PL/SQL is a block of codes, used to write the entire program blocks/
procedure/ function, etc.
• SQL is declarative, that defines what need to be done, rather than how things
need to be done while PL/SQL is procedural that defines how the things needs
to be done.
• SQL executes as a single statement while PL/SQL executes as a whole block.
• SQL mainly used to manipulate data while PL/SQL mainly used to create an
application.
• SQL cannot contain PL/SQL code in it while PL/SQL is an extension of SQL,
so it can contain SQL inside it.
TRANSACTION
A transaction is a program including a collection of database operations, executed as a
logical unit of data processing.

The operations performed in a transaction include one or more of database operations like
insert, delete, update or retrieve data.

It is an atomic process that is either performed into completion entirely or is not performed
at all.

A transaction involving only data retrieval without any data update is called read-only
transaction.
PROPERTIES OF TRANSACTION

ACID is a set of properties of database transaction.


⚫ A stands for Atomicity
⚫ C stands for Consistency
⚫ I stands for Isolation
⚫ D stands for Durability
ATOMICITY
• A transaction’s changes to the state are atomic: either all happen or none happen.

• For example, if funds are transferred from one account to another, this only counts as a
bona fide transaction if both the withdrawal and deposit take place.

• If one account is debited and the other is not credited, it does not qualify as a transaction.

• TPS systems ensure that transactions take place in their entirety.

• Atomicity maintained by Transaction Management Component.


CONSISTENCY
Consistency stands for correctness.

This property ensures that any transaction will bring the database from one valid state to
another.

The actions taken as a group do not violate any of the integrity constraints associated with
the state.

It is the responsibility of Application Programmer.


ISOLATION
Transactions are isolated from each other .

For example, when a fund transfer is made between two accounts the debiting of one and
the crediting of another must appear to take place simultaneously.

The funds cannot be credited to an account before they are debited from another.

Isolation managed by Concurrency Control Manager.


DURABILITY
Once transactions are completed they can not be undone.

If the TPS suffers failure, to recover the transaction a log will be created to keep the
record of all completed instructions.

It is the responsibility of recovery manager.


EXAMPLE OF A TRANSACTION IN DBMS
Suppose a bank employee transfers Rs 500 from A's account to B's account. This is very simple
and small transaction involves several low-level tasks.
A’s Account
Open_Account(A)
Old_Balance = A.balance
New_Balance = Old_Balance – 500
A.balance = New_Balance
Close_Account(A)
B’s Account
Open_Account(B)
Old_Balance = B.balance
New_Balance = Old_Balance + 500
B.balance = New_Balance
Close_Account(B)
TRANSACTION STATES IN DBMS
CONTINUE...
Active − In this state, the transaction is being executed. This is the initial state of every
transaction.

Partially Committed − When a transaction executes its final operation, it is said to be in a


partially committed state.

Failed − A transaction is said to be in a failed state if any of the checks made by the
database recovery system fails. A failed transaction can no longer proceed further.
CONTINUE...
Aborted − If any of the checks fails and the transaction has reached a failed state, then the
recovery manager rolls back all its write operations on the database to bring the database
back to its original state where it was prior to the execution of the transaction. Transactions
in this state are called aborted. The database recovery module can select one of the two
operations after a transaction aborts −
⚫ Re-start the transaction
⚫ Kill the transaction

Committed − If a transaction executes all its operations successfully, it is said to be in


committed state. All its effects are now permanently established on the database system.
TRANSACTION CONTROL COMMANDS

COMMIT − This command is used to save the changes.

ROLLBACK − This command is used to roll back the changes.

SAVEPOINT − It creates points within the groups of transactions in which to ROLLBACK.

RELEASE SAVEPOINT:- This command is used to remove a SAVEPOINT that you have
created.
COMMIT
All the DDL commands are auto-committed whereas the DML commands need to commit
explicitly.
When we use any DML command like INSERT, UPDATE or DELETE, the changes made by
these commands are not permanent, until the current session is closed, the changes made by
these commands can be rolled back.
When you perform any insert, update or delete query it reflected to your table because in every
terminal the auto commit mode is by default set to 1 (i.e. ON).
If you set it to 0 (i.e. OFF) then the DML commands run by you will not affect your table. You
can check this by closing the terminal and reopen it.
Syntax: set autocommit=0;
OR
Start transaction;
Syntax for commit :- Commit;
ROLLBACK
The ROLLBACK command is used to undo transactions that have not already been saved to
the database.

Once you commit the data then you can’t rollback it.

The syntax for a ROLLBACK command is as follows −


Rollback;

Syntax of ROLLBACK with savepoint;


ROLLBACK TO savepoint_name;
SAVEPOINT
SAVEPOINT command is used to temporarily save a transaction so that you can rollback to
that point whenever required.

Using this command we can name the different states of our data in any table and then rollback
to that state using the ROLLBACK command whenever required.

If you commit the data then you can’t rollback it to any created savepoint.

The syntax of Savepoint command is as follows:


SAVEPOINT SAVEPOINT_NAME;

The syntax for rolling back to a SAVEPOINT is as follows:


ROLLBACK TO SAVEPOINT_NAME;
RELEASE SAVEPOINT
The RELEASE SAVEPOINT command is used to remove a SAVEPOINT that you have
created.

Once you release the higher level savepoint , then all the lower level savepoint will
automatically be released.

The syntax for a RELEASE SAVEPOINT command is as follows.


RELEASE SAVEPOINT SAVEPOINT_NAME;
THANKS

You might also like