Oracle Tutorial 11g by Naresh (1)
Oracle Tutorial 11g by Naresh (1)
Oracle_10g By Naresh A K
2
View In Oracle
Working with Index
Database Security
Working with Roles
Working with Synonyms
Working with CASE Expression
Analytic Functions
Introduction to PL/SQL
Block Structure Approach
Types of Block in PL/SQL
Handling Variables
PL/SQL Supports data types
Scope and Visibility of PL/SQL Identifiers
Variable Types in PL/SQL Programming
Control Structure in PL/SQL
Applying Composite Data types in PL/SQL
Cursor in PL/SQL
Use cursors to work with database data.
Working with Exception in PL/SQL
Write robust programs that handle runtime exceptions.
Function For Trapping Exception
Create PL/SQL stored procedures and functions.
Use program structure and control flow to design and write PL/SQL programs.
Use PL/SQL's datatypes for database and program data.
Use the packages supplied with Oracle.
Design and write your own packages.
Maintain and evolve your PL/SQL programs.
Create triggers on database tables.
Use PL/SQL's collection datatypes.
Use bulk operations for improved performance.
Oracle_10g By Naresh A K
3
Oracle_10g By Naresh A K
4
In Oracle 10g there are two types of initialization files namely the 'Server
Parameter file' (spfile) and 'The Parameter file' (pfile). The parameter files hold
Oracle_10g By Naresh A K
5
parameters that can set the sizes of the various buffers and pools of the SGA. You
can also specify the name of the instance, the name of the database and other
size-related parameters needed by the Oracle instance.
A typical parameter setting would be parameter_name = parameter_value
For e.g. DB_NAME=moviedb Here the name of the database is moviedb.
Memory Components of the SGA
The Oracle Instance is made up of the System Global area (SGA) and the
background processes. The SGA is made up of the
Redo Log Buffer
The Database Buffer cache
The Shared Pool
The Java Pool
The Large Pool
The Streams Pool
Redo Log Buffer – A circular buffer that stores all changes made in the database.
It contains are transferred periodically from memory to the online redo log files
on disk by the Log Writer (LGWR) background process. The contents of the redo
log buffer are
essential for instance recovery purposes. The size of the redo log buffer is
determined by the LOG_BUFFER initialization parameter.
The Database Buffer Cache – An area in memory that holds all the blocks read
in from disk for query or modification. Blocks that need to be modified, are
modified in memory and are written back to disk periodically. Modified blocks
that have not yet been written to disk are known as dirty blocks. This buffer is
managed in a manner that free blocks are always made available for new blocks
being read into memory. The contents of the database buffer cache are shared by
multiple user processes. The contents of the database buffer cache are written to
data files on disk by the Database Writer (DBWR) background process. The size
of the default database buffer cache is sized by the DB_CACHE_SIZE
Initialization parameter. The blocks that are part of the Database buffer cache are
sized by the DB_BLOCK_SIZE initialization parameter. This is the default
buffer cache.
The Shared Pool – The contents of this memory area are shared by multiple
Oracle_10g By Naresh A K
6
users and hence the name shared pool. Two specific caches form the shared pool.
The sizes of the two caches are not set individually and are automatically
determined by the Oracle Server. However it is possible to set the overall size of
the Shared pool by using the SHARED_POOL_SIZE initialization parameter.
Library Cache –It is responsible for storing and reusing frequently used SQL
Statements, their execution plans and stored procedures. This cache prevents SQL
Statements from being repeatedly parsed thus improving performance during
Execution of SQL statements. When a statement is executed, Oracle looks for an
Identical statement / execution plan in the library cache. If one is found it is
reused, if not a new parse tree and execution plan are created. The library cache
also holds frequently accessed PL/SQL blocks.
The Data Dictionary Cache – Sometimes referred to as the Row Cache. The
cache consists of blocks that hold data dictionary information read in from the
data files. Reads that are made to the data dictionary information in the datafiles
are also called recursive reads. Typical information stored in this cache is user
account information, table, index and other object definitions, privileges and
other relevant information that is frequently accessed. This cache is also managed
using the Least Recently Used
(LRU) Algorithm, which is on a first-in first-out basis.
The Large Pool – This is an optional pool. The size of this memory area is
determined by the LARGE_POOL_SIZE initialization parameter. It is used for
handling large I/O requests of server processes. Its main functions are to provide
memory for session memory (UGA) for the shared server environment, parallel
execution message buffers (when PARALLEL_AUTOMATIC_TUNING is set to
TRUE). It is also used by the Recovery Manager (RMAN) for its functioning
when the BACKUP_DISK_IO =n and BACKUP_TAPE_IO_SLAVE=TRUE
initialization parameters have been set. This pool does not use the LRU
algorithm.
The Java Pool – This memory area is used by all session-specific Java code and
data within the Java Virtual Machine (JVM). Its size is determined by the
JAVA_POOL_SIZE initialization parameter.
The Streams Pool – This memory area is used by the Oracle Streams Product for
its functioning.
Oracle_10g By Naresh A K
7
Datafiles – These files contain the data of the database. All objects created in the
database by users have their data physically stored in the datafiles. Datafiles
contain the data dictionary and user created data. In order to access the data that
is physically stored in the datafiles and reduce the overhead of disk I/O, blocks
from the datafiles are read into the database buffer cache in memory. Once they
are modified or are no longer needed they are written back to the datafiles.
Control Files – This is a very important file that is required for the Oracle
Database to function. If any one of the control files is unavailable the database is
shutdown. Hence it recommended that multiple copies of the control file are
maintained in the database on separate disks. The control file keeps a record of
the names, size and locations different physical files of the database. It also holds
other control information necessary to keep the database functioning. The
following is a list of the entries maintained in the control file.
Oracle_10g By Naresh A K
8
Redo Log Files – These files contain a record of all the changes made in the
database. These changes are referred to as redo entries. Redo entries can be used
to recover the database in the event of an instance failure. Instance failure can
occur when the contents of the SGA are lost such as in the event of a power
outage or an abnormal shutdown of the database. Any change made in the
database is first recorded in the online redo log buffer before it is actually
implemented. Hence even if modified blocks were not written in the event of an
instance failure, the changes can be recovered by using the online redo log files.
In Oracle 10g, a minimum of two redo logs should be available. These redo logs
files are known as redo groups.
Redo log groups are used in a circular fashion. Consider the figure. There are two
Disks DISK1 and DISK2. There are two redo log groups GROUP1 and
GROUP2.
GROUP1 has two members Rlog1 and Rlog1b. GROUP2 has two members
Rlog2a and Rlog2b. When the LGWR performs a write, it first writes
simultaneously to Rlog1a and Rlog1b. When the group becomes filled, it starts
Writing simultaneously to Rlog2a and Rlog2b. The contents of the members are
Identical. Now, if one of the disks is lost as a result of failure, the data is still
available in a member on another disk.
Oracle_10g By Naresh A K
9
v$<object>
1. V$database
2. V$session
3. v$tablespace
4. v$sql
5. v$instance
6. v$lock
7. v$locked_object
8. v$sga
9. v$datafile
10.v$controlfile
11.v$logfile
12.v$log
13.v$parameter
14.v$session_wait
Oracle_10g By Naresh A K
10
What is Normalization ?
What is De-Normalization ?
Meeting all the requirements of third normal form and it should not have
multi_valued deptndencies.
An entity is in Fifth Normal Form (5NF) if, and only if, it is in 4NF and every join dependency for the
Oracle_10g By Naresh A K
11
The Boyce-Codd Normal Form, also referred to as the "third and half (3.5) normal form", adds one
more requirement:
Meet all the requirements of the third normal form.
Every determinant must be a candidate key.
Oracle_10g By Naresh A K
12
SQL*PLUS
All commands of SQL are types at the SQL prompt which is called
TEMPorary Memory Location.
Only one SQL statement is managed in the SQL buffer.
The current SQL statement replaces the previous SQL statement in the buffer.
The SQL statement can be divided into different lines within the SQL buffer.
Only one line i.e. the current line can be active at a time in the SQL buffer.
At SQL prompt, editing is possible only in the current SQL buffer line by
using (ed).
Every statement of SQL should be terminated using (;) semicolon.
One SQL statement can contain only one (;) semicolon.
To run the previous or current SQL statement in the buffer type(/) at SQL
prompt.
Oracle_10g By Naresh A K
13
Tables can be created at any time, even when the users are using the database.
Size of the table need not be specified.
The structure of the table can be modified online.
The user should have permission on CREATE TABLE command and Storage
Area.
The table name should begin with a letter and can be 1-30 character long.
Name can contain
A-Z, a-z, 0-9,-,$ and #
Name cannot be duplicated for another object in the same oracle server.
Names connote be oracle SERVERS reserved words.
Names are not case sensitive.
DATATYPES IN ORACLE
Oracle_10g By Naresh A K
14
DATETIME DATATYPES
LARGE OBJECT DATATYPES
ROWID DATATYPES
CHARACTER DATATYPES
Oracle_10g By Naresh A K
15
Oracle_10g By Naresh A K
16
Oracle_10g By Naresh A K
17
CHAR
NCHAR DATATYPE
It is first time defined in oracle 9i, and contains Unicode data only.
The column's maximum length is determined by the national character set
definition.
The maximum size allowed in 2000 Bytes, and size has to be specified.
If the data is shorter than the actual size then the blank pads are applied.
VARCHAR2 DATATYPE
NVARCHAR2 DATATYPE
NUMBER DTATATYPE
It stores zero, positive and negative fixed and floating point numbers.
The range of magnitude is
1.0*10-130 to 9.9.…9*10-125
The general declaration is Number(P,S)
P It specifies the precision ie the total number of digits (1 to 38)
S It specifies the scale ie the number of digits to the right of the decimal
point, it can range from -84 to 127
Oracle_10g By Naresh A K
18
FLOAT DATATYPE
It specifies to have decimal point any Where from the first to the last digit or
can have no decimal point at all.
The Scale values is not applicable to floating point numbers, as the number of
digits that can appear after the decimal point is not restricted.
FLOAT It specifies a floating point numbers with decimal precision 38
or binary precision of 126
FLOAT(b) It specifies a floating point number with binary precision b
The precision can range from 1 to 126
To convert from binary to decimal precision multiply 'b' by 0.30103
To convert from decimal to binary precision multiply the decimal
precision by 3.32193
The maximum of 126 digits of binary precision is roughly equivalent to 38
digits of decimal precision.
LONG DATATYPES
Oracle_10g By Naresh A K
19
TIMESTAMP DATATYPE
RAW and LONG RAW data types are intended for storage of binary data or
byte strings.
RAW and LONG RAW are variable length data types.
They are mostly used to store graphics, sounds, documents etc.
The oracle converts the RAW and LONG RAW data into hexadecimal form.
Each hexadecimal character represents four bits of RAW data.
Oracle_10g By Naresh A K
20
BFILE DATATYPE
It enables access to binary file LOB's which are stored in the file systems
outside oracle.
A BFILE column or the attributes stores the BFILE locator.
The BFILE locator maintains the directory alias and the filEname.
The binary file LOB's do not participate in transactions and are not
recoverable.
The maximum size is 4 Gb.
BLOB DATATYPE
CLOB DATATYPE
NCLOB DATATYPE
Eg:
Oracle_10g By Naresh A K
21
INSERT STATEMENT
Eg:
Oracle_10g By Naresh A K
22
In this case the values should be provided to all the columns that exist inside
the table.
The order in which the values are declared in the values clause should follow
the same order as that of the original table order.
The Char, Varchar2 and Date type data should be declared in single quotes.
In this case the order of the columns declared in the INSERT list need not be
of the same order as that of the original table.
The data values in the VALUES clause should match with that of INSERT list.
The columns for which the data is not supplied are filled with NULL values.
If the columns that were not supplied with data are declared with NOT NULL
constraint then the INSERT statement is rejected.
Oracle_10g By Naresh A K
23
Sysdate FUNCTION
USER FUNCTION
SUBSTITUTION VARIABLES
Oracle_10g By Naresh A K
24
The list file is used to save all information which performed in SQL *PLUS.
1.in SQL *PLUS
NAVIGATION: 2.FILE-SpoolSpool File
3.give the file name
4.performed all tasks.
5.now spool off.
The SAVE command is used to store the current contents of the SQL buffer.
At SQL prompt type the full name of the path where the file has to be created.
Give the name of the file with (.SQL) extension.
If the file has to be replaced with the same existing name then use REPLACE
ALL clause.
Eg:
SQL>SAVE c:\scripts\insert_statement.SQL
TO GET SCRIPT:
Get used to display the script file.
Sal>get E:\nitdir\ins
TO RUN SCRIPT:
Oracle_10g By Naresh A K
25
SQL>RUN c:\scripts\insert_statement.SQL
SQL>@ c:\scripts\insert_statement.SQL
Query: It is an operation that retrieves data form one or more tables or Views.
Select: The Select statement is used to retrieve data from one or more tables,
Views object Views or Materialized Views.
The user must have the Select privilege on the specified object.
The Select ANY TABLE allows selecting the data from any recognized object.
Oracle_10g By Naresh A K
26
PRE REQUISITES:
Syntax:
Example:
Sql>update emp set deptno=(select deptno from emp where empno=7788) where
job =(select job from emp whee empno=7788);
Use sub queries in update statements to update rows in a table based on values
from another table.
Oracle_10g By Naresh A K
27
It is used to update a value in a column with default value set in the constriants.
RETURNING CLAUSE:
Restriction:
DELETE STATEMENT:
PRE REQUISTIES:
To delete rows from a table, the table must be in the users’ schema.
Delete any table system privilege allows to delete rows from any table or table
partition or from the base table of any view.
Oracle_10g By Naresh A K
28
MULTIPLE INSERTS:
CONDITONAL INSERT:
Oracle_10g By Naresh A K
29
Every data change made during the transaction is tEMPorary until the
transaction is committed.
Data manipulation operations primarily affects state of the data can be
Oracle_10g By Naresh A K
30
recovered.
The current user can review the result of the data manipulation operation by
querying the tables.
Other users cannot view the result of the data manipulation operations made
by the current user.
The Alter table statement is used to change the table’s structural definition.
The Alter table statement is used to :
ADD a new column.
MODIFY an existing column.
Define a default value for new column.
Oracle_10g By Naresh A K
31
Modifying a Column:
Dropping a Column:
A column can be dropped from a table by using the alter table statement.
The Drop column clause is used for this purpose and the feature is enabled for
Oracle 8i onwards.
Oracle_10g By Naresh A K
32
The Set Unused Option marks one or more columns as unused such that they
can be dropped when the damage on system resources is less (8i)
The response time is faster than the Drop clause.
Unused columns are treated as if the were dropped, even though their column
data remains in the table rows.
After a column has been marked unused, we cannot have access to that
column.
The names and types of columns marked unused will not be displayed during
a Describe.
We can add to a table a new column with the same name as an unused
column.
SQL > Create table sampe1 (id number, name varchar2 (23));
SQL > Alter table EMP set UNUSED (Ename);
SQL > DESC EMP;
This option removes from the table all columns currently marked as unused.
The option is used when we want to reclaim the extra disk space from unused
columns in the able.
If the table does not contain unused columns the statement return with no
errors.
Dropping a Table:
Oracle_10g By Naresh A K
33
SQL > RENAME < old name > TO < new name >;
TRUNCATING A TABLE:
It is used it remove all rows from a table and to release the storage space use
by the specific table.
The truncate table will not facilitate for rollback.
Oracle_10g By Naresh A K
34
*ALL_COL_COMMENTS
*ALL_TAB_COMMENTS
*USER_COL_COMMENTS
*USER_TAB_COMMENTS
SYNTAX:
SQL> COMMENTS ON table<table name>/column<tablename.column>
is’text’;
Ex:
Sql> COMMENT ON table EMP IS ‘the table storing employee information’;
SYNTAX:
SQL>CREATE table<table name>as select columns from table
name[wherecondition];
SQL>CREATE table temp1 (ecode, name, basic, deptno) as select emno, ename,
sal, deptno from EMP;
Oracle_10g By Naresh A K
35
The default justification of the data after it is retrieved from the table is
LEFT Date and Character data.
Right Numeric Data.
The default display of the data is always in Upper casing.
The character and date columns heading can be truncated, but number heading
cannot be truncated.
Arithmetic Operators
Oracle_10g By Naresh A K
36
Operator precedence
Multiplication and Division take priority over addition and subtraction (*,/,
+,-)
Operators of the same priority are evaluated from left to right
To prioritize evaluation and to increase clarity parenthesis can be
implemented.
Oracle_10g By Naresh A K
37
NVL Function
The NVL function is used to convert a NULL values to an actual values.
SQL >Select Empno num, Ename name, Sal “Basic Salary”, Job Designation
from EMP;
SQL >Select Deptno AS “Department ID”, Dname AS “Department Name”, loc
AS place from Dept;
SQL >Select hiSal “Maximum Range”, LoSal “Minimum Range”, grade from
Salgrade;
Oracle_10g By Naresh A K
38
Literals In Oracle
Literal and Constant values are synonyms to one another and refer to a fixed
data value.
The types of literals recognized by oracle are:
Text Literals
Integer Literals
Numbers Literals
Interval Literals
Text Literals
It specifies a text or character literal.
It is used to specify values whenever 'text' or Char appear in
Expressions, Conditions, SQL Functions and SQL Statements.
It should be enclosed in single quotes.
They have properties of both Char and Varchar2 data types.
A test literal can have a maximum length of 4000 bytes.
Oracle_10g By Naresh A K
39
Filtering of Records
The numbers of rows returned by a query can be limited using the Where
clause.
A Where clause contains a condition that must be met and should directly
follow the “from” clause.
Oracle_10g By Naresh A K
40
Eg:
Where Deptno=10;
Where Hiredate='03-jan-99'
Where Job='MANAGER'
There is no such rule that, the values being compared should be supplied
explicitly.
Logical Operators
Oracle_10g By Naresh A K
41
OR
NOT
AND
It returns true if both or all component condition are true.
It return false if either is False, else returns Unknown.
Truth Table.
Oracle_10g By Naresh A K
42
S
E
N NUL FALS NUL
U L E L
L
L
SQL >Select Ename, Sal, Job from EMP Where Sal>1400 and Sal<=4000;
SQL >Select Ename, Sal, Job from EMP Where (Sal>=1500 and Sal <=5000)
AND Job='MANAGER';
OR Operator
It returns True if either component condition is True.
It return false if both are False, else return Unknown.
Truth Table.
Oracle_10g By Naresh A K
43
S
E
N TRU NUL NUL
U E L L
L
L
SQL >Select Empno, Ename, Job, Sal from EMP Where Sal>=110 OR
Job='CLERK';
SQL >Select Empno, Ename, Job, Deptno from EMP Where Deptno=10 OR
Deptno=20;
SQL >Select Empno, Ename, Job from EMP Where (Sal <=2500 or Sal>=5000)
OR Job='MANAGER';
NOT Operator
Truth Table.
Oracle_10g By Naresh A K
44
L
S
E
SQL > Select Ename, Sal , Job from EMP Where not Job= 'MANAGER';
SQL > Select Ename, Sal, Job from EMP Where NOT Sal >5000;
SQL > Select Ename, Job, Sal, Deptno from EMP Where NOT
(Job='SalESMAN' AND Deptno=30);
SQL > Select Empno, Ename, Job, Sal from EMP Where (Sal>=1120 OR Job
='CLERK') AND Deptno=30;
SQL > Select Empno, Ename, Job, Sal from EMP Where (Sal >=1100 AND
Job='CLERK') OR Deptno=20;
Rules of Precedence
The default precedence order is
ALL comparison operators.
NOT operator
AND operator
OR operator
The precedence can be controlled using parenthesis.
Oracle_10g By Naresh A K
45
SQL > Select Empno, Ename, Sal, Job from EMP Where Sal BETWEEN 1999
AND 3000;
SQL > Select Empno, Ename, Job from EMP Where Sal NOT BETWEEN 1000
AND 2500;
SQL > Select Empno, Ename, Hiredate from EMP Where Hiredate BETWEEN '
12-JAN-81' AND '28-FEB-84';
SQL > Select Empno, Ename, Hiredate from EMP Where Hiredate BETWEEN '
12-JAN-81' AND '28-FEB-84';
SQL > Select Empno, Ename, Job from EMP Where Ename NOT IN
('FORD','ALLEN');
SQL > Select Empno, Ename, Deptno from EMP Where Deptno in (10,20,30);
SQL > Select Empno, Ename, Hiredate from EMP Where Hiredate IN ('20-FEB-
81','09-jan-81');
SQL > Select Empno, Ename, Comm from EMP Where Comm is NULL;
SQL > Select Empno, Ename, Comm from EMP Where Comm is NOT NULL;
Oracle_10g By Naresh A K
46
SQL > Select Empno, Ename, Job from EMP Where Ename LIKE 'S%';
SQL > Select Empno, Ename, Job from EMP Where Ename NOT LIKE 'S%';
SQL > Select Empno, Ename, Job from EMP Where Ename LIKE '_A%';
SQL > create table sample (name varchar2 (10), phone varchar2 (10));
SQL > insert into sample values ('naresh_ak','99:000:888');
SQL > Select Name, Phone from sample Where name LIKE '%\_%' ESCAPE '\';
Ordering Information
Oracle_10g By Naresh A K
47
SQL > Select Empno, Ename, Job, Deptno, Hiredate from EMP ORDER BY
Hiredate;
SQL > Select Empno, Ename, Job, Deptno, Hiredate from EMP ORDER BY
Hiredate DESC;
SQL > Select Empno, Ename, Job from EMP ORDER BY Deptno, Sal, Hiredate;
Oracle_10g By Naresh A K
48
These functions manipulate groups of rows to give one result per group of
rows.
CHARACTER FUNCTION
Accept character input and can return both character and number values.
NUMBER
Accept numeric input and return numeric values.
DATE
Operate on values of date data type, can return both date and number.
CONVERSION
Convert a value from one data type to another.
GENERAL
NVL and DECODE
DECODE
Operates on any data type and can return any data type.
Lower Function
They are functions that return character values unless stated.
They return the data type VARCHAR2. Limited to a length of 4000 Bytes.
Oracle_10g By Naresh A K
49
UPPER Function
It converts the alpha character values to upper case.
The return value has the same data type as the argument char.
SQL > Select UPPER (' welcome to world of computing') from DUAL;
SQL > Select Empno, Ename, UPPER (Ename) from EMP Where Job='CLERK';
SQL > Select Empno, Ename from EMP Where UPPER (Job)='MANAGER';
SQL > Select Empno, Ename from EMP Where Job IN ('MANAGER', upper
('clerk')) ;
INITCAP function
It converts the alpha characters values to uppercase for the first letter of each
word, keeping all other letters in lower case.
Words are delimited by white spaces of characters that are not alphanumeric.
Oracle_10g By Naresh A K
50
SQL > Select INITCAP (' welcome to world of computing') from DUAL;
SQL > Select Empno, Ename, INITCAP (Ename) from EMP Where
Job='CLERK';
CONCAT Function
It concatenates the first character values to the second character value. Only
two parameters accepted.
It return the character data type.
SQL > Select CONCAT (' welcome to world',' of computing') from DUAL;
SQL > Select Empno, Ename, CONCAT (Ename, Job) from EMP Where
Job='CLERK';
SQL > Select Sal, Deptno, CONCAT (CONCAT (INITCAP (Ename),'is a '), Job)
Jobs from EMP Where Deptno in (30, 40);
Oracle_10g By Naresh A K
51
SQL > Select Ename, Job from EMP Where SUBSTR (Job, 4,3)=UPPER('AGE');
Note: if you add and extras '-' at the end of the regular expression, you get the
trailing '-' as part of the returned string.
SQL >Select regexp_substr ('My Ledger: Debits, Credits, and Invoices 1940',
'[: punct :] [^,]+') from dual;
Select regexp_substr ('My Ledger Debits Credits, :and Invoices 1940',
'[: punct:] [^,]+') from dual;
We can use the match parameter variable to further customize the search. Match
parameter is a text literal that lets you change the default matching behaviour of
the function. Its possible values are as follow:
SQL > Select regexp_substr ('My Ledger: Debits, Credits, and Invoices
1940','My',1,1,'c') from dual;
SQL > Select regexp_substr ('My Ledger: Debits, Credits, and Invoices
1940','My',1,1,'i') from dual;
LENGTH Function
Oracle_10g By Naresh A K
52
If the char has data type CHAR , the length includes all trailing blanks.
If the char is NULL , it returns NULL.
INSTR FUNCTION
Searches for column/expression beginning with its nth character for the mth
occurrence of char2, and returns the position of the character in char1, that is
the first character of this occurrence.
N can be positive or negative, if negative searches' backward from the end of
column/expression.
The value of m should be positive otherwise it will give an error “out of
range”
The default values of both m and n are 1
The return values are relative to the beginning of char1 regardless of the value
of n, and is expressed in characters.
If the search is unsuccessful, the return value is zero.
SQL > Select Job, INSTR (Job,'A',3,2) from EMP Where Job='MANAGER';
SQL > Select Job, INSTR (Job,'A',2) from EMP Where Job='MANAGER';
Oracle_10g By Naresh A K
53
Used to specify a matching list where you are trying to match any one of the
[]
characters in the list.
Used to specify a nonmatching list where you are trying to match any
[^ ]
character except for the ones in the list.
Oracle_10g By Naresh A K
54
Value Description
[..] Matches one collation element that can be more than one character.
Oracle_10g By Naresh A K
55
Value Description
{n,m}? Matches the preceding pattern at least n times, but not more than m times.
LPAD Function
Pads the character value right justified to a total width of a character positions.
The default padding character is space.
RPAD Function
Pads the character value left justified to a total width of an character positions.
The default padding character is space.
Oracle_10g By Naresh A K
56
LTRIM Function
RTRIM Function
Oracle_10g By Naresh A K
57
CHR Function
ASCII Function
It returns the decimal representation in the character database set of the first
character of the char.
Oracle_10g By Naresh A K
58
NUMBER Function
ROUND Function
REPLACE Function
Oracle_10g By Naresh A K
59
TRANSLATE Function
It returns a char with all occurrences of each character in from replaced by its
corresponding character in to.
Characters in char that are not in from are not replaced.
The argument from can contain more characters than to .
If the extra characters appear in char, they are removed from the return value.
SQL > Select Job, TRANSLATE (Job, 'p','') from EMP Where
Job='PRESIDENT';
SQL > , Where Job='PRESIDENT';
SQL > Select Job, TRANSLATE (Job, 'A','O') from EMP Where
Job='PRESIDENT';
TRUNCATE Function
Oracle_10g By Naresh A K
60
MODULUS Function
POWER Function
SQUARE Function
Syntax: SQUARE (n);
It returns square root of N.
The value of N cannot be negative.
SQRT returns a real result.
DATE FUNCTION
Oracle_10g By Naresh A K
61
Sysdate
It is a date function that returns current date and time.
Sysdate is generally Selected upon a dummy table.
DATE ARITHMETIC
As database stores dates as numbers, Arithmetic operations can be
implemented.
Number constants can be added or subtracted upon dates.
The operations that can be applies are:
1. Date + Number Add number of days to a date
2. Date - Number Subtracts number of days from a date.
3. Date - Number Subtract one date from another.
4. Date + Number /24 Add number of hours to a date.
Note: the date arithmetic can't be implemented upon dates which are declare
directly in the Select list even-though declare in the original format until and
unless it is not converted to a proper date using proper conversion function.
DATE FUNCTION
ADD_MONTHS Function
Oracle_10g By Naresh A K
62
MONTHS_BETWEEN Function
NEXT_DAY Function
LAST_DAY Function
Oracle_10g By Naresh A K
63
Mostly used to determine how many days are left in the current month.
ROUNDING of Dates
TRUNCATING Dates
SQL > Select ROUND (Sysdate, 'DAY') ,TRUNC(Sysdate, 'DAY') from dual;
SQL > Select ROUND (Sysdate, 'MON') ,TRUNC(Sysdate, 'MONTH') from
dual;
SQL > Select ROUND (Sysdate, 'DAY') ,TRUNC(Sysdate, ‘year’) from dual;
CONVERSION Function
The conversion functions convert a value from one data type to another.
The data type conversion in oracle is of two types:
Oracle_10g By Naresh A K
64
IN ASSIGNMENTS
VARCHAR2/CHAR NUMBER
VARCHAR2/CHAR DATE
NUMBER VARCHAR2
DATE VARCHAR2
IN EXPRESSIONS
VARCHAR2/CHAR NUMBER
VARCHAR2/CHAR DATE
Oracle_10g By Naresh A K
65
Converts Date of Date data type to a value of VARCHAR2 data type in the
format specified.
Format is the optional date format that can be used.
The 'nlsparams' specifies the language in which month and day names and
abbreviation are returned.
FORMAT MODELS
D(.)99D99
It return the specified position of the decimal character.
The default decimal delimiter is a period(.).
Only one decimal character can be specified in a number format mode.
G(,)99G99
Returns the specified position of the group separator.
Multiple group separators can be specified.
L L99
Returns the specified position of the local currency symbol.
Oracle_10g By Naresh A K
66
MI 99999MI
Returns negative value with a trailing minus sign (-).
Returns position value with a trailing blank.
MI format should be declared as trailing argument only.
PR 9999PR
Returns negative value in < angle brackets>
It can appear only as trailing declaration.
S S9999
Returns negative value with a leading minus sign.
Returns positive value with a leading pllus sign.
9999S
Returns negative values with a trailing minus sign.
Returns positive value with a trailing plus sign.
S can appear as first or last value.
Oracle_10g By Naresh A K
67
(,)Comma 9,999
Returns a comma in the specified position.
Multiple commas can be specified.
$ 9999
Return values with a leading Dollar Sign.
C Cyyy
Returns specified position of the ISO currency symbol.
The date format models can be used in the TO_CHAR function to translate a
Oracle_10g By Naresh A K
68
AD or A.D./BC or B.C.
Indicates AD/BC with or without periods.
AM or A.M. / PM or P.M.
It indicates meridian indicator with or without periods.
SQL > Select TO_CHAR (Sysdate,' A.M.'), TO_CHAR (Sysdate, 'PM') from
dual;
SQL > Select Sal, Hiredate, TO_CHAR (Hiredate,' AM') from EMP;
Oracle_10g By Naresh A K
69
SQL > Select Sal, Hiredate, TO_CHAR (Hiredate,' DD-DAY') from EMP
Where TO_CHAR (Hiredate, 'DD-DAY')='03-WEDNESDAY';
SQL > Select Sal, Hiredate, TO_CHAR (Hiredate,' D-DY-DAY') from EMP;
IW Specifies the week of the year (1-51 or 1-53) based on the ISO standard.
SQL > Select Sal, Hiredate, TO_CHAR (Hiredate,' IW') from EMP;
SQL > Select Sal, Hiredate, TO_CHAR (Hiredate,' YEAR') from EMP;
W Specifies the week of the month (1-5) week starts on the first day for the
month and ends on the seventh.
SQL > Select Sal, Hiredate, TO_CHAR (Hiredate,' W') from EMP ;
WW Specifies the week of the year (1-53) , week 1 start on the first day of the
year and continues to the seventh day of the year.
SQL > Select Sal, Hiredate, TO_CHAR (Hiredate,' WW') from EMP ;
Oracle_10g By Naresh A K
70
SQL > Select Sal, Hiredate, TO_CHAR (Hiredate,' Q') from EMP
Where TO_CHAR (Hiredate, 'Q')=5;
HH/HH12 Return the hour of the day in twelve hour clock mod.
SQL > Select Sal, Hiredate, TO_CHAR (Hiredate,' hh'), TO_CHAR (Hiredate,'
HH12:am') from EMP ;
HH24 Returns the hour of the day in twenty four hour chock mode (0-23)
SQL > Select Sal, Hiredate, TO_CHAR (Hiredate,' HH24') from EMP;
SQL >
SQL > Select Sysdate, TO_CHAR (Sysdate,' HH: MI’) from dual ;
Oracle_10g By Naresh A K
71
SP Spell numbers
SQL > Select Sysdate, TO_CHAR (Sysdate,' DDSP: MONTH: YYYY’) from
dual ;
SQL > Select Sysdate, TO_CHAR (Sysdate,' DDSPTH: MONTH: YYYY’) from
dual;
SQL > Select Sysdate, TO_CHAR (Sysdate,' DDSPTH: MONTH: YYYYSP’)
from dual;
TO_NUMBER Function
TO_DATE Function
Oracle_10g By Naresh A K
72
SQL>select months_between(to_date(’02-02-1995’,’mm-dd-yyyy’),to_date(’02-
02-1995’,’mm-dd-yyyy’))months from dual;
Oracle_10g By Naresh A K
73
Oracle_10g By Naresh A K
74
The data types for arguments may be char, varchar2, number or date.
poAll group functions except count (*) ignore NULL values, to substitute a
value for NULL values use the NVL function.
When a group function is declared in a Select list, no single row columns
should be declared.
When a group function is declared in a Select list, other columns can be
declared, but they should be grouped columns and all the no functional
columns should be declared into a GROUP BY clause.
AVERAGE FUNCTION
SQL > Select AVG (Sal), AVG (distinct Sal) from EMP;
SQL > Select AVG (comm), AVG (distinct comm) from EMP;
SUM FUNCTION
SQL > Select SUM (Sal), SUM (distinct Sal) from EMP;
SQL > Select SUM (comm), SUM (distinct comm) from EMP;
MAXIMUM FUNCTION
SQL > Select MAX (Sal), MAX (distinct Sal) from EMP;
SQL > Select MAX (comm), MAX (distinct comm) from EMP;
MINIMUM FUNCTION
Oracle_10g By Naresh A K
75
SQL > Select MIN (Sal), MIN (distinct Sal) from EMP;
SQL > Select MIN (comm), MIN (distinct comm) from EMP;
COUNT FUNCTION
All group function except count (*) ignore null values in column.
Using NVL function forces group functions to include NULL values.
SQL > Select AVG (comm), AVG (NVL (comm,0)) from EMP;
Oracle_10g By Naresh A K
76
The above specification falls under the principle of groups within groups.
SQL > Select Deptno, SUM (Sal), AVG (Sal) from EMP Where Job='CLERK'
GROUP BY Deptno;
HAVING CLAUSE
It is used to specify which group has to display.
SQL > Select Deptno, SUM (Sal), AVG (Sal) from EMP GROUP BY
Deptno HAVING max (Sal)>=2900;
SQL > Select Deptno, SUM (Sal), AVG (Sal) ,MAX(Sal),MIN(Sal) from EMP
GROUP BY Deptno HAVING count (*)>=2;
Oracle_10g By Naresh A K
77
The GROUP BY clause can be used in a SELECT statement to collect data across
multiple records and group the results by one or more columns.
The syntax for the GROUP BY clause is:
SELECT column1, column2, ... column_n, aggregate_function (expression)
FROM tables
WHERE predicates
GROUP BY column1, column2, ... column_n;
aggregate_function can be a function such as SUM, COUNT, MIN, or MAX.
Oracle_10g By Naresh A K
78
The HAVING clause is used in combination with the GROUP BY clause. It can
be used in a SELECT statement to filter the records that a GROUP BY returns.
The syntax for the HAVING clause is:
SELECT column1, column2, ... column_n, aggregate_function (expression)
FROM tables
WHERE predicates
GROUP BY column1, column2, ... column_n
HAVING condition1 ... condition_n;
aggregate_function can be a function such as SUM, COUNT, MIN, or MAX.
Oracle_10g By Naresh A K
79
Oracle_10g By Naresh A K
80
SQL > Select MAX (SUM (Sal)) from EMP GROUP BY Deptno;
SQL > Select MIN (SUM (Sal)) from EMP GROUP BY Deptno;
SQL > Select AVG (MIN (SUM (Sal))) from EMP GROUP BY Deptno;
Miscellaneous Functions.
GREATEST FUCTION.
Syntax: GREATEST (Exp1, Exp2...);
Oracle_10g By Naresh A K
81
LEAST FUNCTION
USER FUNCTION
Syntax: USER
It returns the current oracle user with the VARCHAR2 data type.
The function cannot be used in the condition of a CHECK constraint.
UID FUNCTION
Syntax: UID
It returns an integer that uniquely identifies the current USER.
Oracle_10g By Naresh A K
82
USERENV FUNCTION
Syntax: USERENV
It returns information of VARCHAR2 data type above the current session.
SOUNDEX FUNCTION
NVL2:
NVL2(x, value1, value2): Returns value1 if x is not null; if x is null, value2 is
returned
select comm, NVL2(comm,40,50) from emp;
NULLIF:
NULLIF() compares two expressions. If they are equal, it returns NULL.
Otherwise, it returns the first expression.
Oracle_10g By Naresh A K
83
DATA INTEGRITY
It is a state in which all the data values stored in the database are correct.
Enforcing data integrity ensures the quality of the data in the database.
ENTITY INTEGRITY
It defines a row as UNIQUE entity for particular table.
Entity integrity enforces the integrity of the identifies columns, or the
PRIMARY KEY of a table.
DOMAIN INTEGRITY
Domain integrity validates the entries for a given column.
It can enforced through:
Restricting type (data type).
By format (CHECK constraint).
By range of possible values (Foreign Key, Check, Default, Not Null).
REFERENTIAL INTEGRITY
It preserves the defined relationships between tables when record are entered
Oracle_10g By Naresh A K
84
or deleted.
It ensure that Key values are consistent across table.
When referential integrity is enforced, it prevents from.
Adding records to a related table if there is no associated records in the
primary table.
Changing values in a primary table that result in orphaned records in a
related table.
Deleting records from a primary table if there are matching related records.
CONSTRAINTS
Constraints are used to define an integrity constraint, as rule that restricts the
values in a database.
As per oracle there are Six types of constraints:
1. NOT NULL
2. UNIQUE
3. PRIMARY KEY
4. FOREGIN KEY/REF
5. CHECK
Oracle_10g By Naresh A K
85
EXCEPTIONS:
NOT NULL constraints are supported for a column or attribute whose type
is user-defined object VARRAY, LOB
RESTRICTIONS:
NULL or NOT NULL cannot be specified in a view constraint.
NULL or NOT NULL cannot be specified for an attribute of an object.
UNIQUE CONSTRAINT
Oracle_10g By Naresh A K
86
RESTRICTIONS
A table or View can have only one UNIQUE key.
UNIQUE key cannot be implemented on columns having.
LOB,LONG,LONG RAW,VARRAY,NESTED
TABLE,OBJECT,BFILE,TIMESTAMP WITH TIME ZONE
If it is a local time then we can create UNIQUE key.
A composite UNIQUE key cannot have more than 32 columns.
Same column or combination of columns cannot be designated as both
PRIMARY key and UNIQUE key.
userThe UNIQUE key can be specified only for the top level (root) table or
view.
Oracle_10g By Naresh A K
87
RESTRICTIONS
Oracle_10g By Naresh A K
88
PRIMARY key can be specified only for the top level (root) table or view.
NOTE: One column can contain much number of constraints, but the column
should contain different constraints.
Oracle_10g By Naresh A K
89
RESTRICTIONS
The FOREIGN key columns cannot be applied on
LOB,LONG,LONG RAW,VARRAY,NESTED
TABLE,OBJECT,BFILE,TIMESTAMP WITH TIME ZONE
The REFERNCED Unique/Primary key constraint on the parent table or view
must already be deleted.
A composite foreign key cannot have more than 32 columns.
The child and Parent table must be on the same database.
To enable referential integrity across nodes of a distributed database data base
TRIGGER are used.
REFERENCES CLAUSE
The references clause should be used when the foreign key constraint is
Inline.
When the constraint is out of line, we must specify the foreign key , key
words.
Oracle_10g By Naresh A K
90
(HOSPITAL_ID));
ONDELETE CLAUSE
EXAMPLE:1
Oracle_10g By Naresh A K
91
EXAMPLE:2
SQL > insert into department select * from Dept Where Deptno in (10,20);
SQL > insert into employee select * from emp Where Deptno in (10,20);
CHECK CONSTRAINT
It defines a condition that each row must satisfy.
To satisfy the constraint, each row in the table must make the condition either
Oracle_10g By Naresh A K
92
True or Unknown.
Oracle does not verify that CHECK conditions are not mutually exclusive.
RESTRICTIONS
The condition of a CHECK constraint can refer to any column in the table ,
but it cannot refer to columns of other tables.
The constructs that cannot be included are .
Queries to refer to values in other rows.
Calls to functions Sysdate, UID,USER,USERENV
The pseudo columns CURVAL,NEXTVAL,LEVEL or ROWNUM.
Date constants that are not fully specified
A single column can have multiple CHECK constraint that reference the
columns in the definition.
There is no limit to the number of CHECK constraints that can be defined on
a column.
The CHECK constraints can be defined at the column level or table level.
Oracle_10g By Naresh A K
93
Syntax:
Oracle_10g By Naresh A K
94
GUIDELINES
DROPPING CONSTRAINTS
Oracle_10g By Naresh A K
95
DISABLING CONSTRAINTS
GUIDELINES
The DISABLE clause can be used both in create table and the alter table
statement.
The CASCADE caluse disables dependent integrity constraints.
ENABLING CONSTAINT
The constraints can be enabled without dropping it or re-creating it.
The ALTER TABLE statement with the ENABLE clause.
GUIDELINES
VIWING CONSTRAINT.
To view all constraints on a table by querying the USER_CONSTRAINTS
data dictionary view.
The codes that are reveled are:
C CHECK
P PRIMARY KEY
R REFERENTIAL INTEGRITY
U UNIQUE KEY
Oracle_10g By Naresh A K
96
The names of the columns that are involved in constraint can be known by
quering the USER_CONS_COLUMNS data dictionary view.
*****************************************************************
**************************
JOINS
A join is a query that combines rows from two or more tables, view or
materialized view.
A join is performed whenever multiple tables appear in the queries FROM
clause.
The query Select list can Select any columns from any of these tables.
The common columns names within the tables should qualify all references to
these columns.
Join Condition
Many join queries contain Where clause, which compares two columns,
each from a different table.
The applied condition is called a join condition.
To execute a join.
Oracle combines pairs of rows, each containing one row from each table,
for which the join condition evaluates to True.
Oracle_10g By Naresh A K
97
The columns in the join condition need not be part of the Select list.
The Where clause of a join query can also contain other condition that
refer to columns of only one table.
To execute a join of three or more tables.
Oracle first joins two of the tables based on the join condition comparing
these columns and then join's the result to another.
The oracle OPTIMIZER determines the order in which oracle join tables
based on the:
Join condition
INDEXES on tables.
STATISTICS for the tables.
The LOB columns cannot be specified in the Where clause, when the Where
clause contains any joins.
GUIDELINES
When writing a Select statement that join's table, precede the column name
with the table name for clarity and to enhance database access I.e
(EMP.Deptno).
If the same column name appears in more than one table, the column name
must be prefixed with the table name.
To join N tables together, we need a minimum of n-1 join condition.
Oracle_10g By Naresh A K
98
The names of the column names should be qualified in the Where clause, with
the table name to avoid ambiguity.
If there are no common columns names between the two tables, the
qualification is not necessary.
GUIDELINES
A table alias can be up to 30 characters in length.
If a table alias is used from a particular table name in the from clause, then
that table alias must be substituted for the table name through out the Select
statement.
A table alias should be meaning full.
A table alias is valid only for the current Select statement.
Self Joins
It is a join of a table to itself.
The same table appears twice in the from clause and is followed by table
aliases.
The table aliases must qualify the column names in the join condition.
Oracle_10g By Naresh A K
99
To perform a self join, oracle combines and returns rows of the table that
satisfy the join condition.
SQL >Select E1.Ename ||'''s Manager is '|| ' '||E2.Ename “Employees and
Managers “
From EMP E1, EMP E2 Where E1.mgr=E2.Empno;
Cartesian Products
SQL > Select Ename, Job, Dname, loc from EMP ,Dept;
SQL > Select Ename, Job, Dname, loc from EMP, Dept Where
Job='MANAGER';
NonEqui Join
It is a join condition that is executed when no column in one table corresponds
directly to a column in the other table.
The data in the tables is directly not related but indirectly or logically related
through proper values.
Oracle_10g By Naresh A K
100
SQL > Select E.Ename, E.Sal, S.grade from EMP E, Salgrade S Where E.Sal
Between S.losal and S.hiSal;
Oracle 8i | Oracle 9i | Oracle 10g | Oracle 11g | Oracle 12c | Miscellaneous | PL/SQL | SQL | Oracle
RAC | Oracle Apps | Linux
Home » Articles » 9i » Here
Joins
o JOIN ... ON
o Multiple Joins
o OUTER JOIN , left out join, right outer join and full outer join.
CASE Expressions
NULLIF Function
COALESCE Function
Scalar Subqueries
Explicit Defaults
Joins
A range of new join syntax are available that comply with the ANSI/ISO SQL: 1999 standards.
Oracle_10g By Naresh A K
101
CROSS JOIN
NATURAL JOIN
The NATURAL JOIN performs a join for all columns with matching names in the two tables.
ANSI/ISO Syntax Existing Syntax
The USING clause is used if several columns share the same name, but you do not wish to join
using all of these common columns. The columns listed in the USING clause cannot have any
qualifiers in the statement, including the WHERE clause.
ANSI/ISO Syntax Existing Syntax
JOIN ... ON
The ON clause is used to join tables where the column names do not match. The join conditions
are removed from the filter conditions in the where clause.
ANSI/ISO Syntax Existing Syntax
Oracle_10g By Naresh A K
102
Multiple Joins
Multiple Joins are those where more than two tables are joined. The SQL: 1999 standard
assumes the tables are joined from the left to the right, with the join conditions only being able
to reference columns relating to the current join and any previous joins to the left.
ANSI/ISO Syntax Existing Syntax
OUTER JOIN
There are three variations on the outer join. The LEFT OUTER JOIN returns all the rows from the table
on the left side of the join, along with the values from the right hand side, or NULLs if a matching row
doesn't exist. TheRIGHT OUTER JOIN does the reverse of this. Finally, the FULL OUTER
JOIN returns all rows from both tables, filling in any blanks with nulls.
ANSI/ISO Syntax Existing Syntax
Extra filter conditions can be added to the join to using AND to form a complex join. These are often
necessary when filter conditions are required to restrict an outer join. If these filter conditions are placed
Oracle_10g By Naresh A K
103
in the WHERE clause and the outer join returns a NULL value for the filter column the row would be
thrown away. If the filter condition is coded as part of the join the situation can be avoided.
CASE Expressions
The case expression is a more flexible extension of the DECODE statement. In its simplest form it is
used to return a value when a match is found.
A more complex version is the Searched case expression where a comparison expression is used to
find a match.
NULLIF Function
The NULLIF function returns a NULL value if both parameters are equal in value. If the parameters are
not equal, it returns the value of the first parameter. The following query would return NULL.
COALESCE Function
The COALESCE function returns the first non-NULL value in an expression list. If all expressions are
null it returns NULL. The following query would return '3'.
Oracle_10g By Naresh A K
104
Scalar Subqueries
Scalar subqueries return a single value. They could be used in previous versions of Oracle in some
parts of an SQL statement, but Oracle9i extends their use to almost any place where an expression can
be used, including:
CASE expressions
SELECT statement
WHERE clause
ORDER BY clause
As a parameter of a function
For example.
Scalar subqueries can only return a single column and a single row. If more than one row is returned an
error is produced. If no rows are returned the value of NULL is used. The datatype of the returned value
must match the datatype it is being compared against. Scalar subqueries cannot be used for the
following:
RETURNING clauses
Explicit Defaults
The DEFAULT keyword can be used to explicit assign the columns default value during an INSERT or
UPDATE statement.
Oracle_10g By Naresh A K
105
OUTER JOIN
Oracle_10g By Naresh A K
106
To define the set of rows to be inserted into the target table of an Insert or
create table statement.
To define the set of rows to be included in a view or materialized view in a
Create view or Create Materialized view statement.
To define one or more values to be assigned to existing rows in an Update
statement.
To provide values for condition in a Where clause, Having clause, Start With
clause of Select , Update and Delete statements.
To define a table to be operated on by a containing query.
Solve a problem by combining the two queries, placing one query inside the
other query.
The inner query or the sub query returns a value that is used by the outer
query or the main query.
They are practically very useful when we need to Select rows from a table
with a condition that depends on the data in the table itself.
SUB Queries should be enclosed with braces( ).
The expression operator can be of :
Oracle_10g By Naresh A K
107
Guidelines to Follow:
Eg:
SQL > Select Ename , Sal, Job from EMP Where Sal > ( Select Sal from
EMP Where Empno=7566);
SQL > Select Ename , Sal, Job from EMP Where Job= ( Select Job from EMP
Where Ename='SMITH') ORDER BY Sal;
The data from the main query can be displayed by using a Group Function in
a Sub Query.
As a Group Function returns a single row, the query passes through the
success state.
The inner sub query should not have a group by clause in this scenario.
SQL > Select Ename, Job, Sal from EMP Where Sal = ( Select MAX(Sal) from
EMP);
SQL > Select Ename, Job, Sal from EMP Where Sal > ( Select AVG(Sal) from
EMP);
Oracle_10g By Naresh A K
108
SQL > Select Deptno, Min (Sal) from EMP Having MIN (Sal) > (Select
MIN(Sal) from EMP Where Deptno=20) GROUP BY DeptNO;
SQL > Select Job, AVG(Sal) from EMP group by Job Having AVG(Sal)
<( Select MAX(AVG(Sal)) from EMP group by Job);
SQL >Select Ename, Sal, Deptno from EMP Where Sal in (Select MIN(Sal)
from EMP Group By Deptno);
SQL > Select Ename, Sal, Deptno from EMP Where Sal <ANY (Select Sal from
EMP Where Deptno=20 ) ;
SQL >Select Ename, Sal, Deptno from EMP Where Sal <ANY (Select Sal from
EMP Where Job ='CLERK' );
Oracle_10g By Naresh A K
109
SQL >Select Ename, Sal, Deptno from EMP Where Sal <ANY (Select Sal from
EMP Where Deptno=20 ) AND Job <> 'CLERK';
SQL >Select Ename, Sal, Deptno from EMP Where Sal >ANY (Select Sal from
EMP Where Job ='CLERK' );
SQL >Select Ename, Sal, Deptno from EMP Where Sal >ANY (Select Sal from
EMP Where Deptno=20 ) AND Job <> 'CLERK';
ALL Operator
SQL > Select Ename, Sal, Deptno from EMP Where Sal >ALL (Select AVG(Sal)
from EMP Group By Deptno);
SQL > Select Job, Deptno, Sal from EMP Where (Deptno, Job) in ( Select
Oracle_10g By Naresh A K
110
Deptno, Job from EMP Where Deptno=20 and Job <> ('SalESMAN'));
If one of the values returned by the inner query is NULL value, then the
entire query returns no rows.
All condition that compare a NULL values result is a NULL
When ever a NULL could be part of sub query it is better not to use NOT IN
operator as it is equivalent to <>ALL
SQL > Select E.Ename from EMP E Where e.Empno in (Select M.mgr from
EMP M);
Oracle_10g By Naresh A K
111
SQL > Select E.Ename, E.Sal , E.Deptno, E1. sumsal from EMP E, (Select
Deptno, sum (Sal) sumsal from EMP group by Deptno) E1
Where E.Deptno=E1.Deptno ;
SQL > Select D1.Deptno , Dname, Staff from Dept D1, (Select Deptno, Count(*)
AS STAFF from EMP Group by Deptno) D2 Where D1.Deptno = D2.Deptno
AND staff >=5;
SQL > Select Deptno, SUM (Sal), Sum (Sal)/tot_Sal*100 “Salary percentage”
From EMP, (Select Sum (Sal) Tot_Sal from EMP)
Group by Deptno, tot_Sal;
SQL > Select * from (Select Empno, Ename, Hiredate from EMP ORDER BY
Hiredate Desc);
SQL > Select Ename, Sal, (Select AVG(Sal) from EMP) “ organization Average”
from EMP;
Oracle_10g By Naresh A K
112
Steps Performed
First the outer query is executed.
Passes the qualified column value to the inner query Where clause.
The inner query or candidate query is executed, and the result is passes to the
outer queries Where clause.
Depending on the supplied value, the condition is qualified for the specific
record.
SQL > Select Deptno, Dname from Dept D Where EXISTS ( Select * from EMP
E Where d.Deptno= E.Deptno);
SQL > Select Deptno, Dname from Dept D Where NOT EXISTS ( Select * from
EMP E Where d.Deptno=E.Deptno);
HIERARCHICAL QUERIES
These are queries that are executed upon tables that contain hierarchical data.
To execute the hierarchical queries, we need the following queries.
Oracle_10g By Naresh A K
113
Where It is used to restrict the rows returned by the query without affecting
other rows of the hierarchy.
Steps Followed
ORACLE selects the root row(s) of the hierarchy, which satisfy the condition
of the START WITH clause.
Oracle selects the child rows of each row. Each child row must satisfy the
condition of the CONNECT BY clause, with respect to one of the root rows.
Oracle Select children by evaluating the CONNECT BY condition with
respect to current parent row.
If the query contains a Where clause, oracle removes all rows from the
hierarchy that do not satisfy the condition of the Where clause.
RESTRICTIONS
They cannot be used to perform joins.
They cannot Select data from a view, whose query perform a Job.
If ORDER BY clause is used, then the rows are returned as per the
specification in the ORDER BY clause.
START WITH
CONNECT BY CLAUSE
Oracle_10g By Naresh A K
114
This clause specifies the relationship between Parent and Child rows, in a
hierarchical query.
This clause contains a condition that defines a relations ship.
This condition can be any condition as defined by the syntax description.
Within the condition, some part of the condition must use the PRIOR operator,
which refers to the parent row.
The forms of PRIOR operator is
PRIOR expr comparision_operator expr
Expr comparision_operator PRIOR expr.
The clause can contain other conditions to further filter the rows Selected by
the query.
It cannot contain a sub query.
SQL > Select Ename, Empno, mgr, Job, Sal from EMP START WITH
Sal=3000 CONNECT BY PRIOR Empno=mgr;
SQL > Select Ename, Empno, mgr, Job from EMP START WITH
Job='MANAGER' CONNECT BY PRIOR Empno=mgr;
SQL > Select Ename, Empno, mgr, Job from EMP CONNECT BY PRIOR
Empno=mgr;
Oracle_10g By Naresh A K
115
Oracle_10g By Naresh A K
116
PSUEDO COLUMNS
Pseudo Columns behave like a table columns, but is not actually stored in a
table.
The Available Pseudo Columns are:
LEVEL
ROWID
ROWNUM
CARRVAL
NEXTVAL
This pseudo column return 1 for root node, 2 for a child of a root and so on.
To establish the hierarchical relationship with LEVEL NEED
SQL > SELECT LPAD ('>', 2* (LEVEL -1)) LEVELs, Ename, Empno, Mgr, Job
from emp START WITH sal=5000
CONNECT BY PRIOR Empno=Mgr;
SQL > SELECT LPAD ('>', 2* (LEVEL -1)) ||Ename||' ' ||Empno||' '||Mgr||' '||Job
from emp
START WITH sal=5000
CONNECT BY PRIOR Empno=Mgr;
SQL > Select LPAD ( ' *', 2* (level -1)) || Ename ||' '||Empno||' '||Mgr||' '||Job || ' '||
Sal from EMP START WITH Job='PRESIDENT' CONNECT BY PRIOR Empno=mgr AND
LEVEL <=2;
SQL > Select LPAD ( ' >', 2* ( LEVEL -1 )) || Ename Org_chart, Empno, mgr,
Job from EMP
Oracle_10g By Naresh A K
117
SQL > Select LPAD ( ' ', ROWNUM,' * ') from EMP;
SQL > Select ROWNUM, Ename, Sal from EMP;
Oracle_10g By Naresh A K
118
SQL > Select ROWNUM, Ename, Sal from EMP Where ROWNUM<6
ORDER By Sal; WRONG WAY
SQL > Select * from (Select * from EMP ORDER BY Sal DESC) Where
ROWNUM <6;
SQL > SELECT MIN (SAL) FROM (SELECT SAL FROM EMP ORDER BY
SAL DESC) WHERE ROWNUM <1+&1;
This pseudo column returns a row's address for each row in the database.
ROWID values contain information necessary to locate a row.
The row belongs to which data block in the data file.
The row belongs to which row in the data block (first rows is 0).
The row belong to which data file (first file is 1)
The rows in different tables that are stored together in the same cluster can
have the same ROWID
The data type of the values belonging to the ROWID are of ROWID data
type.
Oracle_10g By Naresh A K
119
SQL > Select ROWID, Ename, Job from EMP Where Deptno=20;
SQL > Select Ename, Sal, Job from EMP Where ROWID
='AAACQQAACAAAAEHAAA';
SQL > Select Ename, Sal, Job from EMP Where ROWID
<'AAACQQAACAAAAEHAAA';
SQL > SELECT * FROM (SELECT ROWNUM RN, EMPNO FROM EMP)E
WHERE MOD(E.RN,2)=0;
Oracle_10g By Naresh A K
120
RESTRICTION
The Currval and Nextval cannot be used in:
A Sub Query.
A view's query or snapshot's query.
A Select statement with the distinct operator.
A Select Statement with a Group by or Order by clause.
A Select statement that is combined with another Select statement with
UNION, INTERESECT, MINUS set statement.
The Where clause of a Select statement.
The Default value of a column in a Create Table or Alter Table statement.
The condition of Check constraint.
SEQUENCE
A SEQUENCE is a schema object that can generate unique sequential values.
The SEQUENCE values are often used for Primary Key's and Unique Key's.
To refer to the current or next value of a SEQUENCE in the schema of
another user, the following privileges should be available.
Select Object Privilege.
Select Any Sequence.
In a single Select statement all referenced sequences. LONG columns,
Updated tables, and locked tables, must be located on the same database.
When a Sequence is created, we can define its Initial value and the Increment
between its values.
The First reference to the NEXTVAL returns the Sequences initial value.
Before the Currval can be used for a Sequence in a session, first the
Sequence should be incremented with Nextval.
A Sequence can be incremented only once in a singe SQL statement.
A Sequence can be accessed by many users concurrently with no WAITING
or LOCKING.
Oracle_10g By Naresh A K
121
Currval and Nextval should be qualified with the name of the sequence.
SCHEMANAME.SEQUENCEname.CURRVAL
SCHEMANAME.SEQUENCEname.NEXTVAL
SCHEMANAME.SEQUENCEname.CURRVAL@dblink
SCHEMANAME.SEQUENCEname.NEXTVAL@dblink
CREATING SEQUENCES
INCREMENT BY
Specifies the interval between the sequence numbers.
Value can be positive or negative, but cannot be 0.
If the value is positive it is incremented sequence else it is detrimental
sequence.
If omitted default to the instrumentation of 1.
Oracle_10g By Naresh A K
122
MINVALUE
Specifies the Sequence's minimum value.
NOMINVALUE
Specifies a minimum value of 1 for an ascending sequence or -(10)26 for
descending sequence.
MAXVALUE
Specifies the maximum value that can be generated.
NOMAXVALUE
empnSpecifies a maximum value of (10)27 for ascending sequence or -1 for
descending sequence.
START WITH
Specifies the first sequence number to be generated.
For ascending sequences the default value is sequence's minimum value, vice
versa.
CYCLE
Specifies the sequence will continue to generate values after reaching either
maximum or minimum value.
NOCYCLE
specifies the sequences cannot general more values after the targeted limit.
CACHE
specifies the pre allocation of sequence number, the minimum is 2k
Cache tells Oracle to pre-generate or cache the next nth sequence values and
store them in system memory for increased performance. If the database fails
(crashes), the sequence numbers are lost, and when the application is restarted,
a gap may occur in the sequence numbers. To prevent this possibility you can
specify NOCACHE, which defers the caching of sequence numbers in
memory. Using NOCACHE may result in slightly reduced performance, but it
will prevent any gaps from appearing in the sequence should a database
failure take place. In general, Oracle recommends caching sequence numbers
and not using the NOCACHE parameter unless the continuity of sequence
numbers is considered a critical factor
Oracle_10g By Naresh A K
123
NOCACHE
Specifies the values of a sequence are not reallocated.
If the above parameters are not specified by default 20 values is CACHE.
ORDER
Guarantees the sequence numbers to be generated in the order of request.
NOORDER does not guarantee the sequence number without pre order default
SQL > CREATE TABLE SAMPLE
(SAMPLEID NUMBER (4) CONSTRAINT SAMPLEID_PK PRIMARY
KEY,
SAMPLE_NAME VARCHAR2 (15), SAMPLE_DATE DATE);
SQL >. INSERT into EMP (Empno, Ename) values (sample .nextval, '&Ename ');
Oracle_10g By Naresh A K
124
SQL >
c
Modifying a Sequence
The ALTER command can be used to change the present status of a sequence.
The ALTER sequence command can be used to change:
Increment value
Maximum value
Mininum value
Cycle option
Cache option
CONFIRMING SEQUENCES
All sequences that have been created are documented in the data dictionary.
The data dictionary in which the information of sequences are stored is
USER_OBJECTS;
The settings of the sequence can be confirmed by Selecting on
USER_SEQUENCES.
Oracle_10g By Naresh A K
125
Sequence created.
In our first example, we will assign the NEXTVAL pseudo-column to a variable, as follows.
SQL> DECLARE
2 n PLS_INTEGER;
3 BEGIN
4 n := s.NEXTVAL;
5 DBMS_OUTPUT.PUT_LINE('Nextval=' || TO_CHAR(n));
6 END;
7 /
Nextval=1
Oracle_10g By Naresh A K
126
We can also use the sequence expression to set a default for our variable, as the following
example demonstrates.
SQL> DECLARE
2 n PLS_INTEGER := s.NEXTVAL;
3 BEGIN
4 DBMS_OUTPUT.PUT_LINE('Nextval=' || TO_CHAR(n));
5 END;
6 /
Nextval=2
Session altered.
SQL> DECLARE
2 n PLS_INTEGER;
3 BEGIN
4 FOR i IN 1 .. 10000 LOOP
5 n := s.NEXTVAL;
6 END LOOP;
7 FOR i IN 1 .. 10000 LOOP
Oracle_10g By Naresh A K
127
Session altered.
Interestingly, the tkprof output for our trace file includes two similar SQL statements, both of
which select the sequence's next value from DUAL. As stated, Oracle's implementation of
sequence fetching hasn't changed. The new PL/SQL sequence expression is executed "behind
the scenes" using a query from DUAL (as are the SYSDATE and USER PL/SQL functions)
and our tkprof file highlights this. The first entry is as follows.
****************************************************************************
****
SQL ID : 0k4rn80j4ya0n
Select S.NEXTVAL
from
dual
****************************************************************************
****
We have 10,000 executions and fetches of this statement (sequence cache size is at the default
of 20 as we can see from the current gets above. Oracle updated the SEQ$ table 500 times to
assign 10,000 sequence numbers; with a series of 20 sequence values per update). This is the
Oracle_10g By Naresh A K
128
statement that Oracle executed to support our new sequence expression. We know this because
there is no "NVAL" alias in the SQL text, unlike the second statement in the tkprof output
below.
****************************************************************************
****
SQL ID : 9kwysc3kyrusj
SELECT S.NEXTVAL AS NVAL
FROM
DUAL
****************************************************************************
****
This is the statement that we explicitly coded into our example. We can see that the statistics
for I/O, executes and fetches are identical to those for our 10,000 PL/SQL sequence
expressions. Critically, the elapsed and CPU times are also the same (we attribute such tiny
differences to "noise"). We conclude, therefore, that the new sequence syntax provides greater
convenience, but nothing else.
SET OPERATORS
These operators are used to combine information of similar data type from one
Oracle_10g By Naresh A K
129
UNION OPERATOR
The UNION operator merges the outputs of two or more queries into a single
set of rows and columns.
The queries are all executed independently but their output is merged.
Only the final query ends with a semicolon
SQL > Select Ename, Job from EMP Where Deptno =20
UNION
Select Ename, Job from EMP Where Deptno=30;
RESTRICTION
The two Select statement may not contain an ORDER by clause , the final
result of the entire UNION operation can be ordered.
The number of columns retrieved by the first Select statement must be equal
to the number of columns retrieved by the second Select, and data types must
match.
The columns used fro ordering must be defined through a number.
Oracle_10g By Naresh A K
130
UNION ALL
It all similar to UNION, Where UNION suppresses the duplicates.
If the duplicate records have also to be displayed then UNION ALL is used.
SQL > Select Empno, Ename, deptno from EMP Where Deptno=10
UNION ALL
Select Empno, Ename, deptno from EMP Where Deptno=30
ORDER BY 1;
INTERSECT OPERATOR
This operator return the rows that are common between tow sets of rows.
SQL > Select Empno, Ename, Sal from EMP Where Deptno=10 and sal > 2000
INTERSECT
Select Empno, Ename, Sal from EMP Where Deptno=10 and sal <3000
ORDER BY 1;
MINUS OPERATOR
SQL > Select DEPTNO, Empno, Ename from EMP Where Deptno=10
MINUS
Select DEPTNO, Empno, Ename from EMP Where Deptno=30
ORDER BY 1;
Oracle_10g By Naresh A K
131
VIEWS IN ORACLE
PREREQUISITES
Oracle_10g By Naresh A K
132
Types Of Views
Simple Views
Complex views
Simple Views Which contains a sub query that retrieves from one base table.
Complex Views
Complex View
SQL > Create or Replace View OrgDesignations As Select Job from EMP Where
Oracle_10g By Naresh A K
133
Deptno=10
UNION Select Job from EMP Where Deptno in (20,30);
Once the view has been created, we can query upon the Data Dictionary table
called USER_VIEWS to see the name and definition of the View.
The text of the Select statement that constitutes the views is stored in a LONG
column.
Modifying a View
SQL > Create View InsertDetp20 as Select * from EMP Where Deptno=20;
Oracle_10g By Naresh A K
134
As Select Ename, Job, Sal, Grade from EMP E, Salgrade S Where E.Sal Between
S.loSal AND S.HiSal;
Dropping A View
INLINE VIEWS
An Inline View is a sub query with an alias called as correlation name, which
can be used within a SQL statement.
An Inline View is similar to using a named sub query in from clause of the
main query.
An Inline View is not a schema object.
An Inline View in from clause of a Select statement defining data source for
the Select statement.
Example
SQL > Select E1.Ename, E1.Sal, E1.Deptno, E2.MaxSal from EMP E1, (Select
Deptno, Max (Sal) MaxSal from EMP Group by Deptno) E2 Where
E1.Deptno=E2.Deptno and E1.Sal < E2.MaxSal;
Oracle_10g By Naresh A K
135
Data can be added through a View, unless it contains any of the above rules
and there are Not Null columns, and without Default values.
Example
SQL > Create View InserDetp (DeptId, DeptName, Place) as Select Deptno,
Dname, Loc from Dept;
To ensure that DML on the view stays within the domain of the view by using
the WC option clause.
Views make it possible to perform referential integrity checks.
Using views we can enforce constraints at databases level.
Using views we can protect the data integrity, but the use is very limited.
The WC option clause specifies that Insert, and Updates performed through
the View are not allowed to create rows, that the Vies cannot Select.
Views allow integrity constraints and data validation check to be enforce on
data being inserted or updated.
Example
SQL > Create or Replace View EDept30 As Select * from EMP Where
Deptno=30 WITH CHECK OPTION CONSTRAINT EDept30ChkView;
SQL > Create Or Replace View Emanager As Select * from EMP Where
Job='MANAGER'
CHECK OPTION CONSTRAINT MANAGER View;
B adding the WITH READ ONLY option we can ensure that no DML
operations are executed.
An Attempt to perform a DML operation results in ORACLE SERVER
ERROR.
Oracle_10g By Naresh A K
136
Example
It is a schema object which contains an entry for each value that appears in the
indexed columns of the table or cluster.
It provides direct, fast access to rows.
Type of INDEXES
Normal Index
Oracle_10g By Naresh A K
137
Bitmap Indexes
They store RowID's associated with a key value as Bitmap.
Specify Bitmap to indicate that index has to be created with bitmap for
each Distinct key.
Each bit in the bitmap corresponds to a possible Rowid.
Unique Indexes
Specify UNIQUE to indicate that the value of the columns or columns
upon with the index is based must be Unique.
We cannot specify both Unique and Bitmap.
Function Indexes
They are based on expressions
Enable query to evaluate value returned by an expression.
Partitioned Indexes.
They contain partitions containing and entry for each value that appears in the
indexed columns of the tables.
PRE REQUISITES:
The table or Cluster to be Indexed must be in the own schema.
Index object privilege should be available on the table to indexed
Crete any index system privilege must be available.
Oracle_10g By Naresh A K
138
Index Example:
Note: The Function based indexes are used only when the query statement is
executed through the specified function.
Example:
Oracle_10g By Naresh A K
139
Specification of an Index:
Oracle_10g By Naresh A K
140
DATABASE SECURITY
SQL > Grant < privileges Name > ON <Object Name > TO < User Name >
Oracle_10g By Naresh A K
141
REVOKE
Revoke is used when we want one database to stop sharing the information
with other users.
Revoke privileges is assigned not only on table object, but also Views,
Synonyms, Indexes etc.
SQL > REVOKE < privileges Name > ON <Object Name > FROM < User Name
>
TYPES OF PRIVILEGES
System privileges
They allow a user to perform certain actions within the database.
Object privileges
An object privileges allows a user to perform certain actions on database
objects.
The schema object that stores the information about the privileges is
USER_TAB_PRIV_MADE.
The column of USER_TAB_PRIV_MADE
Grantee, Table_Name, Grantor, privilege, Grantable and Hierarchy.
The Schema object that stores the information about the PRIVILEGES receive
are
Oracle_10g By Naresh A K
142
USER_TAB_PRIVS_RECD
The column of USER_TAB_PRIVS_RECD
Owner , Table_Name ,Grantor , privilege, Grantable and Hierarchy
Advantage:
Rather than assigning privileges one at a time directly to a user, we can create
a ROLE, assign privileges to that ROLE, and then Grant that ROLE to
multiple USERS and ROLES.
When you ADD or DELETE a privileges from a ROLE, all users and Roles
assigned that automatically receive or lose that privilege.
We can Assign multiple roles to USER or ROLE
A ROLE can be assigned with a PASSWORD also.
Role's Creation:
Syntax:
Oracle_10g By Naresh A K
143
Revoking a Role:
Dropping a Role:
Oracle_10g By Naresh A K
144
Syntax:
SQL > Create synonym < synonym _Name > FOR < Schema_Name > .
<Object_Name >
Synonym Types.
Some features for query processing is Oracle include the use of ONLINE
ANALYTICAL PROCESSING (OLAP) upon the data base.
OLAP features are useful for Data Warehousing and Data Mart applications.
The OLAP operation are performance enhancements.
ToP N queries.
Group By
Cube
Roll Up
ROLL UP
Oracle_10g By Naresh A K
145
SQL > Select Deptno, SUM (Sal ) from EMP group by Deptno;
SQL >Select Deptno, SUM (Sal ) from EMP group by ROLLUP (deptno);
When multiple columns are passed to ROLLUP, the ROLLUP, groups the
rows into blocks with the same columns values.
SQL > Select Deptno, SUM (Sal ) from EMP group by ROLLUP (Job);
NOTE: NULL values in the output of ROLLUP operations typically mean that
the row contains subtotal or grant total information. Use the NVL () Function for
proper Meaning.
CUBE:
SQL > Select Deptno, Job, SUM (Sal) Salary from EMP group by CUBE (Job,
Deptno);
Oracle_10g By Naresh A K
146
SQL > Select Grouping (Deptno), Deptno, SUM (Sal) Salary from EMP group by
ROLLUP (Deptno);
DECODE FUNCTION:
Example:
SQL > Select Ename || 'Takes Care of ' || ' '||DECODE ( Job, '
Analyst','Analysis','Clerk','Firing','Manager','Managing','President','Administratio
n' ,'Salesman', 'Sales) Responsibilities from EMP;
SQL > Select Count (*) Total, SUM (DECODE (TO_CHAR (Hiredate,'YYYY'),
1980, 1,0)) “1980”,
SUM (DECODE (TO_CHAR (Hiredate,'YYYY'), 1981, 1,0)) “1981”,
SUM (DECODE (TO_CHAR (Hiredate,'YYYY'), 1982,1,0)) “1982”,
SUM (DECODE (TO_CHAR (Hiredate,'YYYY'), 1983, 1,0)) “1983” from
EMP;
Oracle_10g By Naresh A K
147
Example:
Simple CASE
These expressions are used to determine the returned value.
Syntax:
CASE search_Expr
WHEN Exp1 THEN Result 1
WHEN Exp2 THEN Result 2
ELSE
Default_Result
END;
Example:
Oracle_10g By Naresh A K
148
Syntax:
CASE When Condition 1 Then Result 1
When Condition 2Then Result 2
When Condition n Then Result 1
Else Default Result
End from EMP;
Example:
ANALYTIC FUNCTION:
Oracle_10g By Naresh A K
149
Oracle_10g By Naresh A K
150
Introduced in Oracle 8i, analytic functions, also known as windowing functions, allow
developers to perform tasks in SQL that were previously confined to procedural
languages.
Introduction
o query_partition_clause
o order_by_clause
o windowing_clause
Related articles.
Top-N Queries
Introduction
Probably the easiest way to understand analytic functions is to start by looking at
aggregate functions. An aggregate function, as the name suggests, aggregates data
from several rows into a single result row. For example, we might use
the AVG aggregate function to give us an average of all the employee salaries in the
EMP table.
Oracle_10g By Naresh A K
151
SELECT AVG(sal)
FROM emp;
AVG(SAL)
----------
2073.21429
SQL>
The GROUP BY clause allows us to apply aggregate functions to subsets of rows. For
example, we might want to display the average salary for each department.
DEPTNO AVG(SAL)
---------- ----------
10 2916.66667
20 2175
30 1566.66667
SQL>
In both cases, the aggregate function reduces the number of rows returned by the
query.
Oracle_10g By Naresh A K
152
SET PAGESIZE 50
BREAK ON deptno SKIP 1 DUPLICATES
14 rows selected.
SQL>
Oracle_10g By Naresh A K
153
This time AVG is an analytic function, operating on the group of rows defined by the
contents of the OVER clause. This group of rows is known as a window, which is why
analytic functions are sometimes referred to as window[ing] functions. Notice how
the AVG function is still reporting the departmental average, like it did in the GROUP
BY query, but the result is present in each row, rather than reducing the total number
of rows returned. This is because analytic functions are performed on a result set after
all join, WHERE, GROUP BY and HAVINGclauses are complete, but before the final ORDER
BY operation is performed.
[ query_partition_clause ] [ order_by_clause
[ windowing_clause ] ]
The sub-elements of the analytic_clause each have their own syntax diagrams,
shown here. Rather than repeat the syntax diagrams, the following sections describe
what each section of the analytic_clause is used for.
query_partition_clause
The query_partition_clause divides the result set into partitions, or groups, of
data. The operation of the analytic function is restricted to the boundary imposed by
these partitions, similar to the way a GROUP BY clause affects the action of an
aggregate function. If the query_partition_clause is omitted, the whole result set is
treated as a single partition. The following query uses an empty OVER clause, so the
average presented is based on all the rows of the result set.
CLEAR BREAKS
Oracle_10g By Naresh A K
154
SQL>
Oracle_10g By Naresh A K
155
FROM emp;
SQL>
order_by_clause
The order_by_clause is used to order rows, or siblings, within a partition. So if an
analytic function is sensitive to the order of the siblings in a partition you should
include anorder_by_clause. The following query uses the FIRST_VALUE function to
return the first salary reported in each department. Notice we have partitioned the
result set by the department, but there is no order_by_clause.
Oracle_10g By Naresh A K
156
SQL>
Oracle_10g By Naresh A K
157
SQL>
In this case the "ASC NULLS LAST" keywords are unnecessary as ASC is the default
for an order_by_clause and NULLS LAST is the default for ASC orders. When
ordering by DESC, the default is NULLS FIRST.
Oracle_10g By Naresh A K
158
processed by the analytic function, but it may not always affect the display order. As a
result, you must always use a conventional ORDER BY clause in the query if display
order is important. Do not rely on any implicit ordering done by the analytic function.
Remember, the conventional ORDER BY clause is performed after the analytic
processing, so it will always take precedence.
windowing_clause
We have seen previously the query_partition_clause controls the window, or
group of rows, the analytic operates on. The windowing_clause gives some analytic
functions a further degree of control over this window within the current partition, or
whole result set if no partitioning clause is used. The windowing_clause is an
extension of the order_by_clause and as such, it can only be used if
an order_by_clause is present. The windowing_clause has two basic forms.
When using ROWS BETWEEN, you are indicating a specific number of rows relative to
the current row, either directly, or via an expression. Assuming you don't cross a
partition boundary, that number of rows is fixed. In contrast, when you use RANGE
BETWEEN you are referring to a range of values in a specific column relative to the
value in the current row. As a result, Oracle doesn't know how many rows are included
in the range until the ordered set is created.
It is possible to omit the BETWEEN keyword and specify a single RANGE/ROWS endpoint.
In this case, Oracle assumes your specified RANGE/ROWS is the start point and the end
point it the current row. I would advise against using this syntax as it will be unclear to
anyone who doesn't understand this default action.
Possible values for "start_point" and "end_point" are:
UNBOUNDED PRECEDING : The window starts at the first row of the partition, or the whole
result set if no partitioning clause is used. Only available for start points.
UNBOUNDED FOLLOWING : The window ends at the last row of the partition, or the whole
result set if no partitioning clause is used. Only available for end points.
CURRENT ROW : The window starts or ends at the current row. Can be used as start or end
point.
Oracle_10g By Naresh A K
159
value_expr PRECEDING : A physical or logical offset before the current row using a
constant or expression that evaluates to a positive numerical value. When used with RANGE, it
can also be an interval literal if the order_by_clause uses a DATE column.
The documentation states the start point must always be before the end point, but this
is not true, as demonstrated by this rather silly, but valid, query.
Oracle_10g By Naresh A K
160
SQL>
In fact, the start point must be before or equal to the end point. In addition, the current
row does not have to be part of the window. The window can be defined to start and
end before or after the current row.
For analytic functions that support the windowing_clause, the default action is
"RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW". The
following query is similar to one used previously to report the employee salary and
average department salary, but now we have included an order_by_clause so we
also get the default windowing_clause.
Oracle_10g By Naresh A K
161
SQL>
The following query shows one method for accessing data from previous and following
rows within the current row using the windowing_clause. This can also be
accomplished withLAG and LEAD.
CLEAR BREAKS
Oracle_10g By Naresh A K
162
SQL>
Oracle_10g By Naresh A K
163
LISTAGG orders data within each group specified in the ORDER BY clause and
then concatenates the values of the measure column.
As a single-set aggregate function, LISTAGG operates on all rows and returns a
single output row.
As a group-set aggregate, the function operates on and returns an output row for
each group defined by the GROUP BY clause.
As an analytic function, LISTAGG partitions the query result set into groups based
on one or more expression in the query_partition_clause.
The arguments to the function are subject to the following rules:
The measure_expr can be any expression. Null values in the measure column are
ignored.
The delimiter_expr designates the string that is to separate the measure values.
This clause is optional and defaults to NULL.
The order_by_clause determines the order in which the concatenated values are
returned. The function is deterministic only if the ORDER BY column list achieved
unique ordering.
The return data type is RAW if the measure column is RAW; otherwise the return
value is VARCHAR2.
Aggregate Examples
Oracle_10g By Naresh A K
164
Oracle_10g By Naresh A K
165
AVG *
CLUSTER_DETAILS
CLUSTER_DISTANCE
CLUSTER_ID
CLUSTER_PROBABILITY
CLUSTER_SET
Oracle_10g By Naresh A K
166
CORR *
COUNT *
COVAR_POP *
COVAR_SAMP *
CUME_DIST
DENSE_RANK
FEATURE_DETAILS
FEATURE_ID
FEATURE_SET
FEATURE_VALUE
FIRST
FIRST_VALUE *
LAG
LAST
LAST_VALUE *
LEAD
LISTAGG
MAX *
MIN *
NTH_VALUE *
NTILE
PERCENT_RANK
PERCENTILE_CONT
PERCENTILE_DISC
Oracle_10g By Naresh A K
167
PREDICTION
PREDICTION_COST
PREDICTION_DETAILS
PREDICTION_PROBABILITY
PREDICTION_SET
RANK
RATIO_TO_REPORT
ROW_NUMBER
STDDEV *
STDDEV_POP *
STDDEV_SAMP *
SUM *
VAR_POP *
VAR_SAMP *
VARIANCE *
MERGE:
The Merge statement is used to select rows from one or more sources from
update or insert into one or more tables.
Oracle_10g By Naresh A K
168
SQL> INSERT INTO Bonus (Empno) (Select E.empno from EMP E WHERE
job='SALESMAN');
SQL > MERGE INTO BONUS B USING (SELECT Empno, Sal, Deptno from
EMP WHERE Deptno=30) S
ON (B.Empno = S.Empno)
WHEN MATCHED THEN
UPDATE SET B.BONUS =B.BONUS + S.sal * 0.2
DELETE WHERE (S.Sal > 3000)
WHEN NOT MATCHED THEN
INSERT (B.Empno, B.BONUS) VALUES (S.Empno, S.Sal * 0.2)
WHERE (S.SAL <= 3000);
SQL > MERGE INTO Bonus1 B USING (SELECT Empno, Sal, Deptno from
EMP WHERE Deptno=30) S
ON (B.Empno = S.Empno)
WHEN MATCHED THEN
UPDATE SET B.Bonus =B.Bonus + S.sal * 0.2
DELETE WHERE (S.Sal >2000)
WHEN NOT MATCHED THEN
INSERT (B.Empno, B.Bonus) VALUES (S.Empno, S.Sal * 0.2) WHERE
(S.SAL <= 3000);
Oracle_10g By Naresh A K
169
SQL > RENAME < old name > TO < new name >;
SQL > Comment ON table EMP is ' the table storing Employees information';
Dropping A Comments:
Oracle_10g By Naresh A K
170
SQL > Create table SampDept3 AS Select * from Dept Where 1=3;
Oracle_10g By Naresh A K
171
PL/SQL
Oracle_10g By Naresh A K
172
If the PL/SQL block does not contain any SQL statements, the entire
block is executed on the on the client side.
Advantages of PL/SQL:
Completely portable.
High performance transaction processing language.
Support for SQL
Support for Object Oriented Programming.
Better performance.
Higher productivity.
Tight integration with oracle.
Tight security.
Oracle_10g By Naresh A K
173
Oracle_10g By Naresh A K
174
Declare
Variable, Cursor, User dine Exception.
Begin
SQL statements
Pl/SQL statements
EXCEPTION
Actions to perform when errors occur.
END.
Only Begin and End Keywords are Mandatory.
Place a semicolon (;) at the end of the SQL statement or PL/SQL control
statement.
Use a slash (/) to run the anonymous PL\SQL block in SQL*Plus buffer.
Place a period (.) to close a SQL*plus buffer
Semicolons within the block don’t close or Run the Buffer
In PL\sql an error is called an Exception
Sections keywords DECLARE, BEGIN, and EXCEPTION should not contain
a semicolon
END and all other PL|SQL statements should be placed with a semicolon.
ANONYMOUS BLOCKS
Oracle_10g By Naresh A K
175
NAMED BLOCKS
The have all the features as specified for the anonymous blocks but the
only difference is that each block can be named if necessary.
SUBPROGRAMMED BLOCKS
These are named PL\SQL blocks that can take parameters and can be
invoked.
These blocks are either declared as procedures or functions
A procedural block is used for performing an action, and a functional
block is used for performing computations
Usage of variables:
Date can be temporary stored in one or more variables for use when
validating data input for processing dates flow process.
Manipulation for stored values
Variable can be used for calculations and other data manipulations
without accessing the database.
Reusability
Once declared can be repeated by even in other blocks.
Ease of maintenance:
Variables can be declared basing on the declarations on the definitions
of database columns.
Provide data independence, reduces maintenance costs and allows
programs to adapt as the database changes.
HANDLING VARIABLES:
Oracle_10g By Naresh A K
176
1) Storage format
2) Constraints
3) Valid range
Oracle_10g By Naresh A K
177
PL\SQL blocks.
SYNTAX:
Character Set:
1) PL\SQL programs are written as lines of text using a specific set of
characters.
2) The characters that can be used are
Oracle_10g By Naresh A K
178
A-Z of a-z
0-9
( )+_*<>?!=:.’@%,#$&/{}?[]
3) PL\SQL key words are not case sensitive; hence lower case letters
are equivalent to corresponding upper case letter
Lexical units:
Identifiers:
They are used to name PL\SQL program items and units
Identifiers can be include
Constants, variables, exception, cursors variables,
subprograms, packages.
O Identifiers are not case sensitive, until they are not declared within
single quotes
o An identifiers length cannot exceed 30 characters.
Oracle_10g By Naresh A K
179
RESERVED WORDS
PREDEFINED IDENTIFIERS:
The identifiers globally declared package STANDARD can be
redeclaration.
Declaring predefined identifiers again is error prone as the
local declaration overrides the global declaration
QUOTED IDENTIFIERS:
LITERALS:
A Literal is a numeric, character, string or Boolean values not
represented by identifier
NUMERIC LITERALS:
Oracle_10g By Naresh A K
180
STRING LITERALS:
o A String literal is a sequence of zero or more characters enclosed by
single quotes.
Oracle_10g By Naresh A K
181
o All String literal except in NULL string '' have data type CHAR.
o To represent an apostrophe within a string declare two string quotes.
Example:
' I am in oracle’
'02-10-83’
DATETIME LITERAILS:
o A DATETIME literals can have various formats depending on the
data type.
Example: DATE’1998-12-25’;
TIMESTAMP’1997-10-22 01:05:21;
COMMENTS IN PL\SQL:
o PL\SQL complier ignores comments.
o Comments promote readability and aids understanding
o PL\SQL support two styles.
SINGLE LINE Comments (--)
MULTILINE Comments (/*……*)
BINARY_INTEGER
Oracle_10g By Naresh A K
182
BINARY_INTEGER SUBTYPES
NUMBER:
This datatype are used to store Fixed-point or Floating_point
numbers
The magnitude range is 1*10 ----------------------------------,
above this range numeric overflow or underflow error is
Oracle_10g By Naresh A K
183
generated
Precision can be specified, for total number of digits and scal
Syntax: NUMBER (P,S);
NUMBER SUBTYPES:
PLS_INTERGES
CHAR
It is used to store flexed length character data.
The maximum size is 32767 bytes.
If the maximum size is not specified then it defaults to 1.
Oracle_10g By Naresh A K
184
BOOLEAN TYPES:
DECLARATION IN PL/SQL
The program stores values in variables.
As the program executes, the values of variables can change but the values of
constants cannot change.
Declarations allocate storage space for a value, hence should be specified by a
data type, and name for further reference.
Any variable can be declared only in the declarative part of any PL/SQL
block, subprogram or package.
Example;
DECLARE
Name VARCHAR(20);
DOB date;
Bonus number:=0;
Begin
End;
Oracle_10g By Naresh A K
185
DBMS_OUTPUT package.
The package enables to display output from PL/SQL blocks and subprograms.
The procedure PUT_LINE outputs information to a buffer in the SGA.
The information can be displayed by calling the procedure GET_LINE or by
setting SERVEROUTPUT ON in SQL * Plus.
Syntax:
DBMS_OUTPUT.PUT_LINE ('NARESH’);
Has limitation for maximum of 255 characters per line.
The DBMS_OUTPUT package is owned by the oracle USER SYS.
It writes information to the BUFFER for STORAGE.
The size of the BUFFER can be set between 2000 TO 1,000,000 Bytes.
The specifications to SET buffer are
SET SERVEROUTPUT ON;
SET SERVEROUTPUT ON SIZE 5000;
SET SERVEROUTPUT OFF;
Oracle_10g By Naresh A K
186
OPERATOR in PL/SQL:
Logical
Arithmetic
Concatenation
Parenthesis to control order of operations.
Exponentiation.
Comparison.
SQL*Plus
DECLARE
X NUMBER : =10;
BEGIN
DBMS_OUTPUT.PUT_LINE ('The value of X:=' || ' '||X);
DECLARE
X NUMBER: =20;
BEGIN
DBMS_OUTPUT.PUT_LINE (' The value of X:=' || ' '||X);
END;
Oracle_10g By Naresh A K
187
While passing the values to arguments at Runtime, the PL/SQL variables can
be treated as the types.
Bind variables.
PL/SQL variables.
Bind Variables:
In PL/SQL to reference bind variables, it must be prefixed with a colon ( : ).
In SQL * Plus the bind variable has to be displayed using the PRINT
command.
Oracle_10g By Naresh A K
188
Example:
Example2:
Oracle_10g By Naresh A K
189
Branching Statements:
In PL/SQL branching is implemented using the IF statements.
PL/SQL provides three types of conditional control.
Simple IF , ELSIF, ELSE IF
The branching standards can be implemented either as
Simple IF
Nested IF
Else IF ladders.
Syntax:
IF Condition1 THEN
Statement1;
Statement2;
End IF;
SQL >
Oracle_10g By Naresh A K
190
Syntax:
IF Condition THEN
Statement1;
ELSE
Statement2;
END IF;
This concept should be used when trying to choose between two mutually
exclusive actions.
Example:
BEHAVIOR OF Null’s:
Oracle_10g By Naresh A K
191
END IF;
ELSIF STATEMENTS:
IF conditions1 THEN
Statement1;
ELSIF conditions2 THEN
Statement2;
ELSIF conditions3 THEN
Statement3;
ELSE
Statement N;
END IF;
Oracle_10g By Naresh A K
192
Example:
ELSE
Dbms_output.put_line ('Have a Nice Day’);
END IF;
END;
NESTED IF STATEMENTS:
Oracle_10g By Naresh A K
193
Syntax:
IF Condition THEN
IF Condition THEN
Statement1;
ELSE
IF Condition THEN
Statement2;
ELSE
Statement3;
END IF;
END IF;
ELSE
Statement4;
END IF;
Oracle_10g By Naresh A K
194
ELSE IF LADDER:
Syntax:
IF condition THEN
Statement1;
ELSIF condition THEN
Statement2;
ELSIF condition THEN
Statement3;
ELSE
Statement4;
END IF;
BEGIN
IF V_OPERATOR = '+'THEN
Dbms_output.put_line (TO_NUMBER (V_NUM1 + V_NUM2) );
Oracle_10g By Naresh A K
195
SELECTIONS IN PL/SQL
Syntax:
CASE Selector
WHEN Exp1 THEN Statement1;
WHEN Exp2 THEN Statement2;
ELSE
Statement n;
END CASE;
The reserved word CASE mark the beginning of the CASE statement.
The Selector is a value that determines, which WHEN clause should be
executed associated with it.
The Else clause is optional.
The CASE statement is marked with END CASE.
The Selector is evaluated only once.
Oracle_10g By Naresh A K
196
Example1:
DECLARE
V_Grade CHAR :=UPPER('&EnterGrade');
BEGIN
CASE V_Grade
WHEN 'A' THEN
Dbms_output.put_line ('Grade'|| ' '|| 'is' || ' '||V_Grade );
WHEN 'B' THEN
Dbms_output.put_line ('Grade'|| ' '|| 'is' || ' '||V_Grade );
WHEN 'C' THEN
Dbms_output.put_line ('Grade'|| ' '|| 'is' || ' '||V_Grade );
ELSE
Dbms_output.put_line ('NoGrade');
END CASE;
END;
SEARCHED CASE
A Searched CASE statement has search conditions that yield Boolean value
Oracle_10g By Naresh A K
197
Syntax:
CASE
WHEN SearchCondtion1 THEN Statement;
WHEN SearchCondtion1 THEN Statement;
ELSE
END CASE;
Example1:
DECLARE
V_Grade CHAR :=UPPER('&EnterGrade');
BEGIN
CASE
WHEN V_Grade = 'A' THEN
Dbms_output.put_line('Grade'|| ' '|| 'is' || ' '||V_Grade );
WHEN V_Grade = 'B' THEN
Dbms_output.put_line('Grade'|| ' '|| 'is' || ' '||V_Grade );
WHEN V_Grade = 'C' THEN
Dbms_output.put_line('Grade'|| ' '|| 'is' || ' '||V_Grade );
ELSE
Dbms_output.put_line('No Grade');
END CASE;
END;
Example2:
Oracle_10g By Naresh A K
198
DECLARE
V_Grade CHAR :=UPPER('&EnterGrade');
V_result varchar2(20);
BEGIN
v_result:=CASE
WHEN V_Grade = 'A' THEN
Dbms_output.put_line('Grade'|| ' '|| 'is' || ' '||V_Grade );
WHEN V_Grade = 'B' THEN
Dbms_output.put_line('Grade'|| ' '|| 'is' || ' '||V_Grade );
WHEN V_Grade = 'C' THEN
Dbms_output.put_line('Grade'|| ' '|| 'is' || ' '||V_Grade );
ELSE
Dbms_output.put_line('No Grade');
END CASE;
Dbms_output.put_line(v_result);
END
CASE EXPRESSION:
DECLARE
V_Number NUMBER :=&Number;
V_Result VARCHAR2(100);
BEGIN
V_Result :=CASE WHEN MOD(V_Number ,2)=0 THEN
V_Number ||'is an Even Number'
ELSE
V_Number ||'is an Odd Number'
END ;
Oracle_10g By Naresh A K
199
Dbms_output.put_line(V_Result );
END;
Syntax:
LOOP
Statements1;
---------------
-----------
EXIT;
END LOOP;
DECLARE
V_num NUMBER: = &1;
BEGIN
Oracle_10g By Naresh A K
200
LOOP
Dbms_output.put_line('The Line' ||V_num ||'Output is' ||V_num );
V_num :=V_num + 1;
EXIT statement:
Exit statement is used to terminated a LOOP.
Once the LOOP is terminated, the Control passes to the next statement after
the END LOOP.
EXIT can be issued either as an action within an IF statement or as a stand
alone statement with LOOP.
The EXIT statement should always be placed inside a LOOP.
EXIT can be associated with a WHEN clause to allow conditional terminated
of the LOOP.
A basic LOOP can contain multiple EXIT statements.
The EXIT condition can be at the top of the LOOP or at the end of the LOOP
as per Logical Convenience.
Example:2
DECLARE
V_num NUMBER := &1;
BEGIN
LOOP
Oracle_10g By Naresh A K
201
V_num :=V_num + 1;
END LOOP;
Dbms_output.put_line('The Total lines of outputs are '||to_char(V_num -1));
END;
NESTED LOOPS:
BEGIN
LOOP
END LOOP;
Dbms_output.put_line('The Total lines of outputs are '||to_char(V_num -1));
END;
simultaneously.
The overall loop terminates in declared by the outer loops EXIT WHEN
condition or EXIT condition.
Oracle_10g By Naresh A K
202
DECLARE
V_num NUMBER := &1;
BEGIN
LOOP
LOOP
EXIT WHEN V_num > 5;
Dbms_output.put_line('Inner Loop:'||V_num );
V_num :=V_num + 1;
END LOOP;
Dbms_output.put_line('Outter Loop:'||V_num );
V_num :=V_num + 1;
EXIT WHEN V_num > 10;
END LOOP;
END;
WHILE LOOP:
Syntax:
Oracle_10g By Naresh A K
203
If the condition yields NULL, the loop is bypassed and control passes to the
next statement.
Example1:
DECLARE
V_num NUMBER (2) := &1;
V_output VARCHAR2(100);
BEGIN
END;
Example2:
DECLARE
V_num NUMBER :=&EntNoForReverse;
V_output NUMBER :=0;
V_Position NUMBER ;
Oracle_10g By Naresh A K
204
BEGIN
END;
FOR LOOP:
Syntax:
Statement1;
Statement2;
END LOOP;
Reverse: It is a keyword, and caused the counter to decrement with each iteration
from the Upper bond to the Lower Bond.
Oracle_10g By Naresh A K
205
Example:
BEGIN
Dbms_output.put_line('FOR LOOP START........!');
END LOOP;
Dbms_output.put_line(V_output);
END;
Oracle_10g By Naresh A K
206
BEGIN
Dbms_output.put_line('FOR LOOP START........!');
END LOOP;
Dbms_output.put_line(V_output);
END;
BEGIN
Dbms_output.put_line('FOR LOOP START........!');
FOR i IN 1 .. V_FactNo
LOOP
V_Factorial := V_Factorial *I ;
END LOOP;
Dbms_output.put_line(V_Factorial );
END;
Oracle_10g By Naresh A K
207
BEGIN
Dbms_output.put_line('FOR LOOP START........!');
Dbms_output.put_line(V_Position );
V_Position :=NULL;
END LOOP;
END;
Data retrieval options range from basic Select statement to pattern matching
with regular expressions
Oracle_10g By Naresh A K
208
Example:
SQL > DECLARE
V_Empno NUMBER :=&EnterEmpno;
V_Ename EMP.ENAME%TYPE;
V_JOB VARCHAR2(30);
V_SAL NUMBER ;
BEGIN
SELECT Ename , job, sal INTO V_Ename, V_JOB, V_SAL
from emp where empno=V_Empno;
END;
Oracle_10g By Naresh A K
209
Syntax:
VariableName TableName.ColumnName%TYPE;
This method keeps the pl/sql program to be unaffected even when the data
types within the database are changing.
The methodology provides structural independency for the pl/sql program.
Example:
V_Empno EMP.EMPNO%TYPE:=&EnterEmpno;
V_Ename EMP.ENAME%TYPE;
V_JOB EMP.JOB%TYPE;
V_SAL EMP.SAL%TYPE;
BEGIN
SELECT Ename , job, sal INTO V_Ename, V_JOB, V_SAL
from emp where empno=V_Empno;
END;
%ROWTYPE ATTRIBUTES:
Syntax:
VariableName TableName%ROWTYPE
Oracle_10g By Naresh A K
210
ADVANTAGES:
The number and data type of the underlying database columns may not be
known.
The number and data type of the underlying databases column may change at
runtime.
It is mostly useful when retrieving a row with the Select statement.
Example:
BEGIN
SELECT * INTO v_EmpRecord
from emp where DEPTNO=V_DEPTNO;
END;
Oracle_10g By Naresh A K
211
DECLARE
V_EMPNO EMP.EMPNO%TYPE:=&EMPNO;
v_EmpRecord EMP%ROWTYPE;
BEGIN
SELECT * INTO v_EmpRecord
from emp where EMPNO=V_EMPNO;
END;
V_EMPNO EMP.EMPNO%TYPE:=&EnterEMPNO;
v_EmpRecord EMP%ROWTYPE;
BEGIN
SELECT * INTO v_EmpRecord
from emp where EMPNO=V_EMPNO ;
END;
Oracle_10g By Naresh A K
212
CURSOR IN PL/SQL
Usage: Using a Cursor , the PL/SQL program can control the Context Area,
as the SQL statement in processed.
Cursor Feature:
Allows to FETCH and Process rows returned by a Select statement, one row
at a time.
A Cursor is name, such that it can be referenced.
Cursor Types:
Cursors are broadly recognized as two types.
IMPLICIT Cursor.
EXPLICIT Cursor.
IMPLICIT Cursor
It is a cursor that is automatically declared by oracle every time an SQL
statement is executed.
The programmer cannot control or process the information is an implicit
cursor.
EXPLICIT Cursor:
Oracle_10g By Naresh A K
213
It is Cursor that is defined by the programmer within the program for any
query that returns more than one row of data.
This cursor is declared within the PL/SQL blocks, allows sequential process
of each row of the returned data.
CURSOR ATTRIBUTES:
The attributes return information about the execution of a data manipulation
statement.
Oracle_10g By Naresh A K
214
End if;
END;
As the records are retrieved into memory at the time the cursor is opened,
the data throughout the transaction has a consistent view.
After a Cursor is opened, the new or changed data is not reflected in the
Cursor result set.
EXPLICT CURSOR:
An Explicit Cursor is generated using a name with association of a Select
Statement in the Declare section.
Advantages:
Explicit Cursors provide more programmatic control for programmers.
Explicit Cursors are more efficient implementation. Hence easy to trap errors.
Explicit Cursors are designed to work with Select statements that return
more than one records at a time.
Explicit Cursors require additional steps to operate than implicit cursors.
There are Four Steps that should be performed by an Explicit Cursors.
Cursor Declaration.
Cursor Opening.
Cursor Fetching.
Cursor Closing.
DECLARE
Cursor declaration.
BEGIN
Opening of Cursor.
Fetching the Rows from Cursor.
Close Cursor
END;
Oracle_10g By Naresh A K
215
Example:
Declare
V_Deptno Dept.Deptno%Type := &GiveDeptno;
Cursor DeptCur is Select Empno, Ename, Sal, Job from EMP where
Deptno=V_Deptno;
Begin
Open DeptCur;
Fetch require cursor;
Closed DeptCur;
End;
Eample2:
DECLARE
Cursor EMPDetailsCursor is Select Empno,Ename, D.Deptno, Dname, Job, Sal
from EMP E, Dept D Where E.Deptno = D.Deptno;
V_EMPDept EMPDetailsCursor%ROWTYPE;
BEGIN
Open EMPDetailsCursor;
Fetch require cursor.
Closed EMPDetailsCursor;
END;
CURSOR LOOPS:
Cursors are generally very active with Loops to provide a way to navigate
through the Active Records Set.
Oracle_10g By Naresh A K
216
Each loop iteration advances the pointer by one record in the active set.
The Exit When statement is mandatory to be part of the LOOP;
Example:
BEGIN
Open EMPCur ;
LOOP
FETCH EMPCur INTO V_EMPcur;
EXIT WHEN EMPcur%NOTFOUND;
Dbms_Output.Put_Line (V_EMPcur.Ename ||' '||V_EMPcur.Deptno);
END LOOP;
Close EMPCur;
END;
Most applications are implemented in real time using the For Loop concept.
While using a For Loop, the Cursor does not require Explicit Open, Fetch
or Close.
The processing of the cursor is implicitly handled by the Pl/SQL .
The INDEX variable within the For Loop need not be explicitly declared.
The Cursor for Loops makes the program more compact.
Example:
Oracle_10g By Naresh A K
217
Example:
Begin
FOR EMPRecord IN (Select Ename, Deptno from EMP)
LOOP
Select Dname, Loc INTO V_Dname, V_loc from Dept Where
Deptno=EMPRecord.Deptno;
Dbms_Output.Put_Line (EMPRecord.Ename ||' '||EMPRecord.Deptno ||' '||
V_Dname ||''||V_loc);
END LOOP;
End;
Example:
SQL > DECLARE
v_Empno EMP.Empno%Type;
Oracle_10g By Naresh A K
218
V_Ename EMP.Ename%Type;
V_Sal EMP.Sal%Type;
V_Disig EMP.Job%Type;
CLOSE EMPcurs ;
End;
SQL > CREATE TABLE sample (Ename Varchar2 (20), Salary number (10,2));
END LOOP;
Oracle_10g By Naresh A K
219
Close EMPcur;
END;
Example:2
BEGIN
Open EMPcur ;
Fetch EMPcur INTO V_Ename, V_CurrentSal ,V_Job ;
WHILE EMPcur%ROWCOUNT <=V_Number AND EMPcur%FOUND
LOOP
INSERT INTO sample (Ename, Salary) VALUES (V_Ename,
V_CurrentSal );
V_LastSal :=V_CurrentSal ;
Fetch EMPcur INTO V_Ename, V_CurrentSal, V_Job;
IF V_LastSal =V_CurrentSal THEN
V_Number :=V_Number +1;
END IF;
END LOOP;
CLOSE EMPcur ;
End;
Oracle_10g By Naresh A K
220
Syntax:
Example:
Declare
Cursor EMPCur (PDeptno NUMBER, Pdesig VARCHAR2) IS
Select Empno, Ename, Job from EMP Where Deptno = V_Deptno and
Job=V_desig;
Begin
Open EMPCur (20,'ANALYST');
Loop
Fetch EMPCur INTO V_Empno, V_Ename;
EXIT When EMPCur%NOTFOUND;
Dbms_Output.Put_Line (v_Empno || ' ' ||V_Ename );
END LOOP;
CLOSE EMPcur;
End;
Oracle_10g By Naresh A K
221
Example:2
Begin
FOR I IN EMPCur (10,'CLERK')
Loop
Dbms_Output.Put_Line (I.EMPNO ||' ' ||I.ENAME);
END LOOP;
End;
POINTS TO NOTE:
Parameters allow values to be passed to a cursor when it is opened and to be
used in the query when it executes.
A parametric cursor can be opened and closed explicitly several times in a
block.
A parametric cursor returns a different active set on each occasion.
Each formal parameter is the cursor declaration must have corresponding
Actual Parameters in the Open statement.
When a cursor is opened we pass values to each parameter appositionally.
Parameter notation does not offer greater functionality but simply allows us to
specify input values easily and clearly.
The concept is more useful when the same cursor is reference repeatedly.
The values that are fetched by one cursor can be passed as a parameters to the
other cursor and make the programming more dynamic.
Oracle_10g By Naresh A K
222
v_Empno EMP.Empno%Type;
V_Ename EMP.Ename%Type;
V_Sal EMP.Sal%Type;
V_Disig EMP.Job%Type;
LOOP
CLOSE EMPcurs ;
End;
Many time while working is real time we have to lock rows define date
updating of date deletions.
The For Update Clause is the Cursor Query which is used to Lock the
Affected rows when the cursor is opened.
When For Update clause is used we need not use COMMIT as oracle server
releases locks at the end of transitions.
Syntax
The For Update clause is the last clause in the Select Statement.
If the Oracle Server cannot acquire the locks on the rows then it need to wait
indefinitely.
Oracle_10g By Naresh A K
223
Example:
Declare
Cursor EMPcur is Select Empno, Ename, Sal from EMP Where Deptno =30
FOR UPDATE OF Sal NOWAIT;
The Where CURRENT of clause is used when referencing the Current Row
from an Explicit Cursor.
The clause allows to apply UPDATES and DELETES to the row currently
being addressed, without the need to explicitly reference ROWID.
We must include the FOR UPDATE clause in the CUSOR QUERY , such that
the rows are locked on OPEN.
Example:
Begin
FOR i IN c1 LOOP
UPDATE EMP Set Sal =i .Sal * 2.0 Where CURRENT OF c1 ;
END LOOP;
Commit;
End;
Oracle_10g By Naresh A K
224
A Cursor can be constructed upon the result provided through a Sub query.
The Sub query can be an ordinary one of a correlated Sub query.
The Sub query when evaluated can provide a value on a set of value to the
statement.
END;
Oracle_10g By Naresh A K
225
EXCEPTION HANDLING
Exception handling can appear in two types;
Exception Trapping.
Exception Propagation.
EXCEPTION TRAPPING:
If an exception is raised in the executable section of the block then process the
exception to the corresponding exception handling in the exception section of
the same block.
Oracle_10g By Naresh A K
226
If the exception is successfully handled then the exception does not propagate
to the enclosing block of environment.
If exception is trapped and Handled successfully then the Pl/SQL block
terminated successfully.
EXCEPTION PROPAGATION:
TYPES OF EXCEPTION
As per PL/SQL exception are considered to be of three types
Predefined Oracle Server Errors
Non-Predefined Oracle Server Errors
User Defined Errors.
The PL/SQL programmer can program for exceptions to avoid disruption at
Runtime.
SPECIFICATIONS OF EXCEPTIONS:
Oracle SQLCODE
Exception Error Value
ACCESS_INTO_NULL ORA-06530 -6530
DUP_VAL_ON_INDEX ORA-00001 -1
Oracle_10g By Naresh A K
227
Oracle SQLCODE
Exception Error Value
INVALID_CURSOR ORA-01001 -1001
ORA-01001 -1001
INVALID_CURSOR
Oracle_10g By Naresh A K
228
The Exception handling section taps only those exceptions that are specified
and other exceptions are not trapped unless the Others exception handles is
used.
The others should be the last exception handles in the definition.
Begin the exception handling section of the block with the key word
exception.
Define several exception handler, each with its own set of actions for the
block.
When and Exceptions occurs PL/SQL processes only one handles before
leaving the block.
Place the Others clause after all other exception handling clauses.
We can have at most one Others clause.
Exceptions cannot appear in argument statements or SQL statements.
Oracle_10g By Naresh A K
229
BEGIN
gdthdhfhdfhd
EXCEPTION
WHEN NO_DATA_FOUND THEN
Statement……….
WHEN TOO_MANY_ROWS THEN
Statement……….
WHEN OTHERS THEN
Statement……….1
Statement……….2
END;
Example:1
Begin
Select Ename, Sal INTO V_Ename ,V_Sal from EMP Where Empno=&Empno;
Dbms_output.put_line('Name:'||' '||V_Ename || ' '|| 'Salary:' || ' '||V_Sal );
EXCEPTION
WHEN NO_DATA_FOUND THEN
Dbms_output.put_line('No such EMPloyee exists' );
End;
****************************************************************
Example:1
Oracle_10g By Naresh A K
230
Begin
Select Ename INTO V_Ename from EMP Where Sal=V_Sal ;
INSERT INTO Emessage (message) Values (V_Ename ||'-'||V_Sal );
EXCEPTION
WHEN NO_DATA_FOUND THEN
INSERT INTO Emessage (message) Values ('No such EMPloyee exists with
Salary' ||' ' ||V_Sal );
****************************************************************
SQL > DECLARE
V_Sal EMP.Sal%Type;
V_Ename EMP.Ename%Type;
V_Deptno EMP.Deptno%Type;
V_Job EMP.Job%Type;
Begin
Select Sal, Job, Deptno INTO V_Sal, V_Job, V_Deptno from EMP Where
Empno=&Empno;
Dbms_output.put_line (V_Deptno ||' '||V_Job ||' '||V_Sal);
DECLARE
V_Staff NUMBER(1);
BEGIN
Select count(*) INTO V_Staff from EMP Where Deptno=V_Deptno;
Dbms_output.put_line ('the total number EMPloyee in :'|| V_Deptno|| 'are'||
' ' ||V_Staff );
Oracle_10g By Naresh A K
231
EXCEPTION
WHEN VALUE_ERROR OR INVALID_NUMBER THEN
Dbms_output.put_line('Some Error');
End;
EXCEPTION
WHEN NO_DATA_FOUND THEN
Dbms_output.put_line('The replaced data is Missing');
End;
Syntax:
Declaring the Name for the Exception with in the declarative section.
Exception identifies Exception.
Associating the declared exception.
Reference the declared exception within the corresponding exception handled
Runtime.
@D:\DEMOBLD.SQL
SQL> ALTER TABLE DEPT ADD CONSTRAINT DEPT_DEPTNO_PK
PRIMARY KEY (DEPTNO);
Oracle_10g By Naresh A K
232
BEGIN
Delete from Dept Where deptno =V_Deptno ;
COMMIT;
EXCEPTION
WHEN E_EMPRemaining THEN
V_ErroCode := SQLCODE;
V_ErrMessage :=SUBSTR(SQLERRM,1,200);
--Pk.ep1(V_ErroCode, V_ErrMessage);
--Commit;
DBMS_OUTPUT.PUT_LINE ('Error code:'||V_ErroCode );
--DBMS_OUTPUT.PUT_LINE ('Error Message:'||V_ErrMessage );
-- DBMS_OUTPUT.PUT_LINE('Unable to delete as EMPloyee exist');
END;
****************************************************************
BEGIN
Delete from EMP Where Empno=V_Empno ;
DBMS_OUTPUT.PUT_LINE('EMPloyee has been deleted');
Oracle_10g By Naresh A K
233
COMMIT;
EXCEPTION
When all exception accurse we can identify the associate error code or error
message by using the function.
Based on the values of the code or message we can decide what subsequent
action to be taken base upon the error.
SQL CODE:
It return the numerical value for the internal ORACLE errors.
It an be assigned to a Number variable.
SQL ERRM:
An error number can be passed to SQLERRM
SQLERRM returns the message associated with that error number.
Oracle_10g By Naresh A K
234
V_Sal EMP.Sal%Type;
V_Ename EMP.Ename%Type;
V_Empno EMP.Empno%Type :=&EMPnumber;
V_Job EMP.Job%Type;
V_ErroCode Number;
V_ErrMessage VARCHAR2(200);
BEGIN
Select Ename, Job, Sal INTO V_Ename ,V_Job ,V_Sal from EMP Where
Empno=V_Empno ;
Dbms_output.put_line(V_Ename ||' '||V_Job ||' '||V_Sal );
EXCEPTION
WHEN OTHERS THEN
V_ErroCode := SQLCODE;
V_ErrMessage :=SUBSTR(SQLERRM,1,200);
DBMS_OUTPUT.PUT_LINE ('Error code:'||V_ErroCode );
DBMS_OUTPUT.PUT_LINE ('Error Message:'||V_ErrMessage );
END;
BEGIN
Delete from Dept Where deptno =V_Deptno ;
COMMIT;
EXCEPTION
WHEN E_EMPRemaining THEN
V_ErroCode := SQLCODE;
V_ErrMessage :=SUBSTR(SQLERRM,1,200);
DBMS_OUTPUT.PUT_LINE ('Error code:'||V_ErroCode );
Oracle_10g By Naresh A K
235
DECLARE
V_Deptno Dept.Deptno%Type:= &Deptno;
V_Dname Dept.Dname%Type:= '&Dname';
V_Loc Dept.Loc%Type:='&Loc';
BEGIN
INSERT into Dept (Deptno, Dname, Loc) Values ( V_Deptno ,V_Dname ,V_Loc);
COMMIT;
INSERT into Audittable (Modified_By, Modified_date) Values ( USER ,Sysdate );
COMMIT;
EXCEPTION
WHEN OTHERS THEN
Declare
V_ErroCode NUMBER:= SQLCODE;
V_ErrMessage VARCHAR2 (200) :=SUBSTR(SQLERRM,1,200);
Begin
Oracle_10g By Naresh A K
236
SQL> ALTER TABLE EMP ADD CONSTRAINT EMP_DEPTNO_FK FOREIGN KEY (DEPTNO)
REFERENCES DEPT (DEPTNO);
SQL> DECLARE
V_Deptno Dept.Deptno%Type: = &Deptno;
V_Dname Dept.Dname%Type := '&Dname';
V_Loc Dept.Loc%Type := '&Loc';
E_InvalidDept EXCEPTION;
BEGIN
UPDATE Dept Set Dname=V_Dname ,Loc=V_Loc Where Deptno=V_Deptno ;
IF SQL%NOTFOUND THEN
RAISE E_InvalidDept ;
END IF;
EXCEPTION
END;
EXCEPTION PROPAGATION:
DECLARE
V_TestVariable CHAR(5) := '&EnterString';
BEGIN
DBMS_OUTPUT.PUT_LINE('This is a test line');
Oracle_10g By Naresh A K
237
EXCEPTION
WHEN INVALID_NUMBER OR VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('An error is Raised');
END;
When the data is entered in the declared block if any error is raised the
EXCEPTION block cannot message that error.
For any error caused in the declarative section, the exception block cannot
handle hence we need an exception propagation standard.
BEGIN
DECLARE
V_TestVariable CHAR(5) := '&EnterString';
BEGIN
DBMS_OUTPUT.PUT_LINE('This is a test line');
EXCEPTION
WHEN INVALID_NUMBER OR VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('An error is Raised');
END;
EXCEPTION
WHEN INVALID_NUMBER OR VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('An error in the program');
END;
Oracle_10g By Naresh A K
238
Example:
Declare
E_Eception EXCEPTION;
BEGIN
Begin
RAISE E_Eception;
EXCEPTION
WHEN E_Eception THEN
RAISE;
END;
EXCEPTION
WHEN E_Eception THEN
DBMS_OUTPUT.PUT_LINE (‘an error occur');
End;
NOTE: When re-raising exception we should not supply the exception name to
the RAISE statement.
RAISE-APPLICATION-ERROR PROCEDURE:
Syntax;
Oracle_10g By Naresh A K
239
20999.
Message is the user specified message for the exception can be up to 2042
bytes.
True/False is optional Boolean parameter if true the error is placed on the state
of previous error. If false the default the error replace all previous error.
Example:
Declare
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR ( -20201,'Not a valid EMPloyee');
End;
BLOCK STRUCTURE:
Oracle_10g By Naresh A K
240
Syntax:
EXCEPTION
Exception handler………
End <Procedure Name >;
Oracle_10g By Naresh A K
241
Example:
CREATE OR REPLACE PROCEDURE mybonus As
Cursor DetpCur is Select Deptno from Dept;
Begin
For GroupBonus In DetpCur Loop
UPDATE EMP Set Sal =Sal*0.34 Where Deptno=GroupBonus.Deptno;
Dbms_output.put_line(' The Bonus information is ' ||
GroupBonus.Deptno);
End loop;
End;
EXEC MYBONUS;
Begin
mybonus;
End;
Oracle_10g By Naresh A K
242
PARAMETERS are the means to pass values to and from the calling
environments to the server.
PARAMETERS are the values that as will be processed or returned via the
Execution of the Procedure.
A PL/SQL procedure can be of three types
IN
OUT
INOUT
The Modes upon a procedure specify whether the parameters passed in READ
IN or a RECEPTACLE for what come out.
MODE: IN passes a value into the program.
It is READ ONLY value.
Best suitable for constants, literals, expressions.
Cannot be changed within program default mode.
Example:
Oracle_10g By Naresh A K
243
Mynum NUMBER(4);
BEGIN
Mynum :=num1 ;
WHILE Mynum <num2 LOOP
IF MOD(Mynum ,2)=0 THEN
Dbms_output.put_line('the Even number :'||Mynum );
END IF;
Mynum :=Mynum +1;
End loop;
End;
****************************************************************
BEGIN
Select Ename, Job into O_Ename ,O_Job from EMP Where Empno=I_Empno ;
Exception
When NO_DATA_FOUND then
Dbms_output.put_line('Ever is finding the details of EMPloyees number:'||
I_Empno );
End FindEMP;
Declare
V_Ename EMP.Ename%Type;
V_Job EMP.Job%Type;
Begin
FindEMP(7839,V_Ename ,V_Job );
Dbms_output.put_line('EMPloyee 7839 is '|| V_Ename || ' '||V_Job );
Oracle_10g By Naresh A K
244
End;
****************************************************************
NEMPloyee NUMBER:=0;
TSalary NUMBER(0);
AvgSalary NUMBER(7,2);
BEGIN
OPEN EMPinfoCur;
LOOP
FETCH EMPRecord INTO EMPinfoCur;
EXIT WHEN EMPinfoCur %NOTFOUND;
Dbms_output.put_line('EMPloyee Name:'||EMPRecord.Ename);
Dbms_output.put_line('EMPloyee Job:'||EMPRecord.Job);
Dbms_output.put_line('EMPloyee Salary:'||EMPRecord.Sal ||'
'||'Commission'||EMPRecord.comm);
Oracle_10g By Naresh A K
245
Function can accept one or may or no parameter but a function must have a
RETURN clause is the executable section of a function.
The data type of the RETURN values must be declared in the HEADER of the
function.
A function is not a stand alone executable as a procedure it has to be used
in some context.
A function has OUTPUT that needs to be assigned to a Variable or it can be
used in a Select statement.
SQL > CREATE OR REPLACE FUNCTION < function name > ( parameter l
ist) RETURN data type is
Begin
Body
RETURN ( RETURN VALUE)
END;
A function should RETURN values for all the varying possible execution
streams.
The Return statement need not appears as the first line of the main execution
section.
A function can contain more than one RETURN statement , each exception
should have a RETURN statement.
The parameters of a function can be either IN,OUT OR INOUT MODE.
Oracle_10g By Naresh A K
246
Method2 :
Declare
V_fact NUMBER(4):=0;
Begin
V_Fact :=Factorial(6);
Dbms_output.put_line('the factorial is :' ||' '|| V_fact );
End;
Example2:
BEGIN
IF LENGTH(string_in) <> 11 THEN
Oracle_10g By Naresh A K
247
RAISE incorrect;
END IF;
part1 := TO_NUMBER(SUBSTR(string_in,1,3),'999');
delim := SUBSTR(string_in,4,1);
IF delim <> '-' THEN
RAISE incorrect;
END IF;
part2 := TO_NUMBER(SUBSTR(string_in,5,2),'99');
delim := SUBSTR(string_in,7,1);
IF delim <> '-' THEN
RAISE incorrect;
END IF;
part3 := TO_NUMBER(SUBSTR(string_in,8,4),'9999');
RETURN TRUE;
EXCEPTION
WHEN incorrect THEN
RETURN FALSE;
WHEN OTHERS THEN
RETURN FALSE;
END is_socsecno;
Oracle_10g By Naresh A K
248
Oracle_10g By Naresh A K
249
This type of packages only contains global variables that will be used by
subprograms or cursors.
PACKAGE SPECIFICATION:
Example:
Oracle_10g By Naresh A K
250
Example:
Oracle_10g By Naresh A K
251
Example2:
Oracle_10g By Naresh A K
252
END MYPACK2;
Items declared in package body are private. They can only be accessed within the
package. Where as items declared in package specification is public and is available
outside package. It is explained in the following example.
Oracle_10g By Naresh A K
253
END PACK3;
SQL >
CREATE OR REPLACE PACKAGE BODY PACK3 AS
PROCEDURE EMPInfo (I_Deptno IN NUMBER) IS
Cursor EMPinfoCur is Select Ename, Job, Sal, Comm from EMP Where
Deptno=I_Deptno ;
EMPRecord EMPinfoCur%ROWTYPE;
NEMPloyee NUMBER:=0;
TSalary NUMBER;
AvgSalary NUMBER(7,2);
BEGIN
OPEN EMPinfoCur;
LOOP
FETCH EMPinfoCur INTO EMPRecord;
EXIT WHEN EMPinfoCur %NOTFOUND;
Dbms_output.put_line('EMPloyee Name:'||EMPRecord.Ename);
Dbms_output.put_line('EMPloyee Job:'||EMPRecord.Job);
Dbms_output.put_line('EMPloyee Salary:'||EMPRecord.Sal ||' '||'Commission'||
EMPRecord.comm);
Oracle_10g By Naresh A K
254
END;
END PACK3 ;
Collection Methods
A variety of methods exist for collections, but not all are relevant for every collection
type:
EXISTS(n) - Returns TRUE if the specified element exists.
COUNT - Returns the number of elements in the collection.
LIMIT - Returns the maximum number of elements for a VARRAY, or NULL
for nested tables.
FIRST - Returns the index of the first element in the collection.
LAST - Returns the index of the last element in the collection.
PRIOR(n) - Returns the index of the element prior to the specified element.
NEXT(n) - Returns the index of the next element after the specified element.
EXTEND - Appends a single null element to the collection.
EXTEND(n) - Appends n null elements to the collection.
EXTEND(n1,n2) - Appends n1 copies of the n2th element to the collection.
TRIM - Removes a single element from the end of the collection.
TRIM(n) - Removes n elements from the end of the collection.
DELETE - Removess all elements from the collection.
DELETE(n) - Removes element n from the collection.
DELETE(n1,n2) - Removes all elements from n1 to n2 from the collection.
Oracle_10g By Naresh A K
255
EXISTS(index)
Returns TRUE if the index element exists in the collection, else it returns FALSE.
Use this method to be sure you are doing a valid operation on the collection.
This method does not raise the SUBSCRIPT_OUTSIDE_LIMIT exception if used on an
element that does not exists in the collection.
If my_collection.EXISTS(10) Then
My_collection.DELETE(10) ;
End if ;
6.2 COUNT
Returns the number of elements in a collection.
LIMIT
Returns the maximum number of elements that a varray can contain.
Return NULL for Nested tables and Index-by tables
Oracle_10g By Naresh A K
256
Begin
Declare
TYPE TYP_TAB IS TABLE OF PLS_INTEGER INDEX BY VARCHAR2(1) ;
my_tab TYP_TAB ;
c Varchar2(1) ;
Begin
For i in 65 .. 69 Loop
my_tab( Chr(i) ) := i ;
End loop ;
c := my_tab.FIRST ; -- first element
Loop
Dbms_Output.Put_Line( 'my_tab(' || c || ') = ' || my_tab(c) ) ;
c := my_tab.NEXT(c) ; -- get the successor element
Exit When c IS NULL ; -- end of collection
End loop ;
End ;
Oracle_10g By Naresh A K
257
PL/SQL RECORDS:
A RECORD is a group of related data items in fields, each with its own name and
data type.
When a record type of fields in declared then they can be manipulated as a Unit.
The points to Note are:
Each record defined can have as many fields as necessarily.
Records can be assigned initial values and can be defined as NOT NULL.
Fields without initial values are initialized to NULL.
The DEFAULT keyword can also be used when defining fields.
RECORD types can be declared as user define records in the declarative part of
any block.
We can declare and reference nested records, A record can be the component of
another record.
Syntax:
To create a record, we define a record type and then declare record of that type.
Oracle_10g By Naresh A K
258
The NOT NULL constraint prevents the assigning of NULL’s to those fields.
Fields declarations are like variable declarations each fields has a Unique name and
a specific data type.
The most important point to note is we must create the data type first and the declare
an identifier using the data type.
Example:
Example:
DECLARE
V_Empno NUMBER(4):=&EnterEmpno;
EmpRecord EmpRecordType ;
BEGIN
Oracle_10g By Naresh A K
259
END;
Varrays:
Is short form for variable sized arrays. They are used to store repeating attributes
in a table. Varying arrays can be created based on standard datatypes of Oracle or
by using abstract datatypes.
A varying array take fixed number of elements when it is created, which can be
changed at runtime. The subscript used by Varrays is sequential. We have to
decide the maximum number of elements for the varying array.
Creating VARRAYS
Below given example explains creation and usage of VARRYS. Let us consider
an organization developing multiple projects simultaneously. Each project has
few team members and these members report to a team leader. We will have a
varying array for storing members’ names. Another table is created for storing the
project details.
Oracle_10g By Naresh A K
260
Nested tables
Hold an arbitrary number of elements. They use sequential numbers as subscripts. You
can define equivalent SQL types, allowing nested tables to be stored in database tables
and manipulated through SQL.
Declarations
TYPE type_name IS TABLE OF element_type [NOT NULL];
With nested tables declared within PL/SQL, element_type can be any PL/SQL datatype except :
REF CURSOR
Nested tables declared in SQL (CREATE TYPE) have additional restrictions. They cannot use
the following element types:
q BINARY_INTEGER, PLS_INTEGER
q BOOLEAN
q LONG, LONG RAW
q NATURAL, NATURALN
q POSITIVE, POSITIVEN
q REF CURSOR
q SIGNTYPE
q STRING
Oracle_10g By Naresh A K
261
PL/SQL
Declare
TYPE TYP_NT_NUM IS TABLE OF NUMBER ;
SQL
CREATE OR REPLACE TYPE TYP_NT_NUM IS TABLE OF NUMBER ;
BEGIN
V_NUMLIST.DELETE(2);
V_NUMLIST(3):=100;
BEGIN
END LOOP;
END;
Oracle_10g By Naresh A K
262
BEGIN
SELECT ENAME bulk collect INTO V_LIST1 from emp WHERE
DEPTNO=20;
FOR i IN V_LIST1.FIRST .. V_LIST1.LAST LOOP
DBMS_OUTPUT.PUT_LINE(V_LIST1(i));
END LOOP;
END;
BEGIN
SELECT ENAME bulk collect INTO V_LIST1 from emp WHERE DEPTNO=20;
FOR i IN 1..V_LIST1.COUNT LOOP
DBMS_OUTPUT.PUT_LINE(V_LIST1(i));
END LOOP;
END;
It can also be VARCHAR2 or one of its subtypes VARCHAR, STRING, or LONG. You must
specify the length of a VARCHAR2-based key, except for LONG which is equivalent to
declaring a key type of VARCHAR2(32760).
The types RAW, LONG RAW, ROWID, CHAR, and CHARACTER are not allowed as keys for an
associative array.
Oracle_10g By Naresh A K
263
Declare
TYPE TYP_TAB_VAR IS TABLE OF VARCHAR2(50) INDEX BY BINARY_INTEGER ;
Begin
my_tab(1) := 5 ;
my_tab(2) := 10 ;
my_tab(3) := 15 ;
Introduction
BULK COLLECT
FORALL
SQL%BULK_ROWCOUNT
Updates
Oracle_10g By Naresh A K
264
Related articles.
Introduction
Oracle uses two engines to process PL/SQL code. All procedural code is handled by
the PL/SQL engine while all SQL is handled by the SQL statement executor, or SQL
engine.
There is an overhead associated with each context switch between the two engines. If
PL/SQL code loops through a collection performing the same DML operation for each
item in the collection it is possible to reduce context switches by bulk binding the
whole collection to the DML statement in one operation.
In Oracle8i a collection must be defined for every column bound to the DML which can
make the code rather long winded. Oracle9i allows us to use Record structures during
bulk operations so long as we don't reference individual columns of the collection. This
restriction means that updates and deletes which have to reference inividual columns
of the collection in the where clause are still restricted to the collection-per-column
approach used in Oracle8i.
Oracle_10g By Naresh A K
265
BULK COLLECT
Bulk binds can improve the performance when loading collections from a queries.
The BULK COLLECT INTO construct binds the output of the query to the collection. To
test this create the following table.
The following code compares the time taken to populate a collection manually and
using a bulk bind.
SET SERVEROUTPUT ON
DECLARE
TYPE t_bulk_collect_test_tab IS TABLE OF bulk_collect_test
%ROWTYPE;
Oracle_10g By Naresh A K
266
SELECT *
BULK COLLECT INTO l_tab
FROM bulk_collect_test;
SQL>
We can see the improvement associated with bulk operations to reduce context
switches.
The select list must match the collections record definition exactly for this to be
successful.
Remember that collections are held in memory, so doing a bulk collect from a large
query could cause a considerable performance problem. In actual fact you would
rarely do a straight bulk collect in this manner. Instead you would limit the rows
returned using the LIMIT clause and move through the data processing smaller
chunks. This gives you the benefits of bulk binds, without hogging all the server
memory. The following code shows how to chunk through the data in a large table.
Oracle_10g By Naresh A K
267
SET SERVEROUTPUT ON
DECLARE
TYPE t_bulk_collect_test_tab IS TABLE OF bulk_collect_test
%ROWTYPE;
l_tab t_bulk_collect_test_tab;
CURSOR c_data IS
SELECT *
FROM bulk_collect_test;
BEGIN
OPEN c_data;
LOOP
FETCH c_data
BULK COLLECT INTO l_tab LIMIT 10000;
EXIT WHEN l_tab.count = 0;
Oracle_10g By Naresh A K
268
SQL>
So we can see that with a LIMIT 10000 we were able to break the data into chunks of
10,000 rows, reducing the memory footprint of our application, while still taking
advantage of bulk binds. The array size you pick will depend on the width of the rows
you are returning and the amount of memory you are happy to use.
From Oracle 10g onward, the optimizing PL/SQL compiler converts cursor FOR LOOPs
into BULK COLLECTs with an array size of 100. The following example compares the
speed of a regular cursor FOR LOOP with BULK COLLECTs using varying array sizes.
SET SERVEROUTPUT ON
DECLARE
TYPE t_bulk_collect_test_tab IS TABLE OF bulk_collect_test
%ROWTYPE;
l_tab t_bulk_collect_test_tab;
CURSOR c_data IS
SELECT *
FROM bulk_collect_test;
l_start NUMBER;
BEGIN
-- Time a regular cursor for loop.
l_start := DBMS_UTILITY.get_time;
Oracle_10g By Naresh A K
269
NULL;
END LOOP;
DBMS_OUTPUT.put_line('Regular : ' ||
(DBMS_UTILITY.get_time - l_start));
OPEN c_data;
LOOP
FETCH c_data
BULK COLLECT INTO l_tab LIMIT 10;
EXIT WHEN l_tab.count = 0;
END LOOP;
CLOSE c_data;
DBMS_OUTPUT.put_line('LIMIT 10 : ' ||
(DBMS_UTILITY.get_time - l_start));
OPEN c_data;
LOOP
FETCH c_data
BULK COLLECT INTO l_tab LIMIT 100;
EXIT WHEN l_tab.count = 0;
END LOOP;
Oracle_10g By Naresh A K
270
CLOSE c_data;
OPEN c_data;
LOOP
FETCH c_data
BULK COLLECT INTO l_tab LIMIT 1000;
EXIT WHEN l_tab.count = 0;
END LOOP;
CLOSE c_data;
SQL>
Oracle_10g By Naresh A K
271
You can see from this example the performance of a regular FOR LOOP is comparable
to a BULK COLLECT using an array size of 100. Does this mean you can forget
about BULK COLLECTin 10g onward? In my opinion no. I think it makes sense to have
control of the array size. If you have very small rows, you might want to increase the
array size substantially. If you have very wide rows, 100 may be too large an array
size.
FORALL
The FORALL syntax allows us to bind the contents of a collection to a single DML
statement, allowing the DML to be run for each row in the collection without requiring a
context switch each time. To test bulk binds using records we first create a test table.
The following test compares the time taken to insert 10,000 rows using
regular FOR..LOOP and a bulk bind.
SET SERVEROUTPUT ON
DECLARE
TYPE t_forall_test_tab IS TABLE OF forall_test%ROWTYPE;
Oracle_10g By Naresh A K
272
l_tab(l_tab.last).id := i;
l_tab(l_tab.last).code := TO_CHAR(i);
l_tab(l_tab.last).description := 'Description: ' ||
TO_CHAR(i);
END LOOP;
Oracle_10g By Naresh A K
273
COMMIT;
END;
/
Normal Inserts: 305
Bulk Inserts : 14
SQL>
The output clearly demonstrates the performance improvements you can expect to
see when using bulk binds to remove the context switches between the SQL and
PL/SQL engines.
Since no columns are specified in the insert statement the record structure of the
collection must match the table exactly.
Oracle9i Release 2 also allows updates using record definitions by using
the ROW keyword. The following example uses the ROW keyword, when doing a
comparison of normal and bulk updates.
SET SERVEROUTPUT ON
DECLARE
TYPE t_id_tab IS TABLE OF forall_test.id%TYPE;
TYPE t_forall_test_tab IS TABLE OF forall_test%ROWTYPE;
Oracle_10g By Naresh A K
274
l_id_tab(l_id_tab.last) := i;
l_tab(l_tab.last).id := i;
l_tab(l_tab.last).code := TO_CHAR(i);
l_tab(l_tab.last).description := 'Description: ' ||
TO_CHAR(i);
END LOOP;
Oracle_10g By Naresh A K
275
l_start := DBMS_UTILITY.get_time;
COMMIT;
END;
/
Normal Updates : 235
Bulk Updates : 20
SQL>
The reference to the ID column within the WHERE clause of the first update would
cause the bulk operation to fail, so the second update uses a separate collection for
the ID column. This restriction has been lifted in Oracle 11g, as documented here.
Once again, the output shows the performance improvements you can expect to see
when using bulk binds.
SQL%BULK_ROWCOUNT
The SQL%BULK_ROWCOUNT cursor attribute gives granular information about the rows
affected by each iteration of the FORALL statement. Every row in the driving collection
has a corresponding row in the SQL%BULK_ROWCOUNT cursor attribute.
Oracle_10g By Naresh A K
276
The following code creates a test table as a copy of the ALL_USERS view. It then
attempts to delete 5 rows from the table based on the contents of a collection. It then
loops through theSQL%BULK_ROWCOUNT cursor attribute looking at the number of rows
affected by each delete.
SET SERVEROUTPUT ON
DECLARE
TYPE t_array_tab IS TABLE OF VARCHAR2(30);
l_array t_array_tab := t_array_tab('NARESH', 'SYS',
'SYSTEM', 'DBSNMP',
'BANANA');
BEGIN
-- Perform bulk delete operation.
FORALL i IN l_array.first .. l_array.last
DELETE FROM bulk_rowcount_test
WHERE username = l_array(i);
Oracle_10g By Naresh A K
277
SQL>
So we can see that no rows were deleted when we performed a delete for the
username "BANANA".
The following code creates a collection with 100 rows, but sets the value of rows 50
and 51 to NULL. Since the above table does not allow nulls, these rows will result in
an exception. The SAVE EXCEPTIONS clause allows the bulk operation to continue
past any exceptions, but if any exceptions were raised in the whole operation, it will
jump to the exception handler once the operation is complete. In this case, the
exception handler just loops through the SQL%BULK_EXCEPTION cursor attribute to see
what errors occured.
Oracle_10g By Naresh A K
278
SET SERVEROUTPUT ON
DECLARE
TYPE t_tab IS TABLE OF exception_test%ROWTYPE;
ex_dml_errors EXCEPTION;
PRAGMA EXCEPTION_INIT(ex_dml_errors, -24381);
BEGIN
-- Fill the collection.
FOR i IN 1 .. 100 LOOP
l_tab.extend;
l_tab(l_tab.last).id := i;
END LOOP;
-- Cause a failure.
l_tab(50).id := NULL;
l_tab(51).id := NULL;
Oracle_10g By Naresh A K
279
l_error_count := SQL%BULK_EXCEPTIONS.count;
DBMS_OUTPUT.put_line('Number of failures: ' ||
l_error_count);
FOR i IN 1 .. l_error_count LOOP
DBMS_OUTPUT.put_line('Error: ' || i ||
' Array Index: ' || SQL%BULK_EXCEPTIONS(i).error_index
||
' Message: ' || SQLERRM(-SQL
%BULK_EXCEPTIONS(i).ERROR_CODE));
END LOOP;
END;
END;
/
Number of failures: 2
Error: 1 Array Index: 50 Message: ORA-01400: cannot insert NULL
into ()
Error: 2 Array Index: 51 Message: ORA-01400: cannot insert NULL
into ()
SQL>
As expected the errors were trapped. If we query the table we can see that 98 rows
were inserted correctly.
SELECT COUNT(*)
FROM exception_test;
COUNT(*)
----------
Oracle_10g By Naresh A K
280
98
1 row selected.
SQL>
COLLECTION POINTS:
Associative Arrays:
4. Not stored in dB
5. Not reusable.
10. Acess value from a missing subscript then it will raise not data found.
Nested Tables:
1. Unbounded
Oracle_10g By Naresh A K
281
5. Can be stored in DB
6. It is reusable
8. Dense in nature initially but they will become sparse in nature after deletions.
Varrays:
1. Bounded
4. Stored in db
5. Reusable
7. Extend is required.
Oracle_10g By Naresh A K
282
Updates
In Oracle 10g and above, the optimizing PL/SQL compiler rewrites conventional cursor for
loops to use a BULK COLLECT with a LIMIT 100, so code that previously didn't take
advantage of bulk binds may now run faster.
Oracle 10g introduced support for handling sparse collections in FORALL statements (here).
The restriction on accessing individual columns of the collection with a FORALL has been
removed in Oracle 11g (here).
Oracle_10g By Naresh A K
283
CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger with the given
name or overwrites an existing trigger with the same name.
{BEFORE | AFTER | INSTEAD OF } - This clause indicates at what time the trigger should get
fired. i.e for example: before or after updating a table. INSTEAD OF is used to create a trigger
on a view. before and after cannot be used to create a trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE} - This clause determines the triggering event.
More than one triggering events can be used together separated by OR keyword. The trigger
gets fired at all the specified triggering event.
[OF col_name] - This clause is used with update triggers. This clause is used when you want
to trigger an event only when a specific column is updated.
CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger with the given
name or overwrites an existing trigger with the same name.
[ON table_name] - This clause identifies the name of the table or view to which the trigger is
associated.
[REFERENCING OLD AS o NEW AS n] - This clause is used to reference the old and new values
of the data being changed. By default, you reference the values as :old.column_name
or :new.column_name. The reference names can also be changed from old (or new) to any
other user-defined name. You cannot reference old values when inserting a record, or new
values when deleting a record, because they do not exist.
[FOR EACH ROW] - This clause is used to determine whether a trigger must fire when each
row gets affected ( i.e. a Row Level Trigger) or just once when the entire sql statement is
executed(i.e.statement level Trigger).
WHEN (condition) - This clause is valid only for row level triggers. The trigger is fired only for
rows that satisfy the condition specified.
For Example: The price of a product changes constantly. It is important to maintain the
history of the prices of the products.
We can create a trigger to update the 'product_price_history' table when the price of the
product is updated in the 'product' table.
Oracle_10g By Naresh A K
284
4)If you ROLLBACK the transaction before committing to the database, the data inserted to
the table is also rolled back.
Oracle_10g By Naresh A K
285
3) Then AFTER row level trigger fires once for each affected row. This events will
alternates between BEFORE and AFTER row level triggers.
4) Finally the AFTER statement level trigger fires.
For Example: Let's create a table 'product_check' which we can use to store
messages when triggers are fired.
CREATE TABLE product
(Message varchar2(50),
Current_Date number(32)
);
Let's create a BEFORE and AFTER statement and row level triggers for the product
table.
1) BEFORE UPDATE, Statement Level: This trigger will insert a record into the
table 'product_check' before a sql update statement is executed, at the statement
level.
CREATE or REPLACE TRIGGER Before_Update_Stat_product
BEFORE
UPDATE ON product
Begin
Dbms_output.put_line(‘T1’);
INSERT INTO product_check
Values('Before update, statement level',10);
END;
/
2) BEFORE UPDATE, Row Level: This trigger will insert a record into the table
'product_check' before each row is updated.
CREATE or REPLACE TRIGGER Before_Upddate_Row_product
BEFORE
UPDATE ON product
FOR EACH ROW
BEGIN
INSERT INTO product_check
Values('Before update row level',sysdate);
END;
/
3) AFTER UPDATE, Statement Level: This trigger will insert a record into the
table 'product_check' after a sql update statement is executed, at the statement
level.
CREATE or REPLACE TRIGGER After_Update_Stat_product
AFTER
UPDATE ON product
BEGIN
INSERT INTO product_check
Values('After update, statement level', sysdate);
End;
/
Oracle_10g By Naresh A K
286
4) AFTER UPDATE, Row Level: This trigger will insert a record into the table
'product_check' after each row is updated.
CREATE or REPLACE TRIGGER After_Update_Row_product
AFTER
insert On product
FOR EACH ROW
BEGIN
INSERT INTO product_check
Values('After update, Row level',sysdate);
END;
/
Now lets execute a update statement on table product.
UPDATE PRODUCT SET unit_price = 800
WHERE product_id in (100,101);
Lets check the data in 'product_check' table to see the order in which the trigger is
fired.
SELECT * FROM product_check;
Mesage Current_Date
------------------------------------------------------------
The above result shows 'before update' and 'after update' row level events have
occured twice, since two records were updated. But 'before update' and 'after
update' statement level events are fired only once per sql statement.
The above rules apply similarly for INSERT and DELETE statements.
NAME Type
Oracle_10g By Naresh A K
287
--------------------------------------------------------
TRIGGER_NAME VARCHAR2(30)
TRIGGER_TYPE VARCHAR2(16)
TRIGGER_EVENT VARCHAR2(75)
TABLE_OWNER VARCHAR2(30)
BASE_OBJECT_TYPE VARCHAR2(16)
TABLE_NAME VARCHAR2(30)
COLUMN_NAME VARCHAR2(4000)
REFERENCING_NAMES VARCHAR2(128)
WHEN_CLAUSE VARCHAR2(4000)
STATUS VARCHAR2(8)
DESCRIPTION VARCHAR2(4000)
ACTION_TYPE VARCHAR2(11)
TRIGGER_BODY LONG
This view stores information about header and body of the trigger.
SELECT * FROM user_triggers WHERE trigger_name = 'Before_Update_Stat_product';
The above sql query provides the header and body of the trigger 'Before_Update_Stat_product'.
The below example shows how Trigger's can enter into cyclic cascading.
Let's consider we have two tables 'abc' and 'xyz'. Two triggers are created.
1) The INSERT Trigger, triggerA on table 'abc' issues an UPDATE on table 'xyz'.
2) The UPDATE Trigger, triggerB on table 'xyz' issues an INSERT on table 'abc'.
In such a situation, when there is a row inserted in table 'abc', triggerA fires and will
update table 'xyz'.
When the table 'xyz' is updated, triggerB fires and will insert a row in table 'abc'.
This cyclic situation continues and will enter into a infinite loop, which will crash the
database.
Oracle_10g By Naresh A K
288
Compound Triggers
If we insert into the test table, there is no guarantee of the execution order.
1 row created.
SQL>
Oracle_10g By Naresh A K
289
BEGIN
DBMS_OUTPUT.put_line('TRIGGER_FOLLOWS_TEST_TRG_1 - Executed');
END;
/
1 row created.
SQL>
Compound Triggers
A compound trigger allows code for one or more timing points for a specific object to be
combined into a single trigger. The individual timing points can share a single global
declaration section, whose state is maintained for the lifetime of the statement. Once a
statement ends, due to successful completion or an error, the trigger state is cleaned up.
In previous releases this type of functionality was only possible by defining multiple
triggers whose code and global variables were defined in a separate package, as shown
in the Mutating Table Exceptions article, but the compound trigger allows for a much
tidier solution.
The triggering actions are defined in the same way as any other DML trigger, with the
addition of the COMPOUND TRIGGER clause. The main body of the trigger is made up of an
optional global declaration section and one or more timing point sections, each of which
may contain a local declaration section whose state is not maintained.
-- Global declaration.
g_global_variable VARCHAR2(10);
BEFORE STATEMENT IS
BEGIN
NULL; -- Do something here.
END BEFORE STATEMENT;
Oracle_10g By Naresh A K
290
BEGIN
NULL; -- Do something here.
END BEFORE EACH ROW;
AFTER STATEMENT IS
BEGIN
NULL; -- Do something here.
END AFTER STATEMENT;
END <trigger-name>;
/
The following code creates a test table and a compound trigger that fires for each timing
point associated with insert, update and delete statements. The triggering actions are
logged in a PL/SQL table defined in the global declaration section. The final timing point
for each statement prints out the content of the PL/SQL table to show that the variable
state has been maintained throughout the lifetime of the statement.
-- Global declaration.
TYPE t_tab IS TABLE OF VARCHAR2(50);
l_tab t_tab := t_tab();
BEFORE STATEMENT IS
BEGIN
l_tab.extend;
CASE
WHEN INSERTING THEN
l_tab(l_tab.last) := 'BEFORE STATEMENT - INSERT';
WHEN UPDATING THEN
l_tab(l_tab.last) := 'BEFORE STATEMENT - UPDATE';
WHEN DELETING THEN
l_tab(l_tab.last) := 'BEFORE STATEMENT - DELETE';
END CASE;
END BEFORE STATEMENT;
Oracle_10g By Naresh A K
291
AFTER STATEMENT IS
BEGIN
l_tab.extend;
CASE
WHEN INSERTING THEN
l_tab(l_tab.last) := 'AFTER STATEMENT - INSERT';
WHEN UPDATING THEN
l_tab(l_tab.last) := 'AFTER STATEMENT - UPDATE';
WHEN DELETING THEN
l_tab(l_tab.last) := 'AFTER STATEMENT - DELETE';
END CASE;
END compound_trigger_test_trg;
/
Oracle_10g By Naresh A K
292
after statement is
begin
dbms_output.put_line('T9');
end after statement;
end;
By issuing several insert, update and delete statements against the test table we can see
that the compound trigger is working as expected.
1 row created.
1 row created.
2 rows updated.
2 rows deleted.
SQL>
Oracle_10g By Naresh A K
293
For a more practical use of compound triggers, we can take the example quoted in
the Mutating Table Exceptions article and replace the two triggers and the package with
a single compound trigger, as shown below.
AFTER STATEMENT IS
l_count NUMBER(10);
BEGIN
FOR i IN g_change_tab.first .. g_change_tab.last LOOP
SELECT COUNT(*)
INTO g_change_tab(i).record_count
FROM tab1;
END LOOP;
g_change_tab.delete;
END AFTER STATEMENT;
END tab1_compound_trigger;
/
From a timing point perspective, the Compound Trigger Restrictions follow very closely
with those of individual statement and row level triggers. The main point of interest here is
the control of execution order. If multiple compound triggers are defined for the same
object, their order of execution can be controlled using the FOLLOWS clause, but this cannot
be used to control execution order when both compound and regular DML triggers are
defined against a single object. In such situations it is better to stick with all DML triggers,
or all compound triggers.
Oracle_10g By Naresh A K
294
Prior to 11g, it was only possible to create triggers in the enabled state, then subsequently
disable them. Now they can be explicitly enabled or disabled at creation time, with the
enabled state as the default.
1 row created.
SQL>
1 row created.
SQL>
Oracle_10g By Naresh A K
295
There is a need to calculate the risk rating from the type of the payments and the
amount and store that in the column RISK_RATING. The following simple before
update row trigger does the job pretty well:
create or replace trigger tr_pay_risk_rating
before update
on payments
for each row
begin
dbms_output.put_line ('This is tr_pay_risk_rating');
if (:new.amount) < 1000 then
:new.risk_rating := 'LOW';
elsif (:new.amount < 10000) then
if (:new.pay_mode ='K') then
:new.risk_rating := 'MEDIUM';
else
:new.risk_rating := 'HIGH';
end if;
Oracle_10g By Naresh A K
296
else
:new.risk_rating := 'HIGH';
end if;
end;
/
Now, say someone adds another requirement: some items based on the column
RISK_RATING, PAY_MODE, etc. should be flagged for follow-up in a new column
called FOLLOW_UP. You could have modified the above trigger but it's always a good
policy to leave existing code intact and create a new trigger of the same type (before
update row) as shown below. (I have placed the dbms_output statements in the code
to show how the triggers are getting fired.)
create or replace trigger tr_pay_follow_up
before update
on payments
for each row
begin
dbms_output.put_line ('This is tr_pay_follow_up');
if (
(:new.risk_rating = 'HIGH' and :new.pay_mode =
'C')
or (:new.risk_rating = 'MEDIUM'
and :new.pay_mode = 'K')
or (substr(:new.credit_card_no,1,5) = '23456')
) then
:new.follow_up := 'Y';
else
:new.follow_up := 'N';
end if;
end;
SQL> @upd_pay
This is tr_pay_follow_up
This is tr_pay_risk_rating
1 row updated.
Oracle_10g By Naresh A K
297
What happened here? The column risk_rating is HIGH and the column pay_mode is
"C", which means the column FOLLOW_UP should have been "Y" but it's "N". Why?
To answer the question, look at the order how the triggers fired: tr_pay_follow_up fired
before tr_pay_risk_rating. The latter sets the column value as high risk. So when the
former fired, it found a null (or "N") in the risk_rating column and therefore it considers
the condition satisfied.
In this case the order of execution of triggers is very important. If tr_pay_risk_rating
does not fire before the other one, correct variables will not be set and the set up will
fail to implement the needs properly. The only possible way earlier was to place all this
logic in one code and force the execution by ordering them in the code.
In Oracle Database 11g, you can place a clause in the trigger creation script that
forces the ordering among triggers. Here is the upper portion of the trigger with the
clause:
create or replace trigger tr_pay_follow_up
before update
on payments
for each row
follows tr_pay_risk_rating
begin
... and so on ...
This clause (FOLLOWS <triggerName>) forces the trigger to fire after that specified
trigger. You can test it by running the update script you saw earlier.
SQL> @upd_pay
This is tr_pay_risk_rating
This is tr_pay_follow_up
1 row updated.
1 row selected.
Oracle_10g By Naresh A K
298
The column was properly populated, as expected. Also note the correct ordering of the
triggers that confirms what you intended to do.
Ordering of triggers allow you to reap the benefits of the modular code while making
sure they get executed in the proper sequence.
This is like saying "When an error occurs, do nothing; just ignore or pretend it never
happened and it will not happen again." If only the world were that simple! This
practice leads to potentially buggy, unstable code.
Oracle Database 11g helps a bit in that department. It has a new warning called PLW-
06009 to warn you of such a problem during compile time. Here's an example.
create or replace procedure myproc as
l_dummy varchar2(1);
begin
select dummy
into l_dummy
from dual;
exception
when OTHERS then
null;
end;
When you compile this procedure, it compiles fine without a bit of warning, just like the
good old 10g days. To enable this warning you have to set this session parameter.
SQL> alter session set plsql_warnings = 'enable:all'
2 /
Session altered.
Oracle_10g By Naresh A K
299
SQL> @others1
LINE/COL ERROR
--------
---------------------------------------------------------------
--
8/7 PLW-06009: procedure "MYPROC" OTHERS handler does not
end in
RAISE or RAISE_APPLICATION_ERROR
Basic Syntax
Check Privileges
Create Materialized View
Create Materialized View Logs
Refresh Materialized Views
Cleaning Up
Aggregations and Transformations
Considerations
Oracle_10g By Naresh A K
300
-- Pre-Built
CREATE MATERIALIZED VIEW view-name
ON PREBUILT TABLE
REFRESH [FAST | COMPLETE | FORCE ]
ON [COMMIT | DEMAND ]
[[ENABLE | DISABLE] QUERY REWRITE]
AS
SELECT ...;
The BUILD clause options are shown below.
IMMEDIATE : The materialized view is populated immediately.
DEFERRED : The materialized view is populated on the first
requested refresh.
Oracle_10g By Naresh A K
301
Check Privileges
Check the user who will own the materialized views has the
correct privileges. At minimum they will require the CREATE
MATERIALIZED VIEW privilege. If they are creating materialized
views using database links, you may want to grant them CREATE
DATABASE LINK privilege also.
CONNECT sys@db2
EXEC DBMS_MVIEW.refresh('EMP_MV');
Oracle_10g By Naresh A K
302
Oracle_10g By Naresh A K
303
BEGIN
DBMS_REFRESH.add(
name => 'ak.MINUTE_REFRESH1',
list => 'ak.EMP_MV',
lax => TRUE);
END;
/
A materialized view can be manually refreshed using the
DBMS_MVIEW package.
Oracle_10g By Naresh A K
304
Cleaning Up
CONNECT naresh/nareshak@db2
BEGIN
DBMS_REFRESH.destroy(name =>'ak.MINUTE_REFRESH');
END;
/
CONNECT naresh/nareshak@db1
DROP MATERIALIZED VIEW LOG ON ak.emp;
CONN naresh/nareshak
SET AUTOTRACE TRACE EXPLAIN
---------------------------------------------------------------
------------
| Id | Operation | Name | Rows | Bytes | Cost
(%CPU)| Time |
---------------------------------------------------------------
------------
| 0 | SELECT STATEMENT | | 3 | 21 | 4
(25)| 00:00:01 |
| 1 | HASH GROUP BY | | 3 | 21 | 4
(25)| 00:00:01 |
| 2 | TABLE ACCESS FULL| EMP | 14 | 98 | 3
(0)| 00:00:01 |
---------------------------------------------------------------
------------
Oracle_10g By Naresh A K
305
---------------------------------------------------------------
-----------------------------
| Id | Operation | Name | Rows |
Bytes | Cost (%CPU)| Time |
---------------------------------------------------------------
-----------------------------
| 0 | SELECT STATEMENT | | 3 |
21 | 3 (0)| 00:00:01 |
| 1 | MAT_VIEW REWRITE ACCESS FULL| EMP_AGGR_MV | 3 |
21 | 3 (0)| 00:00:01 |
Before using materialized views and materialized view logs,
consider the following:
Oracle_10g By Naresh A K
306
Package Name:
DBMS_REFRESH
DBMS_MVIEW
materialized view:
declare
type ref_cur is REF CURSOR;
v_ref ref_cur;
v_res emp%rowtype;
v_dept dept%rowtype;
begin
Oracle_10g By Naresh A K
307
if 1 < 5 then
open v_ref for select * from emp;
dbms_output.put_line('first cursor');
loop
fetch v_ref into v_res;
exit when v_ref%rowcount>5;
dbms_output.put_line(v_res.ename);
end loop;
close v_ref;
else
open v_ref for select * from dept;
dbms_output.put_line('second cursor');
end if;
end;
2. Can read OLD and NEW values, but cannot change them.
Oracle_10g By Naresh A K
308
);
projects_details
CREATE TABLE projects_details
(
project_id number(10) primary key,
project_name varchar2(30),
project_start_Date date,
customer_id number(10) references customer_details(customer_id)
);
If we INSERT INTO CPVIEW view directly, the database will raise the
following error :
INSERT INTO CPVIEW VALUES (1,'XYZ Enterprise','Japan',101,'Library
management',sysdate);
-- output
SQL Error: ORA-01779: cannot modify a column which maps to a non key-
preserved table
01779. 00000 - "cannot modify a column which maps to a non key-
preserved table"
*Cause: An attempt was made to insert or update columns of a join view
which
map to a non-key-preserved table.
*Action: Modify the underlying base tables directly.
Oracle_10g By Naresh A K
309
EXCEPTION
WHEN duplicate_info THEN
RAISE_APPLICATION_ERROR (
num=> -20107,
msg=> 'Duplicate customer or project id');
END T1;
Insert into view again. The INSTEAD OF trigger will be fired and insert
the data into the actual table.
INSERT INTO CPVIEW VALUES (1,'XYZ Enterprise','Japan',101,'Library
management',sysdate);
Oracle_10g By Naresh A K
310
Mutating Table Error In Oracle: occur only for “row level trigger”
create or replace trigger t1
before delete on emp
for each row
declare
begin
--update emp set sal=20 where deptno=20;
dbms_output.put_line('yes');
DECLARE
--PRAGMA AUTONOMOUS_TRANSACTION;
v_Count NUMBER;
BEGIN
Oracle_10g By Naresh A K
311
SELECT count(*)
INTO v_count
FROM EMP
WHERE deptno=30;
dbms_output.put_line(v_count);
END;
Now let is issue the update statement again and observe the
results.
JOINS:
Types of joins:
1. Simple,Equi or Normal Joins.
2. Cartisian product/Joins when the CP will Occurs.
It will occurs in two ways. First one , if you are not
following the N-1 Rule.
Second one , if you are not using the join condition in
Where clause.
Oracle_10g By Naresh A K
312
What is schema?
Collection of objects.
Oracle_10g By Naresh A K
313
Rule1 you can see the current value once you generate the
sequence.
Rule2 You can alter anything except the “Start with “ values.
create sequence s1
start with 5
increment by -1
minvalue 1
maxvalue 5
cycle
create sequence s1
start with 1
increment by 1
minvalue 1
maxvalue 5
cycle
cache 4
order; 4 is nothing but 4MB of Memory.
KA03HA2856
KA03HA2857
KA03HA2858 How to generate Alphanumeric sequence.
Oracle_10g By Naresh A K
314
WHAT IS QUERY?
1=1
1=3
Rule1 if the SQ return more than one rows then we can’t user
relation operator (= > <> < >= <=)
Rule2 we can write 0-256 innner queries.
DEPTNO SUMSAL
------ ------
30 9400
20 11375
10 8750
E1
Oracle_10g By Naresh A K
315
Security purpose.
User_synonyms
Oracle_10g By Naresh A K