DBMS UNIT 4 PLSQL
DBMS UNIT 4 PLSQL
https://apex.oracle.com/pls/apex/f?p=4500:1003:100115258005547:::::
https://apex.oracle.com/
PL/SQL
1. Procedural Language /Standard Query Language.
2. Significant member of oracle programing Tool set
3. Extensively used to code server side programming
4. Case-insensitive programming language
Generally a program written in PL/SQL language is divided in to blocks.
Blocks
• Blocks are basic programming unit in PL/SQL Programming language.
• There are two types of blocks in PL/SQL:
1. Anonymous Block
2. Named block
Both type of PL/SQL blocks are further divided in to three dufferent
section which are
1.The declaration section
2. The execution section
3. The Exception-handling section
• The execution section is the only mandatory section of blocks whereas declaration and
exception handling section are optional.
• The basic prototype of anonymous PL/SQL block.
• DECLARE
• <declarations section>
• BEGIN
• <executable command(s)>
• EXCEPTION
• END;
Declaration Section
• First section of PL/SQL block
• Contains definition of PL/SQL identifiers such as variable, constants,
cursors
• All local variable used in the program are defined and documented
• Start with keyword DECLARE.
Execution Section
• Contains executable statements that allow you to manipulate the
variables that have been declared in the declaration section
• The execution section of any PL/SQL block always begins with the
keyword BEGIN and Ends with the keyword END.
• Only mandatory section in PL/SQL block
• This section support all DML commands and SQL+ build in function,
and it also supports DDL commands using native Dynamic SQL or
DBMS_SQL build-in package.
The Exception-handling section
• This is the last section of PL/SQL block which is optional just like the
declaration section.
• This section contain statements that are executed when a runtime
error occurs within the block
• We can sat allException-handling code goes here
Hello World Program in PL/SQL
begin
dbms_output.put_line('Hello World');
end;
• dbms_output.put_line(): It is used for printing the output to the console
screen. It is due to output activation that we write ‘set serveroutput on’ at
start of the program. dbms_output.put_line()
DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
PL/SQL Program To Add Two
Numbers
DECLARE
a integer := 30;
b integer := 40;
c integer;
BEGIN
c := a + b;
dbms_output.put_line('Value of c: ' || c);
END;
DECLARE
f real;
BEGIN
f := 100.0/3.0;
dbms_output.put_line('Value of f:'||f);
END;
Variable Scope in PL/SQL:
PL/SQL allows nesting of blocks. A program block can contain another inner block.
If you declare a variable within an inner block, it is not accessible to an outer block.
There are two types of variable scope:
Local Variable: Local variables are the inner block variables which are not
accessible to outer blocks.
Global Variable: Global variables are declared in outermost block.
Example of Local and Global variables
DECLARE
-- Global variables
num1 number := 95;
num2 number := 85;
BEGIN
dbms_output.put_line('Outer Variable num1: ' || num1);
dbms_output.put_line('Outer Variable num2: ' || num2);
DECLARE
-- Local variables
num1 number := 195;
num2 number := 185;
BEGIN
dbms_output.put_line('Inner Variable num1: ' || num1);
dbms_output.put_line('Inner Variable num2: ' || num2);
END;
END;
/
Example of PL/SQL constant
DECLARE
-- constant declaration
pi constant number := 3.141592654;
-- other declarations
radius number(5,2);
dia number(5,2);
circumference number(7, 2);
area number (10, 2);
BEGIN
-- processing
radius := 9.5;
dia := radius * 2;
circumference := 2.0 * pi * radius;
area := pi * radius * radius;
-- output
dbms_output.put_line('Radius: ' || radius);
dbms_output.put_line('Diameter: ' || dia);
dbms_output.put_line('Circumference: ' || circumference);
dbms_output.put_line('Area: ' || area);
END;
Example of PL/SQL If Statement
DECLARE
a number(3) := 500;
BEGIN
-- check the boolean condition using if statement
IF( a < 20 ) THEN
-- if condition is true then print the following
dbms_output.put_line('a is less than 20 ' );
ELSE
dbms_output.put_line('a is not less than 20 ' );
END IF;
dbms_output.put_line('value of a is : ' || a);
END;
PL/SQL Case Statement
•The PL/SQL CASE statement facilitates you to execute a
sequence of statements based on a selector. A selector can be
anything such as variable, function or an expression that the
CASE statement checks to a boolean value.
•The CASE statement works like the IF statement, only using
the keyword WHEN. A CASE statement is evaluated from top
to bottom. If it get the condition TRUE, then the corresponding
THEN calause is executed and the execution goes to the END
CASE clause.
DECLARE
grade char(1) := 'A';
BEGIN
CASE grade
when 'A' then dbms_output.put_line('Excellent');
when 'B' then dbms_output.put_line('Very good');
when 'C' then dbms_output.put_line('Good');
when 'D' then dbms_output.put_line('Average');
when 'F' then dbms_output.put_line('Passed with Grace');
else dbms_output.put_line('Failed');
END CASE;
END;
PL/SQL Loop
The PL/SQL loops are used to repeat the execution of one or more
statements for specified number of times. These are also known as iterative
control statements.
Syntax for a basic loop:
LOOP
Sequence of statements;
END LOOP;
Types of PL/SQL Loops
There are 4 types of PL/SQL Loops.
Basic Loop / Exit Loop
While Loop
For Loop
Cursor For Loop
PL/SQL Exit Loop (Basic Loop)
PL/SQL exit loop is used when a set of statements is to be executed at least once
before the termination of the loop. There must be an EXIT condition specified in
the loop, otherwise the loop will get into an infinite number of iterations. After the
occurrence of EXIT condition, the process exits the loop.
Example:
DECLARE
i NUMBER := 1;
BEGIN
LOOP
EXIT WHEN i>=10;
DBMS_OUTPUT.PUT_LINE(i);
i := i+1;
END LOOP;
END;
PL/SQL While Loop
PL/SQL while loop is used when a set of statements has to be executed as long as a
condition is true, the While loop is used. The condition is decided at the beginning
of each iteration and continues until the condition becomes false.
Example:
DECLARE
i INTEGER := 1;
BEGIN
WHILE i <= 10 LOOP
DBMS_OUTPUT.PUT_LINE(i);
i := i+1;
END LOOP;
END;
PL/SQL FOR Loop
PL/SQL for loop is used when when you want to execute a set of statements
for a predetermined number of times. The loop is iterated between the start
and end integer values. The counter is always incremented by 1 and once the
counter reaches the value of end integer, the loop ends.
Example:
Example2 :
BEGIN
FOR k IN 1..10 LOOP DECLARE
VAR1 NUMBER;
-- note that k was not declared BEGIN
VAR1:=10;
DBMS_OUTPUT.PUT_LINE(k);
FOR VAR2 IN 1..10
END LOOP; LOOP
DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
END; END LOOP;
END;
PL/SQL GOTO Statement
BEGIN
UPDATE customers SET customer_name = ‘JOHN’, city = ‘hydrabad’
WHERE customer_id = 1;
END;
Delete
BEGIN
DELETE FROM customers WHERE customer_id=2;
END;
BEGIN
DELETE FROM customers;
END;
Function and Procedure
• Both have similar kind of properties
• When it comes to returning the value, function has return data type it
will return the value when u use function.
• In procedure it may or may not return the value
• Function will performants single task and return one value, but
procedure will perform multiple task and it may or may not return
the values or it can return more than one value also.
• Procedure can the executed independently, it doesn't not needed any
PL/SQL
• But function doesn't run in with out PL/SQL
procedure
• The procedure contains a header and a body.
o Header: The header contains the name of the procedure and the parameters or variables passed
to the procedure.
o Body: The body contains a declaration section, execution section and exception section similar
to a general PL/SQL block.
• The value of the parameter cannot be overwritten by the procedure or the function.
• OUT parameters: The OUT parameter cannot be referenced by the procedure or function, but
the value of the parameter can be overwritten by the procedure or function.
• INOUT parameters: The INOUT parameter can be referenced by the procedure or function and
create table user(id number(10) primary key,
name varchar2(100));
• Now write the procedure code to insert record in user table.
create or replace procedure "INSERTUSER"
(id IN NUMBER,
name IN VARCHAR2)
is
begin
insert into user values(id,name);
end;
PL/SQL program to call procedure
Let's see the code to call above created procedure.
BEGIN
insertuser(101,'Rahul');
dbms_output.put_line('record inserted successfully');
END;
• Now, see the "USER" table, you will see one record is inserted.
PL/SQL Drop Procedure
Syntax for drop procedure
DROP PROCEDURE procedure_name;
Example of drop procedure
DROP PROCEDURE insertuser;
PL/SQL Function
• The PL/SQL Function is very similar to PL/SQL Procedure. The main difference between procedure and a
function is, a function must always return a value, and on the other hand a procedure may or may not return
a value. Except this, all the other things of PL/SQL procedure are true for PL/SQL function too.
Syntax to create a function:
CREATE [OR REPLACE] FUNCTION function_name [parameters]
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];
PL/SQL Function Example
Let's see a simple example to create a function.
create or replace function adder(n1 in number, n2 in number)
return number
is
n3 number(8);
begin
n3 :=n1+n2;
return n3;
end;
DECLARE
n3 number(2);
BEGIN
n3 := adder(11,22);
dbms_output.put_line('Addition is: ' || n3);
END;
The maximum of two values
DECLARE
a number;
b number;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;
RETURN z;
END;
BEGIN
a:= 23;
b:= 45;
c := findMax(a, b);
dbms_output.put_line(' Maximum of (23,45): ' || c);
END;
Physical Storage Systems
Physical Storage Systems
• There are several types of storage medias.
• volatile storage: loses contents when power is switched off
• non-volatile storage:
• Contents persist even when power is switched off.
• Includes secondary and tertiary storage, as well as batter-backed up main-memory.
• Factors affecting choice of storage media include
• Speed with which data can be accessed
• Cost per unit of data
• Reliability
Storage device Hierarchy
• After 100,000 to 1,000,000 erases, erase block becomes unreliable and cannot be used
• wear leveling
File organization
• Data base is a collection of files
• Files consist of sequences of records
• Each records consist of fields.
• File can be stored in different methods
• Lets consider in database the files are stored in sequential blocks in
contiguous allocation
• There are three types of allocation in database
• 1. contiguous , 2. non contiguous and 3. index allocation
• CPU search in main memory (RAM) if its not there in RAM it will
search in hard disk, which contain blocks.
• If the record is found its is stored in RAM only from there CPU can
access that record.
• Hard disk will transfer only complete block to RAM.
• File organization is nothing but data is organized in hard disk and how
we are searching record in the hard disk and delete the record in the
hard disk with efficient manner.
Fixed-Length Records
• Simple approach:
• Store record i starting from byte n * (i – 1), where n is the size of each record.
• Record access is simple but records may cross blocks
• Modification: do not allow records to cross block boundaries
Fixed-Length Records
• Deletion of record i: alternatives:
• move records i + 1, . . ., n to i, . . . , n – 1
• move record n to i
• do not move records, but link all free records on a free list
Record 3 deleted
Fixed-Length Records
• Deletion of record i: alternatives:
• move records i + 1, . . ., n to i, . . . , n – 1
• move record n to i
• do not move records, but link all free records on a free list
Record 3 deleted and replaced by record 11
Fixed-Length Records
• Deletion of record i: alternatives:
• move records i + 1, . . ., n to i, . . . , n – 1
• move record n to i
• do not move records, but link all free records on a free list
Indexes as Access Paths
• A single-level index is an auxiliary file that makes it more efficient to
search for a record in the data file.
• The index is usually specified on one field of the file (although it could
be specified on several fields)
• One form of an index is a file of entries <field value, pointer to
record>, which is ordered by field value
• The index is called an access path on the field.
Indexes as Access Paths (contd.)
• The index file usually occupies considerably less disk blocks than the data file
because its entries are much smaller
• A binary search on the index yields a pointer to the file record
• Indexes can also be characterized as dense or sparse
• A dense index has an index entry is created for every search key value (and hence
every record) in the data file.
• A sparse (or nondense) index, on the other hand, has index entries for only some of
the search values
Types of Indexes
• Types of Single-level Ordered Indexes
• Primary Indexes
• Clustering Indexes
• Secondary Indexes
• Multilevel Indexes
• B tree
• B+ tree
Slide 14- 64
Types of Single-Level Indexes
• Primary Index
• Primary Index = primary key + ordered data (database has to in ordered file)
• Primary indexing has fixed length size with 2 fields.
• First field is primary key and second field is pointer to data file.
• Single Blocks can have only fixed number of records, but Index entry is created for
first record of each block. which is called the block anchor
• A similar scheme can use the last record in a block.
• No. of index entries = no. of blocks.
• A primary index is a nondense (sparse) index, since it includes an entry for each disk
block of the data file and the keys of its anchor record rather than for every search
value.
Primary index on the ordering key field
Types of Single-Level Indexes
• Secondary Index
• Secondary Index = non key or candidate key + unordered.
• No. of entry in index file = no. of entries in mail file
• A secondary index provides a secondary means of accessing a file for which some
primary access already exists.
• The secondary index may be on a field which is a candidate key and has a unique
value in every record, or a non-key with duplicate values.
• The index is an ordered file with two fields.
• The first field is of the same data type as some non-ordering field of the data file that is
an indexing field.
• The second field is either a block pointer or a record pointer.
• There can be many secondary indexes (and hence, indexing fields) for the same file.
• Includes one entry for each record in the data file; hence, it is a dense index
Example of a Dense Secondary Index
An Example of a Secondary Index
Slide 14- 70
Types of Single-Level Indexes
• Clustering Index
• Clustering Index = non key + ordered file.
• The data file is ordered on a non-key field unlike primary index, which requires that
the ordering field of the data file have a distinct value for each record.
• Includes one index entry for each distinct value of the field; the index entry points
to the first data block that contains records with that field value.
• There will be only one entry for each unique value of the non-key attribute.
• It is another example of nondense index where Insertion and Deletion is relatively
straightforward with a clustering index.
A Clustering Index Example
• FIGURE 14.2
A clustering index
on the
DEPTNUMBER
ordering non-key
field of an
EMPLOYEE file.
Another Clustering Index Example
Multi-Level Index
Multi-Level Index
1 2 12 25
1 2 6 12 14 25 28
B-Trees 82
Constructing a B-tree (contd.)
Adding 17 to the right leaf node would over-fill it, so we take the
middle key, promote it (to the root) and split the leaf
8 17
1 2 6 12 14 25 28
1 2 6 7 12 14 16 25 28 48 52
B-Trees 83
Constructing a B-tree (contd.)
Adding 68 causes us to split the right most leaf, promoting 48 to the
root, and adding 3 causes us to split the left most leaf, promoting 3
to the root; 26, 29, 53, 55 then go into the leaves
3 8 17 48
1 2 6 7 12 14 16 25 26 28 29 52 53 55 68
B-Trees 84
Constructing a B-tree (contd.)
17
3 8 28 48
1 2 6 7 12 14 16 25 26 29 45 52 53 55 68
B-Trees 85
Inserting into a B-Tree
• Attempt to insert the new key into a leaf
• If this would result in that leaf becoming too big, split the leaf into
two, promoting the middle key to the leaf’s parent
• If this would result in the parent becoming too big, split the parent
into two, promoting the middle key
• This strategy might have to be repeated all the way to the top
• If necessary, the root is split in two and the middle key is promoted to
a new root, making the tree one level higher
B-Trees 86
B+ tree in data base
• B+ tree is a concept in data structures, which is used to implement
indexing in data base.
• In B+ tree, leaf nodes denotes actual data pointers
• All leaf nodes remains at same height
• The leaf nodes are linked using linked list
• B+ tree occupy a little more space than B tree, because it used linked
list for connecting all the leaf nodes.
Advantages of B+ Tree
1. Records can be fetched in equal number of disk accesses.
2. Height of the tree remains balanced and less as compare to B tree.
3. We can access the data stored in a B+ tree sequentially as well as
directly.
4. Keys are used for indexing.
5. Faster search queries as the data is stored only on the leaf nodes.
Example
Example (cont…)
Example (cont…)
Deletion in B+ Tree
• Step 1: Delete the key and data from the leaves.
• Step 2: if the leaf node contains less than minimum number of
elements, merge down the node with its sibling and delete the key in
between them.
• Step 3: if the index node contains less than minimum number of
elements, merge the node with the sibling and move down the key in
between them.
Deleting in B+ tree
Deleting in B+ tree (cont…)
Deleting in B+ tree (cont…)
Raid (Redundant array of independent disk)
• RAID or redundant array of independent disk, is a technology to
connect multiple secondary storage device and use them as a single
storage media.
• RAID consist of an array of disk in which multiple disk are connected
together achieve different goals.
RAID 0 ( striping )- block striping
• In this level, a strip array of disk is implemented.
• The data is broken down into blocks and block are distributed among
disk.
• Each disk receives a block of data to read or write in parallel.
• Advantage: it enhance the speed and performance of the storage
device
• Dis-advantage: there is no parity(error correction code) and backup in
level 0
RAID-1 Mirroring disk
• RAID-1 uses mirroring technique.
• When data is send to a RAID controller, it sends a copy of data to all
the disk in the array.
• RAID level 1 is also called mirroring and provides 100% redundancy in
case of a failure.
RAID-2 (memory style error correcting codes)
• RAID 2 record error detection code using hamming distant for its data
stripped on different disk.
• Like level0, each data bit is a word is recorded on a separate disk and
ECC (error correcting code) of the data word are stored on a different
set disk.
• Dis-advantage : due to its compels structure and high cost, RAID 2 is
not commercially available.
RAID 3 (Bit interleaved parity)
• RAID 3 strip the data onto multiple disk
• The parity bit generate for data word is stored on a different disk.
• Instead of error correcting code in RAID 3 parity bit is stored in
different disk.
• In RAID 2 the structure is complex and cost is heigh, to over come this
in RAID 3 parity bit is used.
• In RAID 3 also stored the duplicate data in additional it used parity bit
instead of error correcting code.
RAID 4(block interleaved parity)
• In this level, an entire block of data is written onto data disk and then
the parity is generated and stored on a different disk,
• Level 3 used byte-level stripping where level 4 uses block level
striping
• Both level 3 and level 4 require at least three disk to implement RAID.
• In first disk data and in second disk we have duplication of data and in
level three parity generator used to store block of parity data.
RAID 5(block interleaved distributed parity)
• Write whole data blocks onto different disk, but the parity bits
generated for data blocks strips are distributed among all the data
disk rather than soring on a different dedicated disk.
• Instead of having a dedicated disk for error correction cord or parity
bit, in RAID 5 we use random/distributed disk to store the parity bit.
RAID 6 (P+Q)
• RAID-6 is an extension of level-5
• In this level, two independent parities are generated and stores in
distributed fashion among multiple disk
• Two parities provide additional fault tolerance.
• This level requires at least four disk drive to implement RAID.
• P is parity bit and Q is ECC(Error correcting code) need two different
disk in RAID 6.
Query Processing Overview