Lectures
Lectures
2
2
5
5
7
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
11
11
11
13
13
13
. . . . . .
. . . . . .
DECODE
. . . . . .
.
.
.
.
.
.
.
.
18
18
23
25
27
.
.
.
.
.
31
31
32
33
34
35
37
37
37
39
44
44
45
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
CONTENTS
Exercises
Lab for W1
Lab for W3
Lab for W4
Lab for W4
Lab for W4
Lab for W5
& W2 . . . . .
. . . . . . . . .
FOR GROUP A
FOR GROUP B
FOR GROUP C
FOR GROUP C
.
.
.
.
.
.
7
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
49
49
49
50
.
.
.
.
.
.
53
53
53
54
55
56
58
.
.
.
.
.
.
.
.
.
.
.
.
ii
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
CONTENTS
Chapter 1
RDBMS Programming Part1: Basic
1.1
Course Layout
Week 11: Class 2 (Lecture 22) PL/SQL Package Part 2: Grants and Synonyms.
Managing Packages in the Database Catalog.
Week 12: Class 1 (Lecture 23) Database Triggers Part 1. Use of triggers in
integrity Management of BI.
Week 12: Class 2 (Lecture 24) Database Triggers Part 2. Triggers and Procedures. Types of Triggers. Controlling Triggers.
Week 13: Class 1 (Lecture 25) Introduction to Dynamic SQL.Dynamic SQL
Architecture.Dynamic Statements. Dynamic Statements with inputs. DBMSSQL
Package.
Week 13: Class 2 (Lecture 26) Introduction to Object in Database Programming.
Week 14: Class 1 (Lecture 27)
Database Administration: Introduction Part 1: Types of Oracle Database Users.Tasks
of a Database Administrator.
Week 14: Class 2 (Lecture 28) Database Administration: Introduction Part
2: Managing Users and Securing the Database.Monitoring Database Operations.
Backup Process in Oracle Database.
Week 15: Class 1 (Lecture 29) Database performance Tuning Part 1: Primary
and Secondary Index. Simple and complex index. Reverse Key Index. Use of
ROWID.
Week 15: Class 2 (Lecture 30) Database performance Tuning 2: Views, clusters,
sequence. PL/SQL Security.
Brief Introduction to other Relational Databases such as : MySQL, PostGRE, MS
SQL Server (O).
Chapter 2
Lecture (Lec 1 & 2) for Week 1
2.1
Synonyms A synonym is an alias for any table, view, materialized view, sequence,
procedure, function, package, type, Java class schema object, user-defined object
type, or another synonym. Because a synonym is simply an alias, it requires no
storage other than its definition in the data dictionary.
Data Dictionary One of the most important parts of an Oracle database is its
data dictionary, which is a read-only set of tables that provides information about
the database. A data dictionary contains:
The definitions of all schema objects in the database (tables, views, indexes,
clusters, synonyms, sequences, procedures, functions, packages, triggers, and
so on)
How much space has been allocated for, and is currently used by, the schema
objects
Integrity constraint information
Privileges and roles each user has been granted
Auditing information, such as who has accessed or updated various schema
objects
DDL and DML SQL statements are divided into two major categories: data
definition language (DDL) and data manipulation language (DML).
DDL: DDL statements are used to build and modify the structure of your tables
and other objects in the database.
DDL Example: CREATE TABLE , ALTER TABLE.
DML:DML statements are used to work with the data in tables. When you are
connected to most multi-user databases (whether in a client program or by a connection from a Web page script), you are in effect working with a private copy
of your tables that cant be seen by anyone else until you are finished (or tell the
system that you are finished).
DML Example: The insert statement. (INSERT INTO table name VALUES
(value 1, ... value n);)
The update statement. UPDATE table name SET attribute = expression
WHERE condition;
Cardinality In data modelling terms, cardinality is how one table relates to another.
1-1 (one row in table A relates to one row in tableB)
1-Many (one row in table A relates to many rows in tableB)
Many-Many (Many rows in table A relate to many rows in tableB)
6
2.1.1
(source: https://docs.oracle.com/cd/A57673_01/DOC/server/doc/SCN73/ch4.htm)
The following block-diagram shows the relationship.
Data blocks.At the finest level of granularity, Oracle stores data in data blocks
(also called logical blocks, Oracle blocks, or pages). One data block corresponds to
a specific number of bytes of physical database space on disk.
Extent. The next level of logical database space is an extent. An extent is a
specific number of contiguous data blocks allocated for storing a specific type of
information.
Segment. The level of logical database storage above an extent is called a segment.
A segment is a set of extents, each of which has been allocated for a specific data
structure and all of which are stored in the same tablespace. For example, each
tables data is stored in its own data segment, while each indexs data is stored in
8
its own index segment. If the table or index is partitioned, each partition is stored
in its own segment.
Oracle allocates space for segments in units of one extent. When the existing
extents of a segment are full, Oracle allocates another extent for that segment.
Step 1: Create a Tablespace first.
CREATE TABLESPACE mytspace
DATAFILE / u02 / o r a c l e / data / lmtbsb01 . dbf SIZE 50M
EXTENT MANAGEMENT LOCAL AUTOALLOCATE;
AUTOALLOCATE causes the tablespace to be system managed with a minimum
extent size of 64K.
Step 2 (a): Create an user and assign that user to a specific tablespace.
CREATE USER s i d n e y
IDENTIFIED BY t e s t 1 2 3
DEFAULT TABLESPACE mytspace
Specify the default tablespace for objects that the user creates. If you omit this clause,
then the users objects are stored in the database default tablespace.
If no default tablespace has been specified for the database, then the users objects are
stored in the SYSTEM tablespace.
There are a number of other parameters which we are now ignoring as not part of our
study objective.
Step 2 (b): Create a specific table and assign a tablespace with it (this will overrule
previous).
create table intel
( dt v a r c h a r 2 ( 2 0 ) ,
tm v a r c h a r 2 ( 2 8 ) ,
ep number ,
moteid number ,
t e m p e r a t u r e number ( 1 2 , 5 ) ,
humidity number ( 2 0 , 8 ) ,
l i g h t number ( 1 2 , 6 ) ,
v o l t a g e number ( 1 0 , 6 )
) t a b l e s p a c e NEW TBSPACE;
Step 3: How to get information about free available space for a tablespace. Use
DBA_FREE_SPACE data-dictionary.
9
10
Chapter 3
Lecture (Lec 3 & 4) for Week 2
3.1
Before you start: SQL*Plus tells you how many rows it found in One table after a
valid query on it. (Notice the 14 rows selected notation at the bottom of the display.)
This is called feedback.
It can be controlled in the following way:
3.1.1
equal to 6.
6.
6.
6.
LIKE
Feature LIKE Mo% Feature begins with the letters Mo.
Feature LIKE _ _ I% Feature has an I in the third position.
Feature LIKE %o%o% Feature has two os in it.
LIKE performs pattern matching. An underline character ( ) represents exactly one
character. A percent sign (%) represents any number of characters, including zero characters.
NULL and NOT NULL
IS NULL essentially instructs Oracle to identify columns in which the data is missing.
Tests Against a List of Values.
For Numbers
Page IN (1,2,3) => Page is in the list (1,2,3)
Page NOT IN (1,2,3) => Page is not in the list (1,2,3)
Page BETWEEN 6 AND 10 => Page is equal to 6, 10, or anything in between
Page NOT BETWEEN 6 AND 10 => Page is below 6 or above 10
For Strings
AND , OR Similar.
12
3.1.2
Sub-queries.
3.2
3.2.1
Joins
3.2.1.1
The natural join returned the results as if you had typed in the following:
select BO.Title
from BOOK_ORDER BO, BOOKSHELF
where BO.Title = BOOKSHELF.Title
and BO.Publisher = BOOKSHELF.Publisher
and BO.CategoryName = BOOKSHELF.CategoryName;
Note: The main difference is that INNER JOIN is used in real life; NATURAL JOIN
is only used in textbooks.
INNER JOIN Note that they support the on and using clauses, so you can specify
your join criteria as shown in the following listing:
New Syntax:
SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date
FROM suppliers
INNER JOIN orders
ON suppliers.supplier_id = orders.supplier_id;
Old Syntax:
SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date
FROM suppliers, orders
WHERE suppliers.supplier_id = orders.supplier_id;
(b) Classical format
SELECT ...
FROM
dataset_one d1
,
dataset_two d2
WHERE d1.column(s) = d2.column(s)
AND
...
14
Outer Join
The New syntax for the Oracle LEFT OUTER JOIN is:
SELECT columns
FROM table1
LEFT [OUTER] JOIN table2
ON table1.column = table2.column;
Example:
SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date
FROM suppliers
LEFT OUTER JOIN orders
ON suppliers.supplier_id = orders.supplier_id;
Example Old:
SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date
FROM suppliers, orders
WHERE suppliers.supplier_id = orders.supplier_id(+);
Right Outer:
New:
SELECT orders.order_id, orders.order_date, suppliers.supplier_name
FROM suppliers
RIGHT OUTER JOIN orders
ON suppliers.supplier_id = orders.supplier_id;
Right Outer:
Old:
15
Full Outer :
SELECT columns
FROM table1
FULL [OUTER] JOIN table2
ON table1.column = table2.column;
New:
SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date
FROM suppliers
FULL OUTER JOIN orders
ON suppliers.supplier_id = orders.supplier_id;
Old:
As a final note, it is worth mentioning that the FULL OUTER JOIN example above could n
written in the old syntax without using a UNION query.
Left and Right Outer: So, what is the difference between the right and left outer
joins? The difference is simple in a left outer join, all of the rows from the left table will
be displayed, regardless of whether there are any matching columns in the right table.
In a right outer join, all of the rows from the right table will be displayed, regardless of
whether there are any matching columns in the left table. Hopefully the example that
we gave above help clarified this as well.
Employee
EmpID EmpName
13 Jason
8 Alex
3 Ram
17 Babu
25 Johnson
Location
EmpID EmpLoc
13 San Jose
8 Los Angeles
3 Pune, India
17 Chennai, India
39 Bangalore, India
17
Chapter 4
Lecture (Lec 5 & 6) for Week 3
4.1
Built-in Functions
Parameters or Arguments:
string1 is the string to pad characters to (the left-hand side).
paddedlength is the number of characters to return. If the paddedlength is smaller
than the original string, the LPAD function will truncate the string to the size of
paddedlength.
padstring is optional. This is the string that will be padded to the left-hand side
of string1. If this parameter is omitted, the LPAD function will pad spaces to the
left-side of string1.
Example:
18
LPAD(tech, 7);
Result:
tech
LPAD(tech, 2);
Result: te
LPAD(tech, 8, 0);
Result: 0000tech
LPAD(tech on the net, 15, z);
Result: tech on the net
LPAD(tech on the net, 16, z);
Result: ztech on the net
4. LTRIM, RTRIM, and TRIM: They trim off (removes) all specified characters
from the left and right ends of strings.
The syntax:
LTRIM( string1, [ trimstring ] )
Parameters or Arguments:
string1 is the string to trim the characters from the left-hand side.
trimstring is the string that will be removed from the left-hand side of string1. If
this parameter is omitted, the LTRIM function will remove all leading spaces from
string1.
Example:
LTRIM(
tech)
Result: tech
LTRIM(
tech, )
Result: tech
LTRIM(000123, 0)
Result: 123
LTRIM(123123Tech, 123)
Result: Tech
19
LTRIM(123123Tech123, 123)
Result: Tech123
LTRIM(xyxzyyyTech, xyz)
Result: Tech
LTRIM(6372Tech, 0123456789)
Result: Tech
Last Example: In this example, every number combination from 0 to 9 has been
listed in the trimstring parameter. By doing this, it does not matter the order that
the numbers appear in string1, all leading numbers will be removed by the LTRIM
function.
Combining: LTRIM and RTRIM
(RTRIM(*#Hello*,*)
LTRIM(*#Hello*,*#)
Now combine them:
LTRIM(RTRIM(*#Hello*,*),*#)
Using the TRIM Function: The preceding example showed how to combine two
functionsa useful skill when dealing with string manipulation. If you are trimming
the exact same data from both the beginning and the end of the string, you can use
the TRIM function in place of an LTRIM/RTRIM combination.
TRIM(
tech
Result: tech
TRIM( FROM
Result: tech
tech
20
5. LENGTH LENGTH tells you how long a string ishow many characters it has in
it, including letters, spaces, and anything else.
6. SUBSTR:
The syntax:
SUBSTR( string, start_position, [ length ] )
Parameters or Arguments:
string is the source string.
startposition is the position for extraction. The first position in the string is always
1.
length is optional. It is the number of characters to extract. If this parameter is
omitted, the SUBSTR function will return the entire string.
Note: If startposition is a positive number, then the SUBSTR function starts from
the beginning of the string.
If startposition is a negative number, then the SUBSTR function starts from the
end of the string and counts backwards.
Example:
21
SUBSTR(This is a test, 6, 2)
Result: is
SUBSTR(This is a test, 6)
Result: is a test
SUBSTR(TechOnTheNet, 1, 4)
Result: Tech
SUBSTR(TechOnTheNet, -3, 3)
Result: Net
SUBSTR(TechOnTheNet, -6, 3)
Result: The
SUBSTR(TechOnTheNet, -8, 2)
Result: On
7. INSTR:
Syntax:
INSTR( string, substring [, start_position [,
nth_appearance ] ] )
Parameters or Arguments:
string is the string to search.
substring is the substring to search for in string.
startposition is the position in string where the search will start. This argument is
optional. If omitted, it defaults to 1. The first position in the string is 1. If the
startposition is negative, the INSTR function counts back startposition number of
characters from the end of string and then searches towards the beginning of string.
nthappearance is the nth appearance of substring. This is optional. If omitted, it
defaults to 1.
Example:
INSTR(Tech on the net, e)
Result: 2
(the first occurrence of e)
INSTR(Tech on the net, e, 1, 1)
Result: 2
(the first occurrence of e)
22
The ASCII function performs the reverse operationbut if you pass it a string, only
the first character of the string will be acted upon:
select ASCII(FSOUG) from DUAL;
ASCII(FSOUG)
-------------70
4.2
Regular Expression
Mainly used for advanced searching. Oracle 10g introduced support support for regular
expressions in SQL and PL/SQL.
Example 1 : REGEXP SUBSTR
DROP TABLE t1;
CREATE TABLE t1 (
data VARCHAR2(50)
);
INSERT INTO t1 VALUES (FALL 2014);
INSERT INTO t1 VALUES (2014 CODE-B);
INSERT INTO t1 VALUES (CODE-A 2014 CODE-D);
23
DATA
-------------------------------------------------------------------------------------FALL 2014
2014 CODE-B
CODE-A 2014 CODE-D
ADSHLHSALK
FALL 2004
5 rows selected.
SQL>
Objective: If we needed to return rows containing a specific year we could use the
LIKE operator (WHERE data LIKE %2014%), but how do we return rows using a
comparison (, =, , =, )?
One Solution is: to pull out the 4 figure year and convert it to a number, so we dont
accidentally do an ASCII comparison.
That is pretty easy using regular expressions.
Solution using Regular Expression: We can identify digits using the "\d" or "[0-9]"
operators. We want a group of four of them, which is represented by the "{4}" operator.
So our regular expression will be "\d{4}" or [0-9]4. The REGEXP_SUBSTR function
returns the string matching the regular expression, so that can be used to extract the
text of interest. We then just need to convert it to a number and perform our comparison.
Solution Query:
SELECT *
FROM
t1
WHERE TO_NUMBER(REGEXP_SUBSTR(data, \d{4})) >= 2014;
DATA
--------------------------------------------------------FALL 2014
2014 CODE-B
CODE-A 2014 CODE-D
3 rows selected.
SQL>
24
4.3
select Dept,Desig,count(*)Total
from emp
group by rollup(Dept,Desig)
order by Dept,Desig;
Sample Output:
25
DEPT DESIG
TOTAL
---------- -------------------10 Asst Manager 2
10 Manager 3
10 5
20 Asst Manager 3
20 Manager 2
20 5
30 Asst Manager 1
30 Manager 2
30 3
13
----------
Example:
select Dept,Desig,count(*)Total
from emp
26
group by cube(Dept,Desig)
order by Dept,Desig;
Sample Output:
DEPT DESIG
TOTAL
---------- -------------------- ---------10 Asst Manager
2
10 Manager 3
10 5
20 Asst Manager
3
20 Manager 2
20 5
30 Asst Manager
1
30 Manager 2
30 3
Asst Manager
6
Manager 7
DEPT DESIG
TOTAL
---------- -------------------- ---------13
4.4
Date Operations
DATE is an Oracle datatype, just as VARCHAR2 and NUMBER are, and it has its
own unique properties. The DATE datatype is stored in a special internal Oracle format
that includes not just the month, day, and year, but also the hour, minute, and second.
TIMESTAMP datatype stores fractional seconds.
select SysDate from DUAL;
SYSDATE
--------27
28-FEB-08
Month Part:
Month Formats:
Format Result
Month
August
Mon
Aug
Day Part:
The day of the month is produced by the DD in the format. A suffix of th on DD
tells Oracle to use ordinal suffixes, such as TH, RD, and ND with the number. In
this instance, the suffixes are also case sensitive, but their case is set by the DD,
not the th:
Format
DDth or
Ddth or
Ddth or
Result
DDTH 11TH
DdTH 11Th
ddTH 11th
28
3. Difference Between Two Dates Date1 - Date1 gives the result in number of
days.
Example:
select max(hire_date)MX
from employees;
select min(hire_date)MN
from employees;
select (max(hire_date)-min(hire_date))/365 Year
from employees;
select hire_date
from employees
where hire_date between TO_DATE(01-JAN-06,DD-MON-YY) AND TO_DATE(01-FEB-09,
29
EXTRACT Function: You can use the EXTRACT function in place of the
TO CHAR function when you are selecting portions of date valuessuch as just the
month or day from a date. The EXTRACT functions syntax is:
EXTRACT
( { { YEAR
| MONTH
| DAY
| HOUR
| MINUTE
| SECOND
}
| { TIMEZONE_HOUR
| TIMEZONE_MINUTE
}
| { TIMEZONE_REGION
| TIMEZONE_ABBR
}
}
FROM { datetime_value_expression | interval_value_expression }
)
Example:
select First_Name, EXTRACT( Month from hire_date) M
from employees;
30
Chapter 5
Lecture (Lec 6 & 7) for Week 4
Introduction to PL SQL.
A few points about PL SQL:
PL/SQL lets you write code once and deploy it in the database nearest the data.
PL/SQL can simplify application development, optimize execution, and improve
resource utilization in the database.
The language is a case-insensitive programming language, like SQL.
History: PL/SQL was developed by modeling concepts of structured programming, static data typing, modularity, exception management, and parallel (concurrent) processing found in the Ada programming language. The Ada programming
language, developed for the United States Department of Defense, was designed
to support military real-time and safety-critical embedded systems, such as those in
airplanes and missiles. The Ada programming language borrowed significant syntax
from the Pascal programming language, including the assignment and comparison
operators and the single-quote delimiters.
5.0.1
Block
execution_statements
[EXCEPTION]
exception_handling_statements
END;
/
Lets write out first block that will do nothing:
BEGIN
NULL;
END;
/
Hello World:
SET SERVEROUTPUT ON SIZE 1000000
BEGIN
dbms_output.put_line(Hello World.);
END;
/
scanf:
--scanf-DECLARE
my_var VARCHAR2(30);
BEGIN
my_var := &i;
dbms_output.put_line(Hello || my_var );
END;
5.0.2
32
. Association
The component selector is a period, and it glues references together, for example, a
schema and a table, a package and a function, or an object and a member method.
Component selectors are also used to link cursors and cursor attributes (columns).
The following are some prototype examples:
schema_name.table_name
package_name.function_name
object_name.member_method_name
cursor_name.cursor_attribute
object_name.nested_object_name.object_attribute
These are referenced in subsequent chapters throughout this book.
@ Association. The remote access indicator lets you access a remote database
through database links.
= Comparison.
!= Comparison Not equal to.
Delimiter In-line comment.
/* Delimiter */ Multi-line comment.
Delimiter.
quoted identifier delimiter is a double quote. It lets you access tables created
in case-sensitive fashion from the database catalog. This is required when you ha
created database catalog objects in case-sensitive fashion. You can do this from
Oracle 10g forward.
For example, you create a case-sensitive table or column by using quoted identifi
delimiters:
CREATE TABLE "Demo"
("Demo_ID" NUMBER
, demo_value VARCHAR2(10));
You insert a row by using the following quote-delimited syntax:
INSERT INTO "Demo1" VALUES
(1,One Line ONLY.);#
5.1
Data-types
33
5.1.1
Scalar Datatypes
Scalar datatypes use the following prototype inside the declaration block of your programs:
variable_name datatype [NOT NULL] [:= literal_value];
1. Boolean. The BOOLEAN datatype has three possible values: TRUE, FALSE,
and NULL.
var1 BOOLEAN; -- Implicitly assigned a null value.
var2 BOOLEAN NOT NULL := TRUE; -- Explicitly assigned a TRUE value.
var3 BOOLEAN NOT NULL := FALSE; -- Explicitly assigned a FALSE value.
There is little need to subtype a BOOLEAN datatype, but you can do it. The
subtyping syntax is:
;
i s [ | | LENGTH( c ) | | ] ) ;
i s [ | | LENGTH( v ) | | ] ) ;
i s [ | | LENGTH( v ) | | ] ) ; END;
Output:
c is [32767]
v is [1]
v is [2]
34
The output shows that a CHAR variable sets the allocated memory size when defined. The allocated memory can exceed what is required to manage the value in
the variable. The output also shows that the VARCHAR2 variable dynamically
allocates only the required memory to host its value.
More on VARCHAR2: You can size a VARCHAR2 datatype up to 32,767 bytes
in length.You can store character strings larger than 4,000 bytes in CLOB or LONG
columns.
Lets look at the example below:
5.1.2
Composite Datatypes
There are two composite generalized datatypes: records and collections. (Will be covered
next).
Just have look at the following example for Record.
DECLARE
TYPE demo_record_type IS RECORD
35
( id NUMBER DEFAULT 1
, value VARCHAR2(10) := One);
demo DEMO_RECORD_TYPE;
BEGIN
dbms_output.put_line([||demo.id||][||demo.value||]);
END;
/
36
Chapter 6
Lecture (Lec 8 & 9) for Week 5
6.1
Control Structure
6.1.1
Conditional statements
FROM STUDENTS
WHERE ID=X;
IF (CGPA >3.78) THEN
dbms_output.put_line(Brilliant);
ELSIF(CGPA between 3.5 and 3.78) THEN
dbms_output.put_line(Mid Level);
ELSE
dbms_output.put_line(Poor);
END IF;
END;
2. Simple CASE Statements. The simple CASE statement sets a selector that is
any PL/SQL datatype except a BLOB, BFILE, or composite type.
Example:
DECLARE
selector NUMBER := 1;
BEGIN
CASE selector
WHEN 0 THEN
dbms_output.put_line(Case 0!);
WHEN 1 THEN
dbms_output.put_line(Case 1!);
ELSE
dbms_output.put_line(No match!);
END CASE;
END;
/
ORDER BY name;
6.1.2
LOOP
1. LOOP and EXIT Statements Simple loops are explicit block structures. A
simple loop starts and ends with the LOOP reserved word. An EXIT statement or
an EXIT WHEN statement is required to break the loop.
Example: LOOP EXIT:
DECLARE
x number := 10;
BEGIN
LOOP
dbms_output.put_line(x);
x := x + 10;
IF x > 50 THEN
exit;
END IF;
END LOOP;
-- after exit, control resumes here
dbms_output.put_line(After Exit x is: || x);
END;
/
SQL> /
10
20
30
40
50
After Exit x is: 60
PL/SQL procedure successfully completed.
x := x + 10;
exit WHEN x > 50;
END LOOP;
-- after exit, control resumes here
dbms_output.put_line(After Exit x is: || x);
END;
/
2. FOR Loop. A FOR LOOP is a repetition control structure that allows you to
efficiently write a loop that needs to execute a specific number of times.
Syntax:
FOR counter IN initial_value .. final_value LOOP
sequence_of_statements;
END LOOP;
Few Points:
After the body of the for loop executes, the value of the counter variable is
increased or decreased.
The initial_value and final_value of the loop variable or counter can be
literals, variables, or expressions but must evaluate to numbers. Otherwise,
PL/SQL raises the predefined exception VALUE_ERROR.
The initial_value need not to be 1; however, the loop counter increment
(or decrement) must be 1.
PL/SQL allows determine the loop range dynamically at run time.
Example:
DECLARE
a number(2);
BEGIN
FOR a in 10 .. 20 LOOP
dbms_output.put_line(value of a: || a);
END LOOP;
END;
/
OUTPUT:
40
value
value
value
value
value
value
value
value
value
value
value
of
of
of
of
of
of
of
of
of
of
of
a:
a:
a:
a:
a:
a:
a:
a:
a:
a:
a:
10
11
12
13
14
15
16
17
18
19
20
Reverse FOR LOOP:By default, iteration proceeds from the initial value to the
final value, generally upward from the lower bound to the higher bound. You can
reverse this order by using the REVERSE keyword. In such case, iteration proceeds
the other way. After each iteration, the loop counter is decremented.
However, you must write the range bounds in ascending (not descending) order.
Example:
DECLARE
a number(2) ;
BEGIN
FOR a IN REVERSE 10 .. 20 LOOP
dbms_output.put_line(value of a: || a);
END LOOP;
END;
/
OUTPUT:
value
value
value
value
value
value
value
value
value
of
of
of
of
of
of
of
of
of
a:
a:
a:
a:
a:
a:
a:
a:
a:
20
19
18
17
16
15
14
13
12
41
value of a: 11
value of a: 10
PL/SQL procedure successfully completed.
Example:
DECLARE
a number(2) := 10;
BEGIN
WHILE a < 20 LOOP
dbms_output.put_line(value of a: || a);
a := a + 1;
END LOOP;
END;
/
OUTPUT:
value
value
value
value
value
value
value
value
value
value
of
of
of
of
of
of
of
of
of
of
a:
a:
a:
a:
a:
a:
a:
a:
a:
a:
10
11
12
13
14
15
16
17
18
19
42
Example:
DECLARE
a number(2) := 10;
BEGIN
WHILE a < 20 LOOP
dbms_output.put_line(value of a: || a);
a := a + 1;
END LOOP;
END;
/
43
Chapter 7
Lecture (Lec 10 & 11 for Week 6
7.1
Motivation for Functions and Procedures: Modular Code. Modularization is the process by which you break up large blocks of code into smaller pieces (modules) that can be
called by other modules. Modularization of code is analogous to normalization of data,
with many of the same benefits and a few additional advantages. With modularization,
your code becomes:
More reusable. By breaking up a large program or entire application into individual components that plug-and-play together, you will usually find that many
modules are used by more than one other program in your current application. Designed properly, these utility programs could even be of use in other applications!
More manageable. Which would you rather debug: a 1,000-line program or
five individual 200-line programs that call each other as needed? Our minds work
better when we can focus on smaller tasks. You can also test and debug on a perprogram scale (called unit testing) before individual modules are combined for a
more complicated integration test.
More readable. Modules have names, and names describe behavior. The more
you move or hide your code behind a programmatic interface, the easier it is to
read and understand what that program is doing. Modularization helps you focus
on the big picture rather than on the individual executable statements. You might
even end up with that most elusive kind of software: self-documenting code.
More reliable. The code you produce will have fewer errors. The errors you do
find will be easier to fix because they will be isolated within a module. In addition,
your code will be easier to maintain because there is less of it and it is more readable.
Forms of Modularization: PL/SQL offers the following structures that modularize
your code in different ways:
Procedure. A program that performs one or more actions and is called as an executable PL/SQL statement. You can pass information into and out of a procedure
through its parameter list.
44
Function. A program that returns data through its RETURN clause, and is used
just like a PL/SQL expression. You can pass information into a function through
its parameter list.
Database trigger. A set of commands that are triggered to execute (e.g., log in,
modify a row in a table, execute a DDL statement) when an event occurs in the
database.
Package. A named collection of procedures, functions, types, and variables. A
package is not really a module (its more of a meta-module), but it is so closely
related that.
7.1.1
45
[local declarations]
BEGIN
executable statements
[EXCEPTION
exception handlers]
RETURN STATEMENT;
END [name];
Common in Procedure and Function:
Has a name.
Can take parameters, and can return values.
Is stored in the data dictionary.
Can be called by many users.
Note: The term stored procedure is sometimes used generically for both stored procedures and stored functions. The only difference between procedures and functions is
that functions always return a single value to the caller, while procedures do not return
a value to the caller.
7.1.1.1
Parameter modes define the behavior of formal parameters. The three parameter modes,
IN (the default), OUT, and IN OUT, can be used with any subprogram. However,
avoid using the OUT and IN OUT modes with functions.
IN: The value of the actual parameter is passed into the procedure when the procedure is invoked. Inside the procedure, the formal parameter acts like a PL/SQL
constantit is considered read-only and cannot be changed.
OUT: Any value the actual parameter has when the procedure is called is ignored.
Inside the procedure, the formal parameter acts like an uninitialized PL/SQL variable and thus has a value of NULL. It can be read from and written to.
INOUT: This mode is a combination of IN and OUT.
Formal Parameters: When you declare a parameter, however, you must leave out
the constraining part of the declaration.
Datatype indicator. 1. Using the %TYPE Attribute 2. Using the %ROWTYPE Attribute
DECLARE
emprec
employees_temp%ROWTYPE;
id emp.id%TYPE;
BEGIN
emprec.empid := NULL; -- this works, null constraint is not inherited
46
Parameter Positions:
Positional Notation: You use positional notation to call the function as follows:
BEGIN
dbms_output.put_line(add_three_numbers(3,4,5));
END;
Named Notation: You call the function using named notation by:
BEGIN
dbms_output.put_line(add_three_numbers(c => 4,b => 5,c => 3));
END;
47
Mixed Notation: You call the function by a mix of both positional and named
notation by:
BEGIN
dbms_output.put_line(add_three_numbers(3,c => 4,b => 5));
END;
Note: There is a restriction on mixed notation. All positional notation actual parameters must occur first and in the same order as they are defined by the function
signature.
48
Chapter 8
Lecture (Lec 11 & 12 for Week 7
8.1
Cursor
(Source http://www.tutorialspoint.com/plsql/plsql_cursors.htm)
In response to any DML statement the database creates a memory area, known as
context area, for processing an SQL statement, which contains all information needed for
processing the statement, for example, number of rows processed, etc.
A cursor is a pointer to this context area. PL/SQL controls the context area through
a 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:
Implicit cursors.
Explicit cursors.
8.1.1
Implicit Cursor
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 the attributes like %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT.
49
%NOTFOUND
%ISOPEN
%ROWCOUNT
8.1.2
Explicit Cursors
Explicit cursors are programmer defined cursors for gaining more control over the context
area. An explicit cursor should be defined in the declaration section of the PL/SQL Block.
It is created on a SELECT Statement which returns one or more rows.
CURSOR cursor_name IS select_statement;
50
DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || || c_name || || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
CURSOR FOR Loop: The cursor FOR loop is an elegant and natural extension
of the numeric FOR loop in PL/SQL. With a numeric FOR loop, the body of the loop
executes once for every integer value between the low and high values specified in the
range. With a cursor FOR loop, the body of the loop is executed for each row returned
by the query.
Syntax
51
Example
Examples: End of the day in bank. Annual salary increment for each employee of
an organization.
52
Chapter 9
Lab Exercises
9.1
Done.
9.2
Lab for W3
1. Create one tablespace myspace and one user. And assign the tablespace to the new
user. Create a number of objects (4 tables: T1, T2, T3 and T4) and assign one
tables data (T4) to a different tablespace myspace2.
2. Remember the following definitions:
A subquery in the WHERE clause of a SELECT statement is also called a nested
subquery.
A subquery in the FROM clause of a SELECT statement is also called an inline
view.
Now create a number of related tables at your own choice and show the functionality
of a nested subquery and an inline view.
3. Show with suitable example the difference between Left and Right Outer joins.
You must create tables with relationship among them and insert relevant records
to demonstrate it. Also show how natural join works here.
53
9.3
54
9.4
55
9.5
2. Present an example to explain the working principal of DECODE and REGEXP SUBSTR.
57
9.6
Refer to the previous assignment for week 4. Complete the pending parts.
Additional Module:
Add the following module in your design:
58