You are on page 1of 49

Cursor

Cursor is a location in the memory where the SQL statement is processed. That is when ever we send an
SQL statement; the system allocates some memory by giving a name. After processing the statement it
automatically cleans that memory. There are four STEPS , which are processed by the system
whenever we send an SQL statement they are

1.Creating cursor : This step allocates memory

2.OPENING  cursor :

In this step process the sql statement

3.Fetching cursor: 

The VALUES  satisfied by the sql statement are fetched from the

table into cursor row by row

4.Closing cursor : This statement CLOSE  the memory allocated for the cursor

TYPES  Of Cursors

There Are Two Types Of Cursors

1. Implicit cursors or SIMPLE  cursors

2. Explicit Cursors

Implicit Cursors

Oracle implicitly opens a cursor to process each sql statement not associated with explicitly declared
cursor. Pl/sql lets you refer to the most recent implicit cursors as the sql cursor.

Implicit cursors have four attributes, you can use in your PROGRAM

1. sql%rowcount

It RETURNS  the number of rows affected by an insert, update or delete

1. sql%found

This attributes evaluates to true, if an insert or update or delete

affected to one or more rows. It evaluates to false if no row is affected

1. sql%notfound

This attributes is logical opposite to sql%found. It evaluates to true,


if an insert or update or delete does not affected to any row. It evaluates to

false if any one row is affected

1. %isopen

It CHECKS  whether the cursor has been opened or not

Example : 1

write a program to check whether there is atleast one row satisfying the given SELECT  
statement or not using implicit cursors

Declare

e emp%rowtype;

Begin

SELECT  * into e from emp where empno=&empno;

if sql%found then

dbms_output.put_line('~~~~~~~~~~~~~~~~~~~~');

dbms_output.put_line(' RECORD  Found ');

dbms_output.put_line('~~~~~~~~~~~~~~~~~~~~');

End if;

End;

Example : 2

write a PROGRAM  to change the ename column values to upper CASE

using implicit cursors

begin

UPDATE  employee set ename=upper(ename);

if sql%found then

dbms_output.put_line('~~~~~~~~~~~~~~~~~~~~');

dbms_output.put_line(sql%rowcount || ' RECORDS  UPDATED  ');


dbms_output.put_line('~~~~~~~~~~~~~~~~~~~~');

else

dbms_output.put_line('~~~~~~~~~~~~~~~~~~~~');

dbms_output.put_line(' Sorry CHANGES  Are not Made ');

end if;

end;

Example : 3

write a program to update the salary of those employees to 20% whose salary is greater than the
given salary, using implicit cursors

begin

update employee set sal=sal+(sal*20)/100 where sal>&sal;

if sql%found then

dbms_output.put_line('~~~~~~~~~~~~~~~~~~~~');

dbms_output.put_line(sql%rowcount || ' Records Updated ');

dbms_output.put_line('~~~~~~~~~~~~~~~~~~~~');

end if;

if sql%notfound then

dbms_output.put_line('~~~~~~~~~~~~~~~~~~~~');

dbms_output.put_line(' Sorry No RECORD  is Satisfied ');

end if;

end;

Explicit Cursors

The USER  creates these cursors for APPLYING  2 or more DML operations on a table. using a cursor
we can fetch all the row values from the table into a variable for printing them or performing some action
with them
In an explicit cursor, there are four steps related to execute cursors by the user. It is also used to compare
a variable value with all values of the column.

The four steps are

1. Declaring a Cursor

2. OPENING  a Cursor

3. Fetching a Cursor

4. CLOSING  a Cursor

Declaring a Cursor

A cursor is defined in the declarative part of the PL/SQL block by naming it and associating it with a query

Syntax :

Declare

Cursor <cursor_name> is <SELECT  Statement>

Opening a Cursor

The cursor must be initialized or opened with the open statement. Opening the cursor excutes the query
and identifies the result set which consists of all the rows that meets the query search criteria

Syntax :

Declare

Cursor <cursor_name> is <select Statement>

Begin

Open <cursor Name>

-----------

End;

Fetching With a Cursor

This statement is used to retrieve the cursors current row. Fetching can be excuted repeatedly until all
rows have been retrieved

Syntax :

Declare
Cursor <cursor_name> is <select Statement>

Begin

Open <cursor Name>

Fetch <cursor Name> into <variable1>,<variable2>,----

-----------

End;

Closing a Cursor

When the last row has been processed, the cursor is closed with the close statement. The close
statement disable the cursor

Syntax :

Declare

Cursor <cursor_name> is <select Statement>

Begin

Open <cursor Name>

Fetch <cursor Name> into <variable1>,<variable2>,----

-----------

Close <cursor Name>

End;

Examples

1. Write a program using an explicit cursor, which displays all the rows from the table

Declare

Cursor c1 is select * from emp;

e emp%rowtype;

Begin

Open c1;

Loop
Fetch c1 into e;

Dbms_output.put_line(e.empno||' '||e.ename||' '||e.sal);

Exit when c1%notfound;

End loop;

Close c1;

End;

2.Write a program using an explicit cursor, to insert values into a table empc from emp table,
whose experience is >=23 years

Declare

cursor c2 is select * from emp where (sysdate-hiredate)/365>=23;

e emp%rowtype;

x number:=0;

begin

open c2;

loop

fetch c2 into e;

exit when c2%notfound;

insert into empc values(e.empno,e.ename,e.job,e.sal,e.hiredate);

x:=x+sql%rowcount;

end loop;

dbms_output.put_line(x||' Records inserted Successfully....');

close c2;

end;

/
3.Write a program using an explicit cursor, to display first 5 records

Declare

cursor c3 is select * from emp;

e emp%rowtype;

x number;

begin

open c3;

loop

fetch c3 into e;

exit when c3%rowcount>5;

dbms_output.put_line(e.empno||' '||e.ename||' '||e.sal);

end loop;

close c3;

end;

Cursor For Loop

A cursor for loop implicitly declares its loop index as a %rowtype, opens a cursor, repeatedly fetches the
rows of values from the result set into fields in the records and closes the cursor when all rows have been
processed or exit command is encountered

Syntax :

Declare

Cursor <cursor_name> is <select statement>

Begin

For <index> in <cursor name> loop

---------

end loop;

end;
/

Example : 1

Write a program to display all employee’s details working in the accepted department number
using cursor for loop

declare

cursor c1 is select * from emp where deptno=&deptno;

e c1%rowtype;

begin

dbms_output.put_line('****************');

for e in c1 loop

dbms_output.put_line(e.empno||' '||e.ename||' '||e.job||' '||e.sal);

end loop;

dbms_output.put_line('****************');

end;

Example : 2

Write a program to display all employee’s details working in the accepted department number and
also display all department details for the given department number using cursor for loops

declare

cursor c1 is select * from emp where deptno=&deptno;

e c1%rowtype;

cursor c2 is select * from dept where deptno=&deptno;

d c2%rowtype;

begin

dbms_output.put_line(' ****Employees Details ***** ');

for e in c1 loop

dbms_output.put_line(e.empno||' '|| e.ename||' '||e.job||' '||e.sal);


end loop;

dbms_output.put_line(' ****Department Details ***** ');

for d in c2 loop

dbms_output.put_line(d.dname||' '||d.loc

||' '||d.deptno);

end loop;

end;
Trigger
Trigger is a database object ie used to execute an action basing on an even. Triggers are event-
based PROGRAMS , which are executed when an event occurs or raises or fires

TYPES  of Triggers

Trigger Type is defined by the type of triggering TRANSACTION  and by the LEVEL  at which the
trigger is executed

Triggers Are Of Two Types

1. Row Level Triggers

2. Statement Level Triggers

Row Level Triggers

A row trigger is fired each time a row in the table is affected by the triggering statement. For example, if
an UPDATE  statement updates multiple rows of a table, a row trigger is fired once for each row affected
by the update statement. If the triggering statement affects no rows, the trigger is not executed at all. Row
triggers should be used when some processing is required whenever a triggering statement affects a
single row in a table.

Row level triggers are created using the "For Each Row" Clause in the Create Trigger Command

Statement triggers

A statement trigger is fried once on behalf of the triggering statement, independent of the number of rows
the triggering statement affects (even if not rows are affected) statement triggers should be used when a
triggering statement affects rows in a table but the processing required is COMPLETELY  independent
of the number of rows affected

Statement level triggers are the default TYPE  of trigger created via Create Trigger Command

Syntax:

create or replace trigger <trigger_NAME >

{before/after/instead of}

{insert/UPDATE /delete}

[ of <column name> on <table name> ]

[ for each row [when <CONDITION >] ]

Declare
variables declarations

-----------------

BEGIN

Executable statements

-------------

Exception

Exception statements

---------------

end;

Syntax Explanation :

or replace : Recreates the trigger if it already exists. this option can be used to change the definition of
an existing trigger without requiring the USER  to drop the trigger first

Trigger Name : is the name of the trigger to be created

Before : Indicates that oracle fires the trigger before executing the trigger statement

After : Indicates that oracle fires the trigger After executing the trigger statement

Insert : Indicates that oracle fires the trigger whenever an INSERT statement adds a row to a table.

Delete : Indicates that oracle fires the trigger whenever a DELETE statement removes a row from the
table.

Update : Indicates that oracle fires the trigger whenever an UPDATE statement changes a value in one
of the columns specified in the OF clause. if the OF clause is omitted, the oracle fires the trigger
whenever an UPDATE statement changes a value in any column of the table.

for Each Row : Designates the trigger to be a row trigger. the oracle engine fires a row trigger once for
each row that is affected by the triggering statement and meets the optional trigger constraint defined in
the When clause. if this clause is omitted the trigger is a statement trigger.

When : specifies the trigger restriction. the trigger restriction contains a SQL condition that must be
satisfied for the oracle to fire the trigger.

Basing on the above 2 types of triggers, they are further classified into 3 types

1. DML Triggers
2. DDL Triggers and

3. Instead of Triggers

1. DML Triggers

These triggers are executed before or after. we apply any dml operations on a table.

When we create a table. the trigger definition is stored in the database, which is identified with the trigger
name. the code in the trigger is processed when we apply any command on the database or table

Examples :

Steps for Creating a Trigger

1. First Create a trigger, next set the server on with the following statement (set Serveroutput on)

2. Run that Trigger with the following statement

@ <trigger name>

3. perform some action (ie either insert or update or delete etc)

Statement Level Triggers

1. Create A Trigger, Which Displays A Message When Ever You Insert A New Row In To Sample1
Table

Create or replace trigger instrig1 before insert on sample1

Begin

dbms_output.put_line('one record inserted successfully.....');

End;

2. Create A Trigger, Which Displays A Message When Ever You Update An Existing Row In The
Table Sample1

Create or replace trigger updtrig1 before update on sample1

Begin

dbms_output.put_line('one record updated successfully.....');

End;

/
1. Create A Trigger, Which Displays A Message When Ever You Delete A Row From The
Table Sample1

Create or replace trigger deltrig1 before delete on sample1

Begin

dbms_output.put_line('record(s) deleted successfully.....');

End;

Row Level Triggers

1. Create A Trigger, Which Displays A Message When Ever You Insert A New Row Into A Table
Sample1

Create or replace trigger instrig2 before insert on sample1

for each row

Begin

dbms_output.put_line(:new.sno||' record inserted successfully.....');

End;

1. Create a trigger, which displays a message when ever you update a row in the table
sample1

Create or replace trigger updtrig2 before update on sample1 for each row

Begin

dbms_output.put_line(:old.sno||' record updated to '||:new.sno);

End;

1. Create A Trigger, Which Displays A Message When Ever You Delete A Row From The
Table Sample1

Create or replace trigger deltrig2 after delete on sample1 for each row

Begin

dbms_output.put_line(:old.sno||' record deleted successfully.....');


End;

DDL TRIGGERS

1. Create A Trigger, Which Displays An Error Message When Ever You Create a New Table
which starts with Letter ‘A’

Create or replace trigger ctrig1 before create on scott.schema

Begin

if dictionary_obj_name like 'a%' then

raise_application_error(-20001,'object name can not start with a');

End if;

End;

1. Create A Trigger, Which Displays An Error Message When Ever You try to drop any Table

Create or replace trigger prevent_drop after drop on scott.schema

Begin

if ora_dict_obj_type='table' then

raise_application_error(-20001,'object can not be dropped');

End if;

End;

1. Create A Trigger, Which Displays An Error Message When Ever You try to Alter any Table

create or replace trigger prevent_alter before alter on scott.schema

begin

if ora_dict_obj_type='TABLE' then

Raise_Application_Error(-20001,'Object Can not be altered');

end if;
end;

INSTEAD OF TRIGGER

Create a trigger, which inserts the given values in to the relevant table through a Composite view

Create or replace trigger instrig instead of

Insert on empdept for each row

Begin

if :new.deptno is not null and :new.dname is not null then

insert into department(deptno,dname) values (:new.deptno,:new.dname);

end if;

if :new.empno is not null and :new.ename is not null then

insert into employee(empno,ename) values (:new.empno,:new.ename);

end if;

End;
Stored Procedure
A procedure is a set of instructions(usually combining sql and plsql commands) saved for calling and
repeated execution

A procedure is a sub PROGRAM  that performs a specific action. A procedure can be called from any
pl/sql block. A procedure has two parts one is Specification and Other is BODY

The procedure specification begins with the keyword procedure followed by procedure name and an
option LIST  of arguments enclosed with in the parenthesis.

The procedure body begins with is or as and ends with an end statement.

It consists of three parts

1. Declarative Part

2. Execution Part

3. Exception HANDLING  Part

Syntax of Procedure
Create [ Or Replace ] Procedure < Procedure Name > ( Argument1 [Mode] <Data TYPE >,
Argument2 [Mode] <data type>,---)

Is / As

LOCAL  Variables Declarations;

------------

Begin

Executable Statements;

---------------

[Exception

Exception Handling; ]

End;

where Mode refers to the type of arguments such as In , Out or InOut


Modes In Procedures And Functions

1. IN : the In parameter lets the USER  to pass values to the called sub programs with in the
sub PROGRAM , the IN parameter acts like a constant. There fore it cannot be modified.

1. OUT : The Out parameter lets the user returned values to the calling block. Inside the sub
program the out parameter acts like a un initialized variable. Its value can not be assigned to
another variable or itself

1. INOUT : the INOUT parameter lets the user pass initial values to the called sub program
and RETURN  updated values to the calling block

Note : the default mode of an argument is "IN"

Show ERRORS  :

This Command is used to show the errors that are occurred during the procedure creation

Ex : when ever we create a procedure and executed, if it show procedure created with compilation errors,
the we can see those errors using the following statement

show Errors

Example :1

Write a procedure to show a simple MESSAGE

Sol. STEPS

1. Write the sub Program

Ed subprocedure1

Create or replace procedure disp is

Begin

Dbms_output.put_line('This is a Sub Program');

End;

1. Next, Compile the above procedure to find errors in the procedure, with the following statement

@ subprocedure1

1. Next, Write the main program

Begin
Dbms_output.put_line('This is Main Program');

Disp;

Dbms_output.put_line('Again Continuing the Main Program');

End;

1. Next, Run the above main procedure with the following statement

@mainprogram1

output :

SQL> @ mainprogram1

This is Main Program

This is a Sub Program

Again Continuing the Main Program

PL/SQL procedure successfully completed.

Example :2

Write a procedure to show a message when updated any row in a particular table

Sol. Steps

1. Write the sub Program

Ed subprocedure2

Create or replace procedure upd(d number)

is

Begin

update employee set sal=sal+(sal*0.2) where empno=d;

dbms_output.put_line(sql%rowcount||' Record Updated...');

End;

/
1. Next, Compile the above procedure to find errors in the procedure, with the following statement

@ subprocedure2

1. Next, Write the main program

Begin

upd(&empno);

End;

1. Next, Run the above main procedure with the following statement

@mainprogram2

output :

SQL> @ mainprogram2

Enter value for empno: 7369

old 2: upd(&empno);

new 2: upd(7369);

1 Record Updated...

PL/SQL procedure successfully completed.

Example 3:

Create a procedure which adds the given three numbers using “in” and “out” parameters

Sol. Steps

1. Write the sub Program

Ed subprocedure3

Create or replace procedure sum_numbers(n1 in number, n2 in

number, res out number)

is

Begin
res:=n1+n2;

End;

1. Next, Compile the above procedure to find errors in the procedure, with the following statement

@ subprocedure3

1. Next, Write the main program

Declare

a number;

b number;

c number;

Begin

a:=&a;

b:=&b;

sum_numbers(a,b,c);

dbms_output.put_line('sum of three numbers is '||c);

End;

1. Next, Run the above main procedure with the following statement

@mainprogram3

output :

SQL> @ mainprogram3

Enter value for a: 10

old 6: a:=&a;

new 6: a:=10;

Enter value for b: 20


old 7: b:=&b;

new 7: b:=20;

sum of three numbers is30

PL/SQL procedure successfully completed.

Example 4:

Create a procedure which Updates the sal with the increment value that you give according to the
given emp number

Sol. Steps

1. Write the sub Program

Ed subprocedure4

Create or replace procedure incr(eno employee.empno%type,s

out NUMBER , i number)

Is

Begin

UPDATE  employee set sal=sal+i where empno=eno;

Dbms_output.put_line('RECORD  Updated----');

End;

1. NEXT , Compile the above procedure to find errors in the procedure, with the following
statement

@ subprocedure4

1. Next, Write the main PROGRAM

Declare

e number:=&empno;

Incr_value number:=&increment;

s employee.sal%type;

Begin
SELECT  sal into s from employee where empno=e;

Incr(e,s,incr_value);

End;

1. Next, Run the above main procedure with the following statement

@mainprogram4

output :

SQL> @ mainprogram4

ENTER  VALUE  for empno: 7369

old 2: e NUMBER :=&empno;

NEW  2: e number:=7369;

Enter value for increment: 48

old 3: incr_value number:=&increment;

new 3: incr_value number:=48;

RECORD  Updated----

PL/SQL procedure successfully COMPLETED .


Function
A function is a sub PROGRAM  that executes a set of statements and returns a value to the main
program. The basic difference between Functions and procedures is, function returns a value to the
calling program or main program where as a procedure does not RETURN  any value

Syntax of A Function

Create [ Or Replace ] Function < Function Name > ( Argument1 [Mode] <Data type>, Argument2 [Mode]
<data type>,---) return data type

Is / As

LOCAL  Variables Declarations;

------------

BEGIN

Executable Statements;

---------------

[Exception

Exception HANDLING ; ]

End;

EXAMPLE  : 1

Write a PROGRAM  to find sum of TWO  numbers

Sol :

ed function1

Create or replace function addition(x integer, y integer) RETURN  integer

is

BEGIN

Return x+y;

End;
/

mainfunction1

Declare

A integer :=&a;

B integer :=&b;

C integer;

Begin

C:=addition(a,b);

Dbms_output.put_line('sum of two numbers is '|| c );

End;

EXAMPLE  : 2

wirte a function which accepts item NUMBER  and quantity and then return the total amount by
fetching rate from the item table

create or replace function itembill(q in number,r in number) return number

is

begin

RETURN  q*r;

end;

ed mainfunction2

declare

q1 NUMBER :=&quantity;

r1 number;

res number;

BEGIN
SELECT  rate into r1 from item where itno=&itno;

res:=itembill(q1,r1);

dbms_output.put_line(' Total AMOUNT  is '||res);

exception

when no_data_found then

dbms_output.put_line(' No Such Item Exits');

end;
Exception Handling
Types of Exceptions

1. Pre Defined Exceptions

2. User Defined Exceptions

Pre Defined Exceptions

These exceptions are used to handle some logical errors known to the system are pre defined. The
following are some of the important pre defined Exceptions

1. no_data_found

This Exception raises when there is no rows to be retrieved from a table

according to given condition

1. dup_val_on_index

This Exception raises when ever you try to store duplicate values into a

table, which has been indexed (unique indexed)

1. cur_already_open

This Exception raises when ever your program attempts to open an already

opened cursor.

A cursor must be closed before it can be re opened. A cursor for loop

automatically opens the cursor to which it refers. So Your program can not open that cursor inside the
loop

1. invalid_cursor

This Exception raises when ever your program attempts an illegal cursor operation, such as closing an un
opened cursor

1. zero_divide

This Exception raises when ever your program attempts to divide a number

by zero
1. program_error

This Exception raises when ever PL/SQL has internal problem

1. storage_error

This Exception raises when ever PL/SQL runs out of memory

1. too_many_rows

This Exception raises when ever a select statement returns more than one

row

1. login_denied

This Exception raises when ever your program attempts to logon to oracle

with an invalid user name and/or password

1. value_error

This Exception raises when ever an arithmetic conversion or size constraint error occurs

For ex, when your program selects a column value into a variable. If the value is longer than the declared
length of the variable, pl/sql abords the assignment and raise the exception value_error

Programs On Exceptions

1. Write a program for handling an error when we try to open an already opened cursor

declare

cursor c1 is select * from emp;

x emp%rowtype;

begin

open c1;

fetch c1 into x;

dbms_output.put_line(x.empno||' '||x.ename);

--open c1;

close c1;

exception
when cursor_already_open then

dbms_output.put_line(' sorry friend, cursor already opened');

end;

2. Write a program to display a message when no data found in the main table

declare

e emp%rowtype;

begin

select * into e from emp where empno=&empno;

dbms_output.put_line('Empno Ename job');

dbms_output.put_line(e.empno||' '||e.ename||' '||e.job);

exception

when No_data_found then

dbms_output.put_line(' sorry friend, no data found');

end;

3. Write a program for handling an error when we insert a duplicate value into a column.

declare

n sample%rowtype;

begin

insert into sample values(&sno,'&sname','&class');

dbms_output.put_line('Record Inserted....');

exception

when dup_val_on_index then

dbms_output.put_line(' sorry friend, you entered a duplicate value');


end;

Note : create a table with unique constraint, for dup_val_on_index,

 create table sample(sno number(3),sname varchar2(10));

 CREATE UNIQUE INDEX IDX_SAM ON SAMPLE(SNO);

4. Write a program for handling an error when we try to close an un opened cursor

declare

cursor c1 is SELECT  * from emp;

BEGIN

--open c1;

dbms_output.put_line(' cursor is OPENED' );

CLOSE  c1;

exception

when invalid_cursor then

dbms_output.put_line(' sorry friend, No such cursor is opened');

end;

/NOTE  : if u remove comment for open c1 then output is cursor is opened, other wise the you will get
“sorry friend, no such cursor is opened ..”, since you r trying to CLOSE  an unopened cursor

5. Write a program for handling an ERROR  when we try to divide a value with zero

declare

a NUMBER :=&a;

b number:=&b;

c number;

BEGIN
c:=a/b;

dbms_output.put_line(c);

exception

when zero_divide then

dbms_output.put_line('Zero Divide ERROR' );

end;

6. Write a PROGRAM  for handling an error when ever the program retrieves too many rows

declare

e emp%rowtype;

BEGIN

SELECT  * into e from emp;

exception

when too_many_rows then

dbms_output.put_line(' sorry friend, too many rows are SELECTED' );

end;

USER  Defined Exceptions

A user can define or create exceptions, which must be raised automatically, because the system does not
knows when to execute the user defined ERRORS . There are 3 steps while working with user defined
exceptions

1. Creating Exception

2. Raising Exception

3. HANDLING  Exception

The main purpose of user defined exceptions is, we can display a message in predefined ERROR  
format in the instances not known to the system or that are not predefined

Syntax :

Declare

<Exception NAME > Exception;


BEGIN

Raise Exception;

Exception

When <Exception name> then

Message

End;

Raise_Application_Error

This is a keyword, which is used to generate an error message in pre defined error format for the given
user defined error

Syntax :

Raise_Application_Error(Error number, ‘ message ‘);

Example :

Raise_Application_Error(-20173, ‘ Some Error ‘);

Note : Error Number for (user defined Exceptions) must be in between –20001 to -20999

1. Write a program for creating an exception and raising it when the basic is <3000, while inserting
rows into a table and also handle it to perform any other action

Declare

invalid_salary exception;

s employee.sal%type:=&sal;

begin

if s<3000 then

raise invalid_salary;

else

insert into employee(sal) values (s);

dbms_output.put_line(' Record Inserted.....');

end if;
exception

when invalid_salary then

dbms_output.put_line(' salary must be >3000 ');

end;

2. Write a program for creating an exception and raising it when ever you try to insert any negative
number into a table

Declare

invalid_number exception;

e employee.empno%type:=&empno;

begin

if e<0 then

raise invalid_number;

else

insert into employee(empno) VALUES  (e);

dbms_output.put_line(' RECORD  Inserted.....');

end if;

exception

when invalid_number then

dbms_output.put_line(' Number must BE  positive ');

end;
Control structures
CONTROL  structures

Control structures are used to control the flow of PROGRAMS  execution. The control structures are
classified into the following categories:

 Conditional Control
  Iterative Control

Conditional Control

PL/SQL supports the following types of Conditional control statements or SELECTION Statements

1. SIMPLE  if statement


2. If...else statement
3. If ...elsif statement

1.Simple If

The simple if statement is used to CHECK  a simple CONDITION , if it is true it will execute the
statements that are present between "if "and "end if". Otherwise it will not execute those statements.

Syntax :

If ( Condition ) then

Statements ;

------------- ;

End If;

2.If...Else Statement

The if …else statement is used to define two blocks of statements, in ORDER  to execute only one
block.

Syntax :

If (CONDITION  ) then

True Block Statements ;

------------------------- ;

Else

False Block Statements ;


-------------------------- ;

End if;

if the condition is true, it will execute the True Block statements otherwise it will execute the false block
statements.

3.If...ElsIf Statement

The if …elsIf statement is used to define SEVERAL  blocks of statements, in order to execute only one
block.

Syntax :

If (condition 1) then

statements 1 ;

--------------- ;

Elsif (condition 2) then

statements 2;

------------- ;

Elsif (condition 3) then

statements 3;

------------;

Elsif (condition n) then

statements n;

------------;

Else

statements;

------------;

End if;
if condition1 is true, it will execute statements1 otherwise it will check Condition2, if it is true it
will execute statements2. if not it will go to condition3, like this the process continues until the condition
matches. If no condition matches, it will execute the else block statements.

Eg 1. Write a program to check whether the given number is a positive number of a negative
number using simple if statement

declare

n number:=&n;

begin

if(n>=0) then

dbms_output.put_line(n||' is a Positive Number');

end if;

if(n<0) then

dbms_output.put_line(n ||' is a Negative Number');

end if;

end;

Branching Statements

declare

x integer:=&x;

y integer:=&y;

p char(1):='&Operator';

r number;

begin

if p='+' then

goto Addition;

elsif p='-' then

goto Subtraction;
elsif p='*' then

goto Multiplication;

elsif p='/' then

goto Division;

else

goto Expt;

end if;

<<Addition>>

r:=x+y;

dbms_output.put_line(r);

return;

<<Subtraction>>

r:=x-y;

dbms_output.put_line(r);

RETURN ;

<<Multiplication>>

r:=x*y;

dbms_output.put_line(r);

return;

<<Division>>

r:=x/y;

dbms_output.put_line(r);

return;

<<Expt>>

dbms_output.put_line(sqlerrm);
end;

Loops

PL/SQL supports, the following TYPES  of loops

1. SIMPLE  Loop

2. While Loop

3. For Loop

 1.SIMPLE  Loop

This loop is used to execute a series of statements as long as the CONDITION  is false. If the condition
becomes true, it will exit from that loop

Syntax :

Loop

Statements;

Exit When <condition>;

Increment/decrement Operations

End Loop;

Eg 2 :Write a program to print first 25 natural numbers using simple loop

Declare

N number:=1;

Begin

Loop

Exit When N>25;

Dbms_output.put_line(N);

N:=N+1;

End loop;

End;
2.While Loop

The while Loop is used to execute a series of statements as long as the condition is True. If
the condition becomes false, it will exit from that loop

Syntax :

While <condition> Loop

Statements;

[ Exit When <condition>; ]

Increment/decrement Operations

End Loop;

Eg 3: Write a program to print first 25 natural numbers using While loop

Declare

N number:=1;

Begin

While N<=25 Loop

Dbms_output.put_line(N);

N:=N+1;

End loop;

End;

3.For Loop

The For loop is used to execute a set of statements as long as the condition is false. If the condition
becomes true, it will exit from that loop

Syntax :

For <variable> in [reverse] <start value> .. <end Value> Loop

Statements;

End Loop;

Eg 4: Write a program to print first 25 natural numbers using For loop

Declare
N number:=1;

Begin

For N in 1..25 Loop

Dbms_output.put_line(N);

End loop;

End;

Eg 5 :Write a program to print first 25 natural numbers using For loop in Reverse order

Declare

N number:=1;

Begin

For N in Reverse 1..25 Loop

Dbms_output.put_line(N);

End loop;

End;

Eg 6: Write a program to print multiplication table for the given number

Declare

i number:=1;

r number:=&number;

Begin

While i<=10 loop

dbms_output.put_line(r||'*'|| i ||'='||r*i);

i:=i+1;

End loop;

End;
Materialized view
A materialized view is a database object that contains the results of a query. They are local copies of data
located remotely, or are used to create summary tables based on aggregations of a table's
data.Materialized view and the Query rewrite feature is added from ORACLE 8i.

A materialized view log is a schema object that records changes to a master table's data so that a
materialized view defined on the master table can be refreshed incrementally.

 If you delete any RECORD  from your Materialized view it is goanna impact your Source table
once it is refreshed.

Examples to the Simple Materialized view’s is given BELOW  .

Eg 1 :Create materialized_view MV refresh as SELECT  * from emp;

Execute dbms_mview.refresh(‘MV’);

Refresh Complete : To perform a complete refresh of a materialized view, the server that manages the
materialized view executes the materialized view's defining query, which essentially recreates the
materialized view. To refresh the materialized view, the result set of the query replaces the existing
materialized view data. Oracle can perform a complete refresh for any materialized view. Depending on
the AMOUNT  of data that satisfies the defining query, a complete refresh can take a substantially longer
amount of time to perform than a fast refresh.

Create Materialized_view MV Refresh complete as SELECT  * from emp;

execute DBMS_mview.refresh(List=>’MV’,Method=>’c’);

Refresh Fast :To perform a fast refresh, the master that manages the materialized view first identifies
the changes that occurred in the master since the most recent refresh of the materialized view and
then APPLIES  these changes to the materialized view. Fast refreshes are more efficient than complete
refreshes when there are few changes to the master because the participating server and network
replicate a smaller amount of data.

Create Materialized_view MV Refresh fast as SELECT  * from emp;

execute DBMS_mview.refresh(LIST =>’MV’,Method=>’F’);

Primary Key Materialized Views :

The following statement creates the primary-key materialized view on the table emp located on a remote
database.

SQL> CREATE MATERIALIZED VIEW mv_emp_pk


REFRESH FAST START WITH SYSDATE
NEXT SYSDATE + 1/48
WITH PRIMARY KEY
AS SELECT * FROM emp@remote_db;
Note: When you create a materialized view using the FAST option you will need to create a view log on
the master tables(s) as shown BELOW :

SQL> CREATE MATERIALIZED VIEW LOG ON emp;Materialized view log created.

Rowid Materialized Views :

The following statement creates the rowid materialized view on table emp located on a remote database:

SQL>CREATE MATERIALIZED VIEW mv_emp_rowid REFRESH WITH ROWID    AS SELECT *


FROM emp@remote_db;

Materialized view log created.

Creating Materialized Aggregate Views :

CREATE MATERIALIZED VIEW sales_mv BUILD IMMEDIATE REFRESH FAST ON COMMIT AS


SELECT t.calendar_year, p.prod_id, SUM(s.amount_sold) AS sum_sales FROM times t, products p,
sales s WHERE t.time_id = s.time_id AND p.prod_id = s.prod_id GROUP BY t.calendar_year, p.prod_id;

Creating Materialized Join Views :

CREATE MATERIALIZED VIEW sales_by_month_by_state


TABLESPACE example
PARALLEL 4
BUILD IMMEDIATE
REFRESH COMPLETE
ENABLE QUERY REWRITE
AS SELECT t.calendar_month_desc, c.cust_state_province,
SUM(s.amount_sold) AS sum_sales
FROM times t, sales s, customers c
WHERE s.time_id = t.time_id AND s.cust_id = c.cust_id
GROUP BY t.calendar_month_desc, c.cust_state_province;

Periodic Refresh of Materialized Views:

CREATE MATERIALIZED VIEW emp_data


PCTFREE 5 PCTUSED 60
TABLESPACE example
STORAGE (INITIAL 50K NEXT 50K)
REFRESH FAST NEXT sysdate + 7
AS SELECT * FROM employees;

Automatic Refresh Times for Materialized Views

CREATE MATERIALIZED VIEW all_customers


PCTFREE 5 PCTUSED 60
TABLESPACE example
STORAGE (INITIAL 50K NEXT 50K)
USING INDEX STORAGE (INITIAL 25K NEXT 25K)
REFRESH START WITH ROUND(SYSDATE + 1) + 11/24
NEXT NEXT_DAY(TRUNC(SYSDATE), 'MONDAY') + 15/24
AS SELECT * FROM sh.customers@remote
UNION
SELECT * FROM sh.customers@local;

SQL Loader
SQL*Loader (sqlldr ) is the utility to use for high performance data loads. The data can be loaded from
any text file and inserted into the database.

During processing, SQL*Loader writes messages to the log file, bad rows to the bad file, and discarded
rows to the discard file.

The Control File

The SQL*Loader control file contains information that describes how the data will be loaded. It contains
the table name, column data types, field delimiters, etc. It simply provides the guts for all SQL*Loader
processing.

SQL*Loader Options

SQL*Loader provides the following options, which can be specified either on the command line or within a
parameter file:

1.  bad – A file that is created when at least one record from the input file is rejected. The rejected
data records are placed in this file. A record could be rejected for many reasons, including a non-
unique key or a required column being null.
2.  bindsize – [256000] The size of the bind array in bytes.
3.  columnarrayrows – [5000] Specifies the number of rows to allocate for direct path column
arrays.
4.  control – The name of the control file. This file specifies the format of the data to be loaded.
5. data – The name of the file that contains the data to load.
6.  direct – [FALSE] Specifies whether or not to use a direct path load or conventional.
7. discard – The name of the file that contains the discarded rows. Discarded rows are those that
fail the WHEN clause condition when selectively loading records.
8.   discardmax – [ALL] The maximum number of discards to allow.
9. errors – [50] The number of errors to allow on the load.
10. external_table – [NOT_USED] Determines whether or not any data will be loaded using external
tables. The other valid options include GENERATE_ONLY and EXECUTE.
11. file – Used only with parallel loads, this parameter specifies the file to allocate extents from.
12. load – [ALL] The number of logical records to load.
13.  log – The name of the file used by SQL*Loader to log results.
14.  multithreading – The default is TRUE on multiple CPU systems and FALSE on single CPU
systems.
15.  parfile – [Y] The name of the file that contains the parameter options for SQL*Loader.
16.  parallel – [FALSE] Specifies a filename that contains index creation statements.
17.  readsize – The size of the buffer used by SQL*Loader when reading data from the input file.
This value should match that of bindsize.
18.  resumable – [N] Enables and disables resumable space allocation. When “Y”, the
parameters resumable_name and resumable_timeout are utilized.
19.  resumable_name – User defined string that helps identify a resumable statement that has been
suspended. This parameter is ignored unless resumable = Y.
20.  resumable_timeout – [7200 seconds] The time period in which an error must be fixed. This
parameter is ignored unless resumable = Y.
21.  rows – [64] The number of rows to load before a commit is issued (conventional path only). For
direct path loads, rows are the number of rows to read from the data file before saving the data in
the datafiles.
22.  silent – Suppress errors during data load. A value of ALL will suppress all load messages. Other
options include DISCARDS, ERRORS, FEEDBACK, HEADER, and PARTITIONS.
23.  skip – [0] Allows the skipping of the specified number of logical records.
24.  skip_unusable_indexes – [FALSE] Determines whether SQL*Loader skips the building of
indexes that are in an unusable state.
25.  skip_index_maintenance – [FALSE] Stops index maintenance for direct path loads only.
26.  streamsize – [256000] Specifies the size of direct path streams in bytes.
27.  userid – The Oracle username and password.

1. To drive the concept of the SQL loader home.., let us assume that we have text file which is the
usual emp table.
2. Now open the cmd prompt and type sqlldr.
3. later the things should look some thing like this.

sqlldr# userid=username/pwd@ora

load data

in file ‘C:\emp.txt’

into table emp_oracle

fields terminated by “,”optionally enclosed by’ ” ’

(empno,ename,job,mgr,sal,comm,deptno)

Frequently Used Data Dictionary Queries


1.INDEX  Table :

SELECT  INDEX_NAME ,INDEX_TYPE,TABLE_OWNER,TABLE_NAME,NUM_ROWS,

LAST_ANALYZED,PARTITIONED From All_Indexes;

2. Index Columns :

SELECT  INDEX_NAME,TABLE_OWNER,TABLE_NAME,COLUMN_NAME,

COLUMN_POSITION, COLUMN_LENGTH,CHAR_LENGTH from ALL_IND_COLUMNS;

3. Table Column LEVEL  Stats :

Select TABLE_NAME,COLUMN_NAME,NUM_DISTINCT,LAST_ANALYZED,AVG_COL_LEN from


All_Tab_Col_Statistics;

4. Constraints on a table:
select CONSTRAINT_NAME,CONSTRAINT_TYPE,TABLE_NAME,SEARCH_CONDITION,

LAST_CHANGE,INDEX_OWNER,INDEX_NAME from All_Constraints;

5. TEXT  of a VIEW :

select view_name,text,owner from All_Views;

6. Text of a Trigger :

select   trigger_name,trigger_type,triggering_event,table_owner,table_name,

description,trigger_body from all_triggers;

7. Locks on Table:

select c.owner,c.object_name,c.object_type,c.object_id,b.sid,b.serial#,

b.status,b.osuser,b.machine,a.LOCKED_MODE from v$locked_object

a ,v$session b,dba_objects c where b.sid = a.session_id and  a.object_id =

c.object_id;

Locking Modes Description:

0- none

1 - null (NULL)

2 - row-S (SS)

3 - row-X (SX)

4 - share (S)

5 - S/Row-X (SSX)

6 - exclusive (X)

8. Query to Kill a Session :

alter system kill session(sid,serial no)

9.Find the Actual size of a Database

SELECT SUM (bytes) / 1024 / 1024 / 1024 AS GB FROM dba_data_files;

10.Find the size occupied by Data in a Database or Database usage details


SELECT SUM (bytes) / 1024 / 1024 / 1024 AS GB FROM dba_segments;

11. Last SQL fired by the User on Database

SELECT S.USERNAME || '(' || s.sid || ')-' || s.osuser UNAME, s.program || '-' ||

s.terminal || '(' || s.machine || ')' PROG,s.sid || '/' || s.serial# sid, s.status

"Status",p.spid,sql_text sqltext FROM v$sqltext_with_newlines t,

V$SESSION s, v$process p   WHERE t.address = s.sql_address   AND

p.addr = s.paddr(+) AND t.hash_value = s.sql_hash_value  ORDER BY s.sid,

t.piece;

12. CPU usage of the USER

SELECT ss.username, se.SID, VALUE / 100 cpu_usage_seconds FROM

v$session ss, v$sesstat se, v$statname sn WHERE  se.STATISTIC# =

sn.STATISTIC#  AND NAME LIKE '%CPU used by this session%' AND se.SID

= ss.SID AND ss.status = 'ACTIVE' AND ss.username IS NOT NULL ORDER

BY VALUE DESC;

13. Long Query progress in database

SELECT a.sid,a.serial#,b.username,opname OPERATION,target

OBJECT,TRUNC (elapsed_seconds, 5) "ET (s)",TO_CHAR (start_time,

'HH24:MI:SS') start_time,ROUND ( (sofar / totalwork) * 100, 2) "COMPLETE

(%)" FROM v$session_longops a, v$session b  WHERE     a.sid = b.sid  AND

b.username NOT IN ('SYS', 'SYSTEM') AND totalwork > 0 ORDER BY

elapsed_seconds;

14.Last DDL SQL Fired from particular Schema or Table:

SELECT CREATED, TIMESTAMP, last_ddl_time  FROM all_objects  WHERE     OWNER =


'MYSCHEMA'  AND OBJECT_TYPE = 'TABLE' AND OBJECT_NAME = 'EMPLOYEE_TABLE';

15.Find Top 10 SQL by reads per execution

SELECT * FROM (  SELECT ROWNUM,SUBSTR (a.sql_text, 1, 200)


sql_text,TRUNC (a.disk_reads / DECODE (a.executions, 0, 1, a.executions))

reads_per_execution,a.buffer_gets,a.disk_reads,a.executions,a.sorts,a.address

FROM v$sqlarea a ORDER BY 3 DESC) WHERE ROWNUM < 10;

16.Oracle SQL query that show the opened connections group by the program that opens the
connection.

SELECT program application, COUNT (program) Numero_Sesiones FROM

v$session GROUP BY program ORDER BY Numero_Sesiones DESC;

17.Get number of objects per owner

SELECT owner, COUNT (owner) number_of_objects FROM dba_objects

Group By Owner ORDER BY number_of_objects DESC;

18.Oracle SQL query that shows Oracle users connected and the sessions number for user

SELECT username Usuario_Oracle, COUNT (username) Numero_Sesiones

FROM v$session Group By Username ORDER BY Numero_Sesiones DESC;

19. DML Operation Audit

select username ,obj_name ,to_char(timestamp,'dd-mon-yy hh24:mi')

event_time  ,substr(ses_actions,4,1) del  ,substr(ses_actions,7,1)

ins ,substr(ses_actions,10,1) sel  ,substr(ses_actions,11,1) upd  from dba_audit_object;

20.SQL Statements with Maximum Wait

select ash.user_id, u.username, s.sql_text, sum(ash.wait_time +

ash.time_waited) ttl_wait_time from v$active_session_history ash,

v$sqlarea s, dba_users u where ash.sample_time between sysdate -

60/2880 and sysdate and ash.sql_id = s.sql_id and ash.user_id = u.user_id

group by ash.user_id,s.sql_text, u.username order by ttl_wait_time ;

21. SQL Text:

select sid, sql_text from v$session s, v$sql q where sid in (* ,*) and

(q.sql_id = s.sql_id or q.sql_id = s.prev_sql_id);


Note:

Provide the Sid for which you wish to see the SQL Text else list will be exhaustive.

22.query to find out which session is currently using the most undo

select s.sid, t.name, s.value from v$sesstat s, v$statname t where

s.statistic# = t.statistic# and t.name = 'undo change vector size' order by

s.value desc;

23. Monitoring Temporary Tablespace Usage

select * from (select a.tablespace_name,sum(a.bytes/1024/1024)

allocated_mb  from dba_temp_files a where a.tablespace_name = upper

('&&temp_tsname') group by a.tablespace_name) x, (select sum

(b.bytes_used/1024/1024) used_mb, sum(b.bytes_free/1024/1024)

free_mb  from v$temp_space_header b where b.tablespace_name=upper

('&&temp_tsname') group by b.tablespace_name);

24. query to find out which sessions are using space in the temporary tablespace.

select s.sid || ',' || s.serial# sid_serial, s.username, s.osuser,

p.spid,s.module,s.program,sum (o.blocks) * t.block_size / 1024 / 1024

mb_used, o.tablespace,count(*) sorts from v$sort_usage o, v$session s,

dba_tablespaces t, v$process p where o.session_addr = s.saddr and

s.paddr = p.addr and o.tablespace = t.tablespace_name group by s.sid,

s.serial#, s.username, s.osuser, p.spid, s.module, s.program, t.block_size,

o.tablespace order by sid_serial;


Explain Plan
Explain Plan : It is a statement that allows you to have oracle generate execution plan for any sql
statement with out actually executing it.You will be able to examine the execution plan by querying the
plan table.

Plan Table : A Plan table holds execution plans generated by the explain plan statements.Create Plan
table by  running utlxplan.sql located in

$oracle_home/rdbms/admin.

Explain Plan Syntax :

Explain plan [set statement_id=<string in single quotes>]

[into <plan table name>]

for

<sql statements>;

Example to Explain Plan:

Sql> Explain plan set statement_id=’demo’ for

select a.customer_name,a.customer_number,b.invoice_number,

b.invoice_type,b.invoice_data,b.total_amount,

c.line_number,c.part_number,c.quantity,c.unit_cost

from customers a, invoices b, invoice_items c

where c.invoice_id=:b1

and c.line_number=:b2

and b.invoice_id=c.invoice_id

and a.customer_id=b.customer_id

Sql> @ explain.sql

ENTER  statement_id : Demo


Oracle Query Tuning
If query taking long time then First will run the query in Explain PLAN , The explain plan process stores
data in the PLAN_TABLE.

it will give us execution plan of the query like whether the query is using the relevant INDEXES  on the
joining columns or indexes to support the query are missing.

If joining columns doesn’t have index then it will do the FULL  table scan if it is full table scan the cost will
be more then will create the indexes on the joining columns and will run the query it should give better
performance and also needs to analyze the tables if analyzation happened long back. The ANALYZE
statement can be used to gather statistics for a specific table, index or cluster using

ANALYZE TABLE employees COMPUTE STATISTICS;

If still have performance issue then will use HINTS, hint is NOTHING  but a clue. We can use hints like

 ALL_ROWS 
One of the hints that 'invokes' the Cost based optimizer 
ALL_ROWS is usually used for batch processing or data warehousing SYSTEMS .

(/*+ ALL_ROWS */)

 FIRST_ROWS 
One of the hints that 'invokes' the Cost based optimizer 
FIRST_ROWS is usually used for OLTP systems.

(/*+ FIRST_ROWS */)

 CHOOSE One of the hints that 'invokes' the Cost based optimizer 


This hint lets the server choose (BETWEEN  ALL_ROWS and FIRST_ROWS, based
on statistics gathered.
 HASH Hashes one table (full scan) and creates a hash index for that table. Then hashes other
table and uses hash index to find corresponding records. Therefore not suitable for < or > join
conditions.

/*+ use_hash */

You might also like