0% found this document useful (0 votes)
19 views

Oracle Tutorial 11g by Naresh (1)

The document provides an extensive overview of Oracle 10g, covering its architecture, memory components, database objects, SQL statements, and PL/SQL programming. It details the Oracle instance, physical files of the database, normalization concepts, and various SQL statement categories. Additionally, it discusses the importance of database security, data integrity, and the use of SQL*Plus for database management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Oracle Tutorial 11g by Naresh (1)

The document provides an extensive overview of Oracle 10g, covering its architecture, memory components, database objects, SQL statements, and PL/SQL programming. It details the Oracle instance, physical files of the database, normalization concepts, and various SQL statement categories. Additionally, it discusses the importance of database security, data integrity, and the use of SQL*Plus for database management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 315

1

Index for Oracle 10/11g


 Oracle Architecture and Administration
 The Oracle Instance
 Memory Components of the SGA
 Starting and Stopping the Oracle Database
 Structured Query Language Statements
 DTABASE OBJECTS
 Data Types In Oracle
 Creating table statement
 Substitution Variables
 Creating an SQL Script File
 Querying the data from tables
 Column Heading Defaults
 Applying Arithmetical Operations in Select Statements
 Arithmetic Operators
 Handling NULL values
 Working with Aliases
 Literals In Oracle
 Using Literals Character Strings
 Applying Concatenation Operator ( || )
 Eliminating the Duplicate Rows From the Output
 Filtering of Records
 Logical Operators
 SQL*Plus Operators
 Ordering Information
 Single Row Function
 Multiple Row Function
 Character Manipulation Function
 Number Function
 Date Function
 Conversion Function
 Format Models
 Date Format models
 Aggregate or Group Function.
 Miscellaneous Functions
 Data Integrity In Database
 Constraints
 JOINS
 SUB Queries /Nested Select / Sub Select / Inner Select
 Hierarchical Queries
 Pseudo Columns
 Sequence (10g)/ simplified sequence expressions
 Set Operators

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

The Oracle Architecture

A database is a centralized repository of organizational data. The Oracle 10g


Database Server allows you to create, store, manage and retrieve the data in the

Oracle_10g By Naresh A K
4

database. A database administrator who is responsible for administering a


database should have a complete and thorough understanding of the architecture
of the database.

The Oracle Instance


The Oracle instance is made up of a number of memory-related components and
Background processes. The instance is the created in memory every-time the
database is started. The instance is associated to only a single database at any
time. The memory components of the Oracle Database 10g are also known as the
System Global Area(SGA).The instance and its components are configured using
a file known as the Parameter file.

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

The Physical Files of the Database


Recalling an earlier discussion, the Oracle Server is made up of the Oracle
Database and Oracle Instance. The Oracle database has a physical and a logical
structure. The physical structure of the database is made up of the operating
system files that comprise the database. All the data of the database is stored in
the physical files. Storage management is a one of the primary functions of the
database administrator. In Oracle Database 10g, there are three types of files
namely:

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.

o The database identifier and name


o Timestamp of database creation
o Tablespace names
o Names and locations of data files and online redo log files
o Current online redo log file sequence number
o Checkpoint information as and when checkpoints are made
o Begin and end of undo segments
o Redo log archive information
o Backup information generated by the recovery manager utility.
This file is size by the values specified for a number of parameters during
database creation, namely MAXLOGMEMBERS, MAXLOGFILES,

Oracle_10g By Naresh A K
8

MAXLOGHISTORY, MAXDATAFILES and MAXINSTANCES.

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

Checkpoint (CKPT) This background process is mandatory. When the contents of


the database buffer cache are transferred to the datafiles by the
DBWR background process, the event is referred to as a CHECKPOINT. When a
checkpoint occurs the Checkpoint (CKPT) background process updates the
headers of the datafiles and control files to indicate the most recent checkpoint.
This process is therefore responsible for synchronizing the database.

 As per oracle database is a collection of data in one or more files.


 The database can contain physical and Logical structures.
 Any normal application consists of :

1. Creating Structures (Table and Indexes)


2. Creating Synonyms for object Names.
3. View objects in different databases.
4. Restricting Access to the objects.

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 ?

Normalization is the process of minimizing redundancy and dependency by


organizing fields and table of a database.The main aim of Normalization is to
add,delete or modify field that can be made in a single table.

What is De-Normalization ?

Normalization is a technique used to access the data from higher to lower


normal forms of database. It is also process of introducing redundancy into a
table by incoroporating data from the related tables.

What are all the different normalizations?


The normal forms can be divided into 5 forms,and they are explained below

First Normal Form(1NF):


This should remove all the duplicate columns from the table. Creation of tables
for the related data and identification of unique columns.
Second Normal Form(2NF):
Meeting all requirements of the first normal form(1NF). Placing the subsets of
data in separate tables and Creation of relationships between the tables using
primary keys.
Third Normal Form(3NF):
This should meet all requirements of (2NF). Removing the columns which are
not dependent on primary key constraints.
Fourth Normal Form (4NF):

Meeting all the requirements of third normal form and it should not have
multi_valued deptndencies.

Fifth Normal Form(5NF):

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

entity is a consequence of its candidate keys.

Boyce-Codd Normal Form (BCNF or 3.5NF)

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.

Structured Query Language Statements

Oracle_10g By Naresh A K
12

 Oracle SQL complies with industry accepted standards.


 It allows the user to communicate with the server.
 It is efficient
 The different categories into which the SQL statement fall are:
 Data Manipulation language Statement(DML)
 INSERT ,UPDATE,DELTE,MERGE
 Data Retrieval Statement. (DRL)/DQL –data query language.
 Select
 Data Definition Language Statement(DDL)
 CREATE,ALTER,DROP,RENAME,TRUNCATE
 Transaction Control Language Statement(TCL)
 COMMIT,ROLLBACK and SAVEPOINT
 Data Control Language(DCL)
 GRANT,REVOKE

SQL*PLUS

 It provides simple interface to the oracle database.


 It supports rudimentary reporting and is the best tool for scripting.
 It provides consistent interface for :
 Retrieving data from data dictionary.
 Creating database objects.

ABOUT SQL BUFFER

 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.

CREATING AND MANAGEING TABLES.

Oracle_10g By Naresh A K
13

DATABASE OBJECTS or SCHEMA

 An oracle database can contain multiple data structures.


 The different database objects in oracle are:
 TABLE is used to store data, Basic Unit.
 VIEW logically represents subsets of data from one or more tables.
 SEQUENCE used to generate primary key values.
 INDEX it is used to improve the performance of some queries.
 SYNONYM used to give the alternate names to objects.

TABLES IN ORACLE 10g

 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.

RULES TO CREATE A TABLE

 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

 Each value in oracle is manipulated by a data type.


 The data type's values associates a fixed set of properties with the value.
 The values of one data type are different from another data type,
 The built-in data types of oracle are categorized as:
 CHARACTER DATATYPES
 NUMBER DATATYPES
 LONG AND RAW DATATYPES

Oracle_10g By Naresh A K
14

 DATETIME DATATYPES
 LARGE OBJECT DATATYPES
 ROWID DATATYPES

CHARACTER DATATYPES

 They stored character data which can be alphanumeric data


 The information can be :
 Words.
 Free-Form Text
 Database character set
 National character set.
 They are less restrictive than other data types and have very few properties.
 The data is stored in strings with byte values
 The information can belong to ASSCII character set.
 Oracle supports both single byte and Multi-byte character sets.
 The different character data types are:
 CHAR,NCHAR,VARCHAR2,NVARCHAR2

Select * from NLS_DATABASE_PARAMETERS

National language settings


NLS_LANG syntax:
NLS_LANG=Language_territory.character set
(Note the underscore between language and teritorry, and dot between teritory
and character set)
Default value: American_America.US7ASCII

Oracle supported languages


AMERICAN GERMAN NORWEGIAN
ARABIC GERMAN DIN POLISH
BENGALI GREEK PORTUGUESE
BRAZILIAN
HEBREW ROMANIAN
PORTUGUESE
BULGARIAN HINDI RUSSIAN
SIMPLIFIED
CANADIAN FRENCH HUNGARIAN
CHINESE
CATALAN ICELANDIC SLOVAK

Oracle_10g By Naresh A K
15

CROATIAN INDONESIAN SLOVENIAN


CZECH ITALIAN SPANISH
DANISH JAPANESE SWEDISH
DUTCH KOREAN TAMIL
LATIN AMERICAN
EGYPTIAN THAI
SPANISH
TRADITIONAL
ENGLISH LATVIAN
CHINESE
ESTONIAN LITHUANIAN TURKISH
FINNISH MALAY UKRAINIAN
FRENCH MEXICAN SPANISH VIETNAMESE

Oracle supported territories


ALGERIA HUNGARY PORTUGAL
AMERICA ICELAND QATAR
AUSTRALIA INDIA ROMANIA
AUSTRIA INDONESIA SAUDI ARABIA
BAHRAIN IRAQ SINGAPORE
BANGLADESH IRELAND SLOVAKIA
BELGIUM ISRAEL SLOVENIA
BRAZIL ITALY SOMALIA
BULGARIA JAPAN SOUTH AFRICA
CANADA JORDAN SPAIN
KAZAKHSTA
CATALONIA SUDAN
N

Oracle_10g By Naresh A K
16

CHINA KOREA SWEDEN


CIS KUWAIT SWITZERLAND
CROATIA LATVIA SYRIA
CYPRUS LEBANON TAIWAN
CZECH
LIBYA THAILAND
REPUBLIC
CZECHOSLOVAKI
LITHUANIA THE NETHERLANDS
A
LUXEMBOU
DENMARK TUNISIA
RG
DJIBOUTI MALAYSIA TURKEY
MAURITANI
EGYPT UKRAINE
A
ESTONIA MEXICO UNITED ARAB EMIRATES
FINLAND MOROCCO UNITED KINGDOM
NEW
FRANCE UZBEKISTAN
ZEALAND
GERMANY NORWAY VIETNAM
GREECE OMAN YEMEN
HONG KONG POLAND

Oracle_10g By Naresh A K
17

CHAR

 It specifies fixed length character string.


 The size should be specified.
 If the data is less than the original specified sized, blank pads are applied.
 The default length is 1 Byte and the Maximum is 2000 Bytes.

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

 It specifies the variable length character string.


 The minimum size is 1 Byte and maximum size is 4000 Bytes.
 It occupies only that space for which the data is supplied.

NVARCHAR2 DATATYPE

 It is first time defined in oracle 9i


 It is defined for Unicode only data.
 The minimum for the size is 1 Byte and maximum is 4000 Bytes.

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

 This data type stores variable length character strings.


 The maximum storage size is up to 2Gb.
 It is used to store very lengthy text strings.
 The length of LONG values may be limited by the memory available on the
computer.
 LONG columns can be referenced in
 Select lists.
 SET clauses of UPDATE statements.
 VALUES clauses of INSERT statements.

RESTRICTIONS FOR LONG DATATYPE

 A single table can contain only one LONG column.


 Object types cannot be created on LONG attribute.
 LONG columns cannot appear in Where clause or in integrity constraints.
 Indexes cannot be created on LONG columns.
 LONG can be returned through a functions, but not through a stored
procedure.
 It can be declared in a PL/SQL unit but cannot be referenced in SQL.

DATE & TIME DATATYPES

Oracle_10g By Naresh A K
19

 It is used to stored date and time information.


 The dates can be specified as literals, using the calendar.
 The information revealed by date is :
 CENTURY , YEAR, MONTH,DATE,HOUR,MINUTE,SECOND
 The default date format in oracle is DD-MON-YY, and is specified in
NLS_DATE_FORMAT.
 The default time accepted by oracle date is 12:00:00Am (mid night)
 The default date accepted by oracle date is the first day of the current month.
 The date range provided by oracle is January 1,4712 B.c to Dec 31,9999 A.d

TIMESTAMP DATATYPE

 It is an extension of the Date data type.


 It stores.
 DAY,MONTH,YEAR,HOUR,MINUTE,SECOND

SYNTAX: TIMESTAMP [ {Fraction-second-precision}]


 Fraction_seconds_precision optionally specifies the number of digits in
the fractional part of the second date time field
 It can be a number in the range of 0-9, with default as 6.

RAW AND LONG DATATYPES

 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.

LARGE OBJECT (LOB) DATATYPES

 The built in LOB data types are


 BLOB , CLOB, NCLOB
 These data types are stored internally.

 The BFILE is an LOB which is stored externally.


 The LOB data types can store large and unstructured data like text, image,
video and spatial data.

Oracle_10g By Naresh A K
20

 The maximum size is up to 4 GB.


 LOB columns contain Lob location, which can refer to out-of-line or in-line
LOB values.
 LOB's Selection actually returns the LOB's locator.

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

 It stores unstructured binary large objects.


 They are bit streams with no character set semantics.
 They are provided with full transactional support.

CLOB DATATYPE

 It stores single byte and multi byte character data.


 Both fixed width and variable width character sets are supported.
They are provided with full transactional support.

NCLOB DATATYPE

 It stores Unicode data using the national character set.

Creating table statement

CREATE TABLE <table_name>


(column_name1 <Datatype> (width),
column_name1 <Datatype> (width),
column_name1 <Datatype> (width)
)

Eg:

Oracle_10g By Naresh A K
21

CREATE TABLE Student


(
Stud_id NUMBER (6),
First_Name VARCHAR2(30),
Last_Name VARCHAR2 (30),
Dob DATE,
Doj DATE,
Fees NUMBER (8,2),
Gender CHAR (1)
);
CREATE TABLE Studio
(
Id NUMBER (6),
Photo BLOB,
Graphic BFILE,
Description LONG
)

DROP TABLE Student;


DROP TABLE Studio;

INSERT STATEMENT

 The INSERT statement is used to add rows to a


 Table
 Views base table.
 A partition of a partition table.
 A sub partition of a composite-partitioned table.
 An object table.
 An object view's base table.
 Insertion of data into a table can be executed in two ways.
 Conventional INSERT.
 Direct-path INSERT.
 In conventional insert statement, oracle reuses free space in the table into
which the data is being inserted and maintains referential integrity constraint.
 In direct-path INSERT, oracle appends the inserted data after existing data in
the table; the free space is not reused.

Eg:

Oracle_10g By Naresh A K
22

INSERT INTO <Table Name> (column1,column2) VALUES(value1,


value2);

Insert data into all columns of a table

INSERT INTO Student VALUES (1232,'Jon','Kumar','24-Feb-80','22-May-82',


2999,'M');

 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.

Inserting data into the required columns

INSERT INTO Student (Stud_id, First_Name, Last_Name, Doj, Gender)


VALUES (2342,'Madhu','Sapna','20-Feb-98','F');

 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.

Inserting NULL Values

 NULL values can be inserted into two ways.


 Implicit  Omit the column from the list
 Explicit  Specify the NULL keyword or specify EMPty string (' ') only
for character strings and dates.
 The targeted columns should not be set as NOT NULL constraint.

INSERT INTO Student (Stud_id, First_Name, Last_Name, Dob, Doj, Fees,


Gender)
VALUES (353,'Krishna',' ', NULL,'12-Jan-07', NULL,'M');

Oracle_10g By Naresh A K
23

Inserting Special Values

Sysdate FUNCTION

 It is a pseudo column provide by the oracle.


 The function returns the current date and time.

INSERT INTO Student (Stud_id, First_Name, DOB, Fees, Gender)


VALUES (3432,'Kumar', Sysdate, 4747,'M');

USER FUNCTION

 It is special function which records the current USER name.

INSERT INTO Students (Stud_id, First_Name, Last_Name, DOB, Fees, Gender)


VALUES (3432,'Kumar', USER, Sysdate, 4747,'M');

SUBSTITUTION VARIABLES

 These variables are used to store values tEMPorarily.


 The values can be stored temporarily through
 Single Ampersand (&)
 Double Ampersand(&&)
 The single ampersand substitution variable applies for each instance when the
SQL statement is created or executed.
 The double ampersand substitution variable is applied for all instances until
that SQL statement is existing.

INSERT INTO Student (Stud_id, First_Name, Last_Name, Dob, Fees, Gender)


VALUES (&stud_Id, '&First_Name' ,'&Last_Name', '&Dob', &fees, '&Gender');

Using double ampersand substitution variable

Oracle_10g By Naresh A K
24

INSERT INTO Student (Stud_id,First_Name, Last_Name,Dob,Fees,Gender)


VALUES (&stud_Id, '&First_Name' ,'&Last_Name', '&Dob', &&fees,
'&Gender');
CREATE AN.LST FLE:

The list file is used to save all information which performed in SQL *PLUS.
1.in SQL *PLUS
NAVIGATION: 2.FILE-SpoolSpool File
3.give the file name
4.performed all tasks.
5.now spool off.

Creating an SQL Script File

 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

SQL>SAVE c:\scripts\insert_statement.SQL REPLACE ALL

TO GET SCRIPT:
Get used to display the script file.
Sal>get E:\nitdir\ins

TO RUN SCRIPT:

Run is used to display the scrpt and run the file.


Sql>RUN E:\nitdir\ins to simple the scrpt file.
Sql>@ E:\nitdir\ins

TO OPEN THE SCRIPT FILE IN EDITOR.


Sql>ed E:\nitdir\ins

Oracle_10g By Naresh A K
25

Run the file:

SQL>RUN c:\scripts\insert_statement.SQL
SQL>@ c:\scripts\insert_statement.SQL

Querying the data from tables

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.

Retrieving Data From All Columns

SQL >Select * from EMP;


SQL >Select * from Dept;
SQL >Select * from Sal grade;

 In this the '*' is a projection operator.


 It projects data from all the columns existing in the table with all records.
 The data is displayed in a table format.

Retrieving Data From Specific Columns

SQL >Select Empno, Ename, Sal from EMP;


SQL >Select Ename, Deptno from EMP;

 The columns names need not be in the same order as table.


 The columns should be separated using comma.
 The column names can be separated into different lines within the SQL buffer.
 The casing of columns names is not important.

UPDATING THE DATA IN A TABLE


 The Updating statement is used to change the existing values in a table or in
the base table of view.

Oracle_10g By Naresh A K
26

PRE REQUISITES:

 The table must be in the own schema.


 Update object privilege should be available.

Syntax:

Update < Table_Name > SET <colum_name> = <values> Where Clause;

Example:

SQL > Update EMP set comm=NULL Where Job='CLERK';


SQL > Update EMP set Deptno=20 Where Empno=7782;
SQL > Update EMP set (Job, Deptno) = (Select Job, Deptno from EMP Where
Empno =7499) Where Empno =7698;
SQL > Update EMP set Job='ANYLYST', Sal = Sal + 100 Where Deptno=20;

UPDATING TWO COLUMNS WITH A SUB QUERY:

Sql>UPDATE emp SET job=(select job from emp where


empno=7788),sal=(select sal from emp where empno=7499) where empno=7369;

Sql> update emp set (job,dptno)=(select job,deptno from dept where


empno=7499)wher empno=7698;

Sql>update emp set deptno=(select deptno from emp where empno=7788) where
job =(select job from emp whee empno=7788);

UPDATING ROWS BASED ON ANOTHER TABLE:

Use sub queries in update statements to update rows in a table based on values
from another table.

Sql>update emp set deptno=(select deptno from dept where


dname=’ACCOUNTING’)where deptno=(select deptno from dept where
dname=’SALES’);

UPDATE DEFAULT VALUES:

Oracle_10g By Naresh A K
27

It is used to update a value in a column with default value set in the constriants.

Sql>update EMP set sal=default where ename=’FORD’;


Sql>update EMP set hiredate=default where empno=7788;

RETURNING CLAUSE:

 The Returning clause is introduced from 10g.


 It is used to return a value from an aggregated function.
 The clause can be specified for tables and for views with a single base table.

Restriction:

 Each expression must be a simple expression or a single set aggregate


function.
 It cannot be specified for multi table insert.
 It cannot be used with parallel DML or with Remote objects.
 It cannot be used to Retrieve Long Types.
 It cannot be specified upon a View upon which a instead of Trigger is defined.

SQL > VARIABLE SumSal number;


SQL > Update EMP set Sal = Sal * 1.1 Where Deptno =10 RETURNING sum
(Sal) INTO : SumSal;
SQL > PRINT SumSal;

DELETE STATEMENT:

 It is used to remove rows from:


 An unpartitioned or portioned table.
 The unpartitioned or portioned base table of a view.

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.

 SYNTAX: DELETE [FROM] <table name>[WHERE condition];

Oracle_10g By Naresh A K
28

SQL > Delete from EMP;


SQL > Delete from EMP Where Ename='SMITH';
SQL>delete from EMP where ename in (‘SMITH’,’FORD’,’JONES’);
SQL>delete from EMP where deptno= (select deptno from dept where
dname=’ACCOUNTING’);
SQL>delete from EMP p where rowid< (select max (rowed) from EMP s where
p.ename=s.ename);
SQL > Delete from EMP Where Hiredate > to_date ('01-01-1999','dd-mm-yyyy');
SQL>delete from emp where job=’SALESMAN’ AND hiredate<sysdate
returning SUM (sal)INTO:BVSAl;

How to create only the structure of a table without values?

Create table emp as select * from emp where 1=2;

MULTIPLE INSERTS:

Support to insert into more than one table at a time.


Create tables d1,d2 and d3 same as dept table strctrue.

Sql> insert all


Into d1 values (deptno)
Into d2 values (deptno)
Into d3 values (deptno)
Select deptno from dept;
Sql>insert ALL
Into d1 (deptno) values (70)
Into d2 (deptno) values (80)
Select deptno from dept where deptno=40;

CONDITONAL INSERT:

Sql> insert all


When deptno<=40 then into d1 values (deptno, dname, loc)
When deptno>40 and deptno<=30 then into d2 values
(deptno, dname, loc)
Else into d3 (deptno, loc) values (deptno, loc)
Select *from dept;

Oracle_10g By Naresh A K
29

Sql> select *from d1;


Sql> select *from d2;
Sql> select *from d3;

TRANSACTION CONTROL STATEMENT:

 Oracle server ensures data consistency based upon transaction.


 Transactions consist of DML statements that make up one consistent change
to the data.

Transaction Start and End Cases:

 A Transaction begins when the fist executable SQL statement is encountered.


 The transaction terminates when the following specifications occur.
 A commit or Roll Back is issued.
 A DDL statement issued.
 A DML statement issued.
 The user exists the SQL*Plus
 Failure of machine or system crashes.
 A DDL statement or a TCL statement is automatically committed and hence
implicitly ends a transaction.

Explicit Transaction Control Statements:

 The logic of Transaction can be controlled by using.


 COMMIT
 It ends the current transaction by making all pending data changes
permanent.
 SAVEPOINT
 It marks a save point within the current transaction.
 ROLLBACK [ TO SAVEPOINT NAME ]
 It ends the current transaction by discarding all pending data changes.

State Of Data before Commit or Rollback:

 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.

State of the Data after Commit is issued:

 Data changes are Witten to the database.


 The previous state of the data is permanently lost.
 All users can view the result s of the transaction.
 The Locks on the affected rows are released.
 All savepoints are erased.

SQL > COMMIT;


SQL > ROLLBACK;
SQL > ROLLBACK TO SAVEPOINT_NAME;
ROLLING BACK CHANGES TO A SAVE POINT:

Sql>ROLLBACK TO <SAVE POINT NAME>;

DATA DEFINITION LANGUAGE:

ALTERING THE TABLE DEFINITION:

 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

Guidelines for Adding a Column:

 A column can be ADDED or MODIFIED to a table.


 We cannot specify the location where the column can appear, it by default
becomes the last column.
 If the table contains records, before the column is added, the new column
contains Null's.

SQL > Alter table EMP ADD (updated_date date);

Modifying a Column:

 A column data type, size and Default value can be changed.


 A change to the default value affects only subsequent insertion to the table.

Guidelines to MODIFY a column:

 We can increase the width or precision of a numeric column.


 We can decrease the width of column if the column contains only NULL
values and if the table has no rows.
 We can change the data type if the column contains Null's.
 We can convert a CHAR column to the Varchar2 data type or convert
Varchar2 column to the CHAR data type if the columns contains NULL
values or if the size is not changes.
 A change to the default value of a column affects only subsequent insertions
to the table.

SQL > ALTER table EMP MODIFY (Job varchar2 (30));

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.

Guidelines to Drop Column:

 The column may or may not contain data.

Oracle_10g By Naresh A K
32

 Only one column can be dropped at a time.


 The table must have at least one column remaining in it after it is altered.
 Once a column is dropped it cannot be recovered.

SQL > Alter table EMP Drop column Job;

SET UNUSED OPTION

 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;

Drop UNUSED Columns Option:

 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.

SQL > Alter table EMP drop UNUSED column;

Dropping a Table:

 It removes the definition of the oracle table.


 The command not only drops the table but the entire database is lost alson
with the associated indexes.

Oracle_10g By Naresh A K
33

SQL > Drop table EMP;

Guidelines to Drop Table:

 The data is totally deleted from the table.


 Any views and synonyms will remain that are invalid.
 Any pending transactions are committed.
 The drop table statement once executed is irreversible.

Changing the name of the Object:

 The RENAME command can be use to change the name of a


 Table.
 View
 Sequence
 To RENAME the object we must be the owner of the object.

SQL > RENAME < old name > TO < new name >;

SQL > RENAME Dept TO Department;

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.

SQL > Truncate table < table Name>;

SQL > truncate table EMP;

APPLYING COMMENTS UPON A TABLE

Oracle_10g By Naresh A K
34

The COMMENTS command is used to ADD comments to a table or a


COLUMN or VIEW etc.
1. EACH COMMENTS CON BE UP TO 2000 BYTES.
2. THE DATTA DICTIONARY IN WHICH COMMENTS IS STROED ARE ….

*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’;

comment on column sampe1.id is 'this is id';

CREATING A TABLE FROM AN EXISTINGG TABLEE

SYNTAX:
SQL>CREATE table<table name>as select columns from table
name[wherecondition];

CREATING AN EXACT COPY

SQL>CREATE table temp as select *from EMP;

CREATEING AN EXACT COPY WITH DIFFERENT AND REQUIRED


COLUMN NAMES

SQL>CREATE table temp1 (ecode, name, basic, deptno) as select emno, ename,
sal, deptno from EMP;

CREATEING A COPYN WITHOUT DATA

Oracle_10g By Naresh A K
35

SQL> CREATE table temp3 as select empno “emp_num” ename “emp_name”


from emp having ‘krishna’=’oracle’;

Column Heading Defaults

 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.

Applying Arithmetical Operations in Select Statements

 Arithmetic expressions can be implemented through Select statements.


 Arithmetic expressions can be implemented to:
 Modify the way the data is displayed.
 Perform calculations
 Implement WHAT-IF scenarios.

An arithmetic expression can contain:


 Simple columns names.
 Constant numeric values.
 Arithmetic operators.

Arithmetic Operators

 The arithmetic operators can be used to create expressions on NUMBER and


DATE data.

Oracle_10g By Naresh A K
36

 The Arithmetic operators supported are:


 Additions  '+'
 Subtractions  '-'
 Multiply  ' *'
 Division  '/'
 The arithmetic operators can be used in any clause of a SQL statement ,except
the FROM clause.
 SQL*Plus ignores black spaces before and after the arithmetic operator.

SQL >Select Empno, Ename, Sal, Sal+100 from EMP;

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.

SQL >Select Empno, Ename, Sal, 12*Sal+100 from EMP;


SQL> Select Empno, Ename, Sal, (12*Sal)+100 from EMP;
SQL > Select Empno, Ename, Sal, 12*(Sal+100) from EMP;

Handling NULL values

Null: It is a value which is Unavailable, Unassigned, Unknown, and Inapplicable.


 A NULL is not same as zero or blank space.
 If a row lacks the data for a particular column, then that values is said to be
NULL or to contain NULL

SQL >Select Ename, Job, Sal, Comm from EMP;


 If any columns value is an arithmetic expression is NULL, the overall result is
also NULL.
 The above situation is termed as NULL propagation and has to be handled
very carefully.

SQL >Select Ename, Job, Sal, comm, Sal + Commfrom EMP;


SQL >Select Ename, Job, Sal, comm, 12*Sal+ Commfrom EMP;

Oracle_10g By Naresh A K
37

NVL Function
 The NVL function is used to convert a NULL values to an actual values.

Syntax: NVL (expr1, expr2)


 Expr1 is the source value of expression that may contain NULL.
 Expr2 is the target values for converting NULL.
 NVL function can be used to convert any data type, the return values is always
the same as the data type of expr1.
 The data types of the sources and destination must match.
 NVL(comm,0)
 NVL(Hiredate,'01-jun-99')
 NVL(Job,'Not Assigned')

SQL >Select Ename, Sal, comm, NVL(comm,0) from EMP;


SQL >Select Ename, Sal, comm, (Sal*12)+NVL(comm,0) from EMP;

Working with Aliases

 An alias is an alternate name given for nay oracle object.


 Aliases in oracle are to two types
 Columns alias
 Table alias
 Column alias RENAMEs a column heading.
 The column alias is specified in the Select list by declaring the alias after the
column name by using the space separator.
 Alias headings appear in Upper casing by default.
 The alias should be declared in double quotes if it is against the specifications
of naming conventions.
 The 'AS' keyword cab be used between the columns name and alias.
 An alias effectively RENAMEs the Select list item for the duration of the
query.
 An alias cannot be used, any Where clause in the Select list for operational
purpose.

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

Applying Concatenation Operator (||)

 The concatenation operator links columns to other columns, arithmetic


expression, or constant values.
 Columns on either side of the operator are combined to make a single output
column.
 The resultant column is treated as an character expression.
 The concatenation operator is represented in oracle by double pipe symbol '||'.

SQL >Select Empno || Ename|| Job Employee from EMP;


SQL > Select Empno || ' '|| Ename||' '|| Job Employee from EMP;
SQL > Select 'today'||'''s'|| ' '||'BrithDay Boy is'|| Ename from EMP;

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.

Eg: 'Employees Information'


'Manger's Specification'

Using Literals Character Strings

Oracle_10g By Naresh A K
39

 A Literal that is declared in a Select list can be a character, a Number or a


Date.
 A Literal is not a column name or a columns alias.
 A Literal is printed for each row that is retrieved by the Select statement.
 Literals Strings of Free-Form text can be included in the query a per the
requirement.
 Date and Character Literals must be enclosed within the single quotation
marks ''.
 Literals increase the readability of the output.

SQL >Select Ename ||':'||'1'||'Month Salary ='|| Sal AS Salaries from


EMP;
SQL >Select 'The Designation of '|| Ename ||'is'||Job As Designation
from EMP;
SQL >Select Dname ||'Department is Located at '||Loc from Dept;
SQL >Select Ename ||'joined the organization on' ||Hiredate from EMP;

Eliminating the Duplicate Rows from the Output

 Until it is instructed SQL*Plus displays the results of a query without


eliminating duplicate rows.
 To eliminate the duplicate rows in the result, the DISTINCT keyword is
used.
 Multiple columns can be declared after the distinct qualifier.
 The Distinct qualifier affects all the selected columns, and represents a distinct
combination of the columns.

SQL >Select distinct Deptno from EMP;


SQL >Select Distinct Job, Deptno from EMP;

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

 The Where clause can compare.


 Values in columns.
 Literal values.
 Arithmetic expression.
 Function.
 The component of a Where clause are
 Column name
 Comparison operator.
 Colum name, constant or list of values.
 The character strings and dates should be enclosed in single quotation marks.
 Character values are case sensitive and date values are format sensitive (dd-
mon-yy).
 The comparison operators are used in conditions that compare one expression
to another.
 The different comparison operator are
 =, <>, !=, > , < , >=, <=
 The format of the Where clause is Where expr operator value

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.

SQL >Select Ename, Sal, Job from EMP Where Job='MANAGER';


SQL >Select Ename, Sal, Job from EMP Where Ename='Blake';
SQL >Select Ename, Hiredate, Deptno, Sal from EMP Where Deptno=10;
SQL >Select Ename||' works in Department'|| Deptno "Employee and
Department" from EMP WHERE Deptno<> 20;
SQL >Select Ename name, Sal Basic, Sal*12 Annual from EMP Where
Sal*12>4000;

Logical Operators

 The Logical operators combine the results of two component condition to


produce a single result.
 The Logical operators provided by oracle are
 AND

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.

A TRUE FALS NUL


N E L
D

T TRUE FALS NUL


R E L
U
E

F FALS FALS FALS


A E E E
L

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.

O TRU FALS NUL


R E E L
T TRU TRUE TRU
R E E
U
E

F TRU FALS NUL


A E E L
L

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

 It returns true if the following condition is False.


 It returns false if the following condition is true.
 If the condition is Unknown, it returns Unknown.

Truth Table.

TRU FALS NUL


E E L
F TRU TRUE NUL
A E L

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);

Combination of AND and OR Operators

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

BETWEEN AND, and NOT BETWEEN AND


 This operator is used to display rows based on a range of values.
 The declared range is inclusive.
 The Lower limit should be declared first.

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';

IN Operator and NOT IN Operator

 The operator is used to test for values in a specified list


 The operator can be used upon any data type.

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');

IS NULL operator and IS NOT NULL operator

 The operator tests for NULL values.


 It is the only operator that can be used to test for NULL's

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

LIKE operator and NOT LIKE operator

 The LIKE operator is used to search for a matching character.


 The character pattern matching operation is referred as a wild card search.
 The available wild cards in oracle are
 '%'  used to represent any sequence of zero or more characters.
 '-'  Represents any single character, only at the position only.
 The wild card symbols can be used in any combination with literal characters.
 For finding exact match for '%' and '-', the ESCAPE option has to be used,
which is '\' symbol with ESCAPE option.

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 '\';

Searching For Regular Expression 10g

SQL >Select Name, Phone from sample Where regexp_like (phone,'[[:punct:]]');

Ordering Information

 The order of rows returned in a query result is undefined.


 The ORDER BY clause can be used to sort the rows.
 The ORDER BY clause should be the last clause in the order of all clauses
in the Select statement.
 An expression of an alias can be specified to sort.
 Default ordering of Data is Ascending
 Number  1-999
 Dates  Earliest - Last
 Strings  A-Z; NULLS is last

 The default ordering upon a column is ascending, to change the default


ordering DESC should be used after the column name.
 Sorting can be implemented on column aliases, and can also be implemented

Oracle_10g By Naresh A K
47

jupon multiple columns.

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;

Single Row Function

 The single row functions can appear in :


 Select list
 Where clause
 START WITH clause
 CONNECT BY clause.
 The types of single row function are
 Character, Number, Date and Conversion.
 They are used to manipulate date items.
 They accept one or more arguments and return one value for each row
returned by the query.
 An argument can be :
 User supplied constant.
 Variable value.
 Column name.
 Expression.

Single Row Function Features

 Acts on each row returned in the query.


 Return one result per row.
 May return a data values of a different type than that referenced.
 May expect one or more argument.
 Can be used in Select, Where and ORDER BY clause.

Oracle_10g By Naresh A K
48

Multiple Row Function

 These functions manipulate groups of rows to give one result per group of
rows.

Specification Behavior of Functions

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.

 The function are categorized as

Oracle_10g By Naresh A K
49

 Character Manipulation Function.


 CASE conversion Function.

Character Manipulation Function

 It converts alpha character values to lower case.


 The return values has the same data type as the argument char type (CHAR or
VARCHAR2)

Syntax: LOWER (column/expression);

SQL > Select LOWER (' WELCOME TO WORLD OF COMPUTING') from


DUAL;
SQL > Select Empno, Ename, LOWER (Ename) from EMP Where
Job='CLERK';
SQL > Select Empno, Ename from EMP Where LOWER(Job)='manager';

UPPER Function
 It converts the alpha character values to upper case.
 The return value has the same data type as the argument char.

Syntax: UPPER (column/expression);

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.

Syntax: INITCAP (column/expression);

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.

Syntax: CONCAT (column/expression column/expression);

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);

SUBSTR SUB-String Function

 Returns specified characters from character value, starting from a specified


position 'm', to 'n' character long.
 Point to Remember.
 If m is 0, it is treated as 1
 If m is positive, oracle counts from the beginning of char to find the first
character.
 If m is negative, oracle counts backwards from the end of the character.
 If n is omitted.
 Oracle returns all characters to the end of char.
 If n is less than 1 or 0 then a NULL is returned.
 Floating point numbers passed as arguments to SUBSTR are automatically
converted to integers.

Syntax: SUBSTR (column/Expression, M, N);

SQL > Select SUBSTR ('ABCDEFG', 3, 4) from DUAL;


SQL > Select SUBSTR ('ABCDEFG', -5, 4) from DUAL;
SQL > Select SUBSTR ('ABCDEFG', 0, 4) from DUAL;
SQL > Select SUBSTR ('ABCDEFG', 4, 0) from DUAL;

Oracle_10g By Naresh A K
51

SQL > Select SUBSTR ('ABCDEFG', 4,-2) from DUAL;

SQL > Select Ename, Job from EMP Where SUBSTR (Job, 4,3)=UPPER('AGE');

Searching for Regular Expression:

SQL > Select regexp_substr ('123-456-7890','-[^-]+') from dual;


SQL > Select regexp_substr ('123-456-7890','-[^-]') from dual;
SQL > Select regexp_substr ('123-456-7890','-[^-]+-') from dual

Note: if you add and extras '-' at the end of the regular expression, you get the
trailing '-' as part of the returned string.

To match Semicolon with comma delimiter.

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:

'I’  Used for case -insensitive matching.


'c'  Used for case -Sensitive matching.

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

 Returns the number of characters in a value.

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.

Syntax: LENGTH (column/expression );

SQL > Select LENGTH ('naresh') from dual;


SQL > Select LENGTH (Ename) || 'characters exist in ' || INITCAP (Ename) ||'''s
Name.' AS “Names and Lengths” from EMP;
SQL > Select INITCAP (Ename), Job from EMP Where LENGTH (Job)=8;

INSTR FUNCTION

 It reruns the numeric position of a named character.

Syntax: INSTR (column/Expression, char2, n, m);

 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 INSTR ('string','r') from dual;


SQL > Select INSTR ('CARPORATE FLOOR','OR',3,2) from dual;
SQL > Select Job, INSTR (Job,' A',2,2) from EMP Where Job='MANAGER';

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

SELECT REGEXP_INSTR ('TechOnTheNet is a great resource', 't', 1, 1, 0, 'i')


FROM dual;

Regular Expression 10,11g:


Value Description

Matches the beginning of a string. If used with amatch_parameter of 'm', it


^
matches the start of a line anywhere within expression.

Matches the end of a string. If used with amatch_parameter of 'm', it matches


$
the end of a line anywhere within expression.

* Matches zero or more occurrences.

+ Matches one or more occurrences.

? Matches zero or one occurrence.

. Matches any character except NULL.

| Used like an "OR" to specify more than one alternative.

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.

() Used to group expressions as a subexpression.

{m} Matches m times.

Oracle_10g By Naresh A K
54

Value Description

{m,} Matches at least m times.

{m,n} Matches at least m times, but no more than n times.

n is a number between 1 and 9. Matches the nth subexpression found within


\n
( ) before encountering \n.

[..] Matches one collation element that can be more than one character.

[::] Matches character classes.

[==] Matches equivalence classes.

\d Matches a digit character.

\D Matches a nondigit character.

\w Matches a word character.

\W Matches a nonword character.

\s Matches a whitespace character.

\S matches a non-whitespace character.

Matches the beginning of a string or matches at the end of a string before a


\A
newline character.

\Z Matches at the end of a string.

*? Matches the preceding pattern zero or more occurrences.

Oracle_10g By Naresh A K
55

Value Description

+? Matches the preceding pattern one or more occurrences.

?? Matches the preceding pattern zero or one occurrence.

{n}? Matches the preceding pattern n times.

{n,}? Matches the preceding pattern at least n times.

{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.

Syntax: LPAD (char1, n, char2);

SQL > Select LPAD ('string',15,'*') from dual;


SQL > Select LPAD ('string',15) from dual;
SQL > Select Ename, LPAD (Ename,15,'-') from EMP Where Sal>500;

RPAD Function

 Pads the character value left justified to a total width of an character positions.
 The default padding character is space.

Syntax: RPAD (char1, n, char2 );

Oracle_10g By Naresh A K
56

SQL > Select RPAD ('string',15,'*') from dual;


SQL > Select RPAD ('string',15) from dual;
SQL > Select Ename, RPAD (Ename,15,'-') from EMP Where Sal>500;
SQL > Select Ename, LPAD (RPAD (Ename,10,'-') ,15,'-')from EMP;

LTRIM Function

 It enables to trim heading characters from a character sting.


 All the leftmost characters that appear in the set are removed.
 It will return the data until the first search fails.

Syntax: LTRIM(char1, set );

SQL > Select LTRIM ('xyxXxyLAST WORLD','xy') from Dual;


SQL > Select LTRIM (Job) from EMP Where Job LIKE 'manager';

RTRIM Function

 It enables the trimming of trailing characters from a character sting.


 All the rightmost characters that appear in the set are removed.

Syntax: RTRIM (char1, set);

SQL > Select RTRIM ('BROWSINGysXxy','xy') from Dual;


SQL > Select RTRIM (Job, 'ER') from EMP Where LTRIM (Job,'MAN') LIKE
'GER';

TRIM Function (8i)

 It enables to trim heading or trailing characters or both from a character string.


 If LEADING is specified concentrates on leading characters.
 If TRAILING is specified concentrates on trailing characters.
 If BOTH or none is specified concentrates both on leading and trailing.
 Returns the varchar2 type.

Syntax: TRIM (Leading/Trailing/Both, Trim_charecter From Trim_Source);

SQL > Select TRIM ('S' from 'MITHSS') from dual;

Oracle_10g By Naresh A K
57

SQL > Select TRIM ('S' from 'SMITHSS') from dual;


SQL > Select TRIM ('S' from 'SSMITHSS') from dual;
SQL > Select TRIM ('S' from 'MITHSS') from dual;
SQL > Select TRIM (Trailing 'S' from 'SSMITHSS') from dual;
SQL > Select TRIM (Leading'S' from 'SSMITHSS') from dual;
SQL > Select TRIM (Both 'S' from 'SSMITHSS') from dual;

CHR Function

 It returns a character having the binary equivalent to 'n'.


 It returns the equivalent for 'n' in database character set or national character
set.

Syntax: CHR (c ); CHR (n using NCHAR_CS)

SQL > Select CHR (67)|| CHR(65) sample from dual;


SQL > Select CHR (16705 using NCHAR_CS) FROM dual;
SQL >Select CHR (16 using NCHAR_CS) FROM dual;
SQL >Select CHR (167 using NCHAR_CS) FROM dual;

ASCII Function

 It returns the decimal representation in the character database set of the first
character of the char.

Syntax: ASCII (char);

SQL > Select ASCII ('A'), ASCII ('APPLE') FROM dual;


 It will return the first character of ASCII value.

Oracle_10g By Naresh A K
58

NUMBER Function

 These functions accept numeric input and return numeric values.


 Many functions return values that are accurate to 38 decimal digits.

ROUND Function

Syntax: ROUND (n, m);


 It returns n rounded to m places right of the decimal point.
 If m is omitted, n is rounded to 0 , places
 M can be negative, and rounds off the digits to the left of the decimal point.
 M must be an integer.

SQL > Select ROUND (15.193,1) from dual;


SQL > Select ROUND (15.193,-1) from dual;
SQL > Select ROUND (45.923,2) ,ROUND (45.923,0) ,ROUND (45.923,-1)
from dual;
SQL > Select ROUND (15.193) from dual;

REPLACE Function

 It returns the every occurrence of search string replaced by the replacement


string.

Oracle_10g By Naresh A K
59

 If the replacement string is omitted or NULL, all occurrences of search string


are removed.
 It substitutes one sting for another as well as to remove character stings.

Syntax: REPLACE (char1, search_string, Replace_string);

SQL > Select REPLACE ('JACK and JUE','J','BL') from dual;


SQL > Select JOB, REPLACE (Job, 'p') from EMP Where Job='PRESIDENT';

TRANSLATE Function

 Used to translate character by character in a string.

Syntax: TRANSLATE (char, from, to);

 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

Syntax: TRUNCATE (n, m);

 It returns n truncated to m decimal places.


 If M is omitted, N is truncated to 0 places.
 M can be negative to truncate M digits left to the decimal point.

SQL > Select TRUNC (15.79,1) from dual;


SQL > Select TRUNC (15.79,-1) from dual;
SQL > Select TRUNC (45.923,2) ,TRUNC (45.923,0) ,TRUNC (45.923,-1)
from dual;

Oracle_10g By Naresh A K
60

MODULUS Function

Syntax: MOD (m, n);

 It returns remainder M divided by N.


 It returns M if N is 0.

SQL > Select MOD (11,4) ,MOD(10,2) from dual;

POWER Function

Syntax: POWER (m, n);

 It returns M raised to the nth power.


 The base M and the exponent N can be any numbers.
 If M is negative, n must be an integer.

SQL > Select POWER (3,2) ,POWER (-3,2) from dual;


SQL > Select POWER (3,-2) ,POWER (-3,-2) from dual;
SQL > Select POWER (-3.5,2) ,POWER (3,-2.5) from dual;
SQL > Select POWER (-3.5,2.5) ,POWER (-3.5,-2.5) from dual;

SQUARE Function
Syntax: SQUARE (n);
 It returns square root of N.
 The value of N cannot be negative.
 SQRT returns a real result.

SQL > Select SQRT (26) from dual;

DATE FUNCTION

 Oracle stores dates in an internal numeric format.


 The dates in oracle range from January 1, 4712 BC to Dec 31,9999 AC
 The default display and input format for any date is DD-MON-YY
 The numeric format represents

Oracle_10g By Naresh A K
61

 Century, Year, Month, Day, Hours, Minutes, Seconds.

Sysdate
 It is a date function that returns current date and time.
 Sysdate is generally Selected upon a dummy table.

SQL > Select Sysdate from dual;

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.

SQL > Select Sysdate, Sysdate + 3 from dual;


SQL > Select Sysdate, Sysdate - 3 , Sysdate + 72/24 from dual;
SQL > Select Ename, Hiredate, Hiredate+ 3 from EMP;
SQL > Select Ename, Hiredate, Hiredate - 3 from EMP;
SQL > Select Ename, Hiredate, Sysdate -Hiredate from EMP;
SQL > Select Ename, Hiredate, (Sysdate -Hiredate)/7 from EMP;
SQL>Select Ename,hiredate,sysdate-hiredate “exofemps” from emp;
SQL>select ename,hiredate,round(sysdate-hiredate)/365) from emp;

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.

Eg: Select Ename, '02-aug-05' +5 from EMP;

DATE FUNCTION

ADD_MONTHS Function

Syntax: ADD_MONTHS (d, n);

Oracle_10g By Naresh A K
62

 It returns the date D plus N moths.


 The argument N can be any integer.

SQL > Select Sysdate, ADD_MONTHS (Sysdate,2) from dual;


SQL > Select Sysdate, ADD_MONTHS (Hiredate, 2) from EMP Where
Deptno=10;

MONTHS_BETWEEN Function

Syntax: MONTHS_BETWEEN (d1, d2);


 It returns number of months between dates D1 and D2.
 If D1 is later than D2, the result is positive, else negative.
 If D1 and D2 are either the same days of the months or both last days of the
months , the result is always an integer.

SQL > Select Empno, Hiredate, MONTHS_BETWEEN (Sysdate, Hiredate)


from EMP
Where months_between (Sysdate, Hiredate) <200;
SQL > Select Empno, Ename, round(months_between (Sysdate,
Hiredate)/12)”experience in years” from EMP;

NEXT_DAY Function

Syntax: NEXT_DAY (d1, char);


 It returns the date of the first weekday named by char that is later than the date
D.
 The Char must be a day of the week in the sessions date language.
 The day of the week can be full name of the abbreviation.

SQL > Select Sysdate, NEXT_Day (Sysdate, 'WED') from dual;


SQL > Select Sal, Sysdate, NEXT_Day (Sysdate, 'MONDAY') from EMP;

LAST_DAY Function

Syntax: LAST_DAY (date);


 It returns the date of the last day of the month that contains date.

Oracle_10g By Naresh A K
63

 Mostly used to determine how many days are left in the current month.

SQL > Select Sysdate, LAST_DAY (Sysdate) from dual;


SQL > Select LAST_DAY (Sysdate)-Sysdate from dual;

ROUNDING of Dates

Syntax: ROUND (date, format);


 Returns date rounded to the unit specified by the format.
 If format is omitted, date is rounded to the nearest day.

SQL > Select ROUND (Sysdate, 'DAY') from dual;


SQL > Select ROUND (Sysdate, 'MON ') from dual;
SQL > Select ROUND (Sysdate,' YEAR') from dual;
SQL >Select Hiredate, ROUND (Hiredate, 'day') from EMP;
SQL >Select Hiredate, ROUND (Hiredate, MONTH') from EMP;
SQL >Select Hiredate, ROUND (Hiredate,' YEAR') from EMP;

TRUNCATING Dates

Syntax: TRUN (date, format);


 Return date with the time portion of the day truncated to the specified unit.
 If format is omitted, date is truncated to the nearest day.

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

 Implicit data type conversion.


 Explicit data type conversion.

Implicit Data type Conversion.


 Implicit data type conversions work according to the conversion specified by
oracle.
 The assignment succeeds if the oracle server can convert the data type of the
value.
 CHAR to NUMBER conversions succeed only if the character string
represents a valid number.
 CHAR to DATE conversions succeed only if the character stings represent
the default format DD-MON-YY.

IN ASSIGNMENTS
 VARCHAR2/CHAR  NUMBER
 VARCHAR2/CHAR DATE
 NUMBER  VARCHAR2
 DATE  VARCHAR2

IN EXPRESSIONS
 VARCHAR2/CHAR NUMBER
 VARCHAR2/CHAR DATE

EXPLICIT Data Conversion


 SQL provides three functions to convert a value from one data type to another.
 The function are:
 TO_CHAR  function conversion to characters.
 TO_DATE  function conversion to dates.7
 TO_NUMBER  function conversion to numbers.

TO_CHAR Conversion Function


 This function can be used in two different flavors.
 TO_CHAR (number conversion)
 TO_CHAR (date conversion)

TO_CHAR (number conversion)

Oracle_10g By Naresh A K
65

Syntax: TO_CHAR (number, format, 'nls parameter');


 Converts Number of Number data type to a value of VARCHAR2 data type.
 Format is the optional number format, that can be used.
 The 'nlsparams' specifies the characters returned by the number format
elements.

TO_CHAR (date conversion)

Syntax: TO_CHAR (Date, Format, 'nls parameter');

 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

 A format model is a character literal that describes the format of Date or


Number data stored in a character string.

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.

SQL > Select TO_CHAR (1235,'99999D99') from dual;


SQL > Select TO_CHAR (1235,'999D99') from dual;

G(,)99G99
 Returns the specified position of the group separator.
 Multiple group separators can be specified.

SQL > Select TO_CHAR (123567,'99G99G999') from dual;


SQL > Select TO_CHAR (1235,'99G999D99') from dual;

L L99
 Returns the specified position of the local currency symbol.

Oracle_10g By Naresh A K
66

SQL > Select TO_CHAR (1235,'L99999') from dual;


SQL > Select TO_CHAR (Sal,'L999999') Currency from EMP Where Deptno
=20;
SQL > Select TO_CHAR (Sal,'L99G999D99','NLS_CURRENCY=Dollar')
Salary from EMP Where Deptno =20;

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.

SQL > Select TO_CHAR (-100000,'L9999G999D99MI') from dual;


SQL > Select Sal, comm, comm-Sal, TO_CHAR (comm-Sal ,'L999999MI')
from EMP Where Deptno =20;

PR  9999PR
 Returns negative value in < angle brackets>
 It can appear only as trailing declaration.

SQL > Select TO_CHAR (-100000,'L99G999D99PR') from dual;


SQL > Select Sal, comm, comm-Sal, TO_CHAR (comm-Sal ,'L999999PR')
from EMP Where Deptno =20;

RN  Return a value as Roman Number in Upper Case.


rn  Return a value as Roman Number in Lower Case.
 The value can be an integer between 1 and 3999
 C, N, D etc.

SQL > Select TO_CHAR (100,'RN'), TO_CHAR (1000,'RN') from dual;


SQL > Select Sal, TO_CHAR (Sal,'RN'), TO_CHAR (Sal, 'rn') from EMP;

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

SQL > Select TO_CHAR (1000,'S9999'), TO_CHAR (-1000,'S9999') from dual;


SQL > Select TO_CHAR (1000,'9999S'), TO_CHAR (-1000,'9999S') from dual;
SQL > Select Sal, TO_CHAR (Sal,'S999999'), TO_CHAR (Sal, '999999S') from
EMP;
SQL > Select Sal, comm, comm-Sal, TO_CHAR (comm-Sal,'S999999'),
TO_CHAR (comm- Sal,'999999S') from EMP Where Deptno =20;

(,)Comma  9,999
 Returns a comma in the specified position.
 Multiple commas can be specified.

SQL > Select TO_CHAR (1000,'99,999,99') from dual;


SQL > Select Sal, TO_CHAR (Sal,'99,999D99') from EMP;

(.) Period  99.99


 Returns a decimal point, at the specified position.
 Only one period can be specified in a number format model.

SQL > Select TO_CHAR (1000,'L99,999.99') from dual;


SQL > Select Sal, TO_CHAR (Sal,'L99,999.99') from EMP;

$  9999
 Return values with a leading Dollar Sign.

SQL > Select TO_CHAR (10000,'$99,999.99') from dual;


SQL > Select Sal, TO_CHAR (Sal,'$99,999.99') from EMP;

C  Cyyy
 Returns specified position of the ISO currency symbol.

SQL > Select TO_CHAR (10000,'C99,999.99') from dual;


SQL > Select Sal, TO_CHAR (Sal,'C99,999.99') from EMP;

DATE FORMAT MODELS

 The date format models can be used in the TO_CHAR function to translate a

Oracle_10g By Naresh A K
68

Date value from original format to user format.


 The total length of a date format model cannot exceed 22 characters.
 For input format models, format items cannot appear twice, and format items
that represent similar information can't be combined.
 Capitalization in a spelled out word, abbreviation, or roman numeral follow
capitalization in the corresponding format element.
 Punctuation such as hyphens, slashes, commas, periods and colons.

AD or A.D./BC or B.C.
 Indicates AD/BC with or without periods.

SQL > Select TO_CHAR (Sysdate, 'AD') from dual;


SQL > Select TO_CHAR (Sysdate,' B.C.') ,TO_CHAR (Sysdate, 'A.D.') FROM
DUAL;
SQL > Select Sal, Hiredate, TO_CHAR (Hiredate,' A.D.') from EMP;

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;

D  Day of the week (1  7)

SQL > Select TO_CHAR (Sysdate, 'D') from dual;


SQL > Select Sal, Hiredate, TO_CHAR (Hiredate,' D') from EMP;

DAY  indicates spelled name of the week Day.


 Pads to a length of 9 characters.

SQL > Select TO_CHAR (Sysdate, 'DAY') from dual;


SQL > Select Sal, Hiredate, TO_CHAR (Hiredate,' DAY') from EMP Where
TO_CHAR (Hiredate, 'DAY')='WEDNESDAY';

DD It indicates the day of month (1  31)

Oracle_10g By Naresh A K
69

SQL > Select TO_CHAR (sysdate, 'DD-DAY') from dual;


SQL > Select Sal, Hiredate, TO_CHAR (Hiredate,' DD-DAY') from EMP;

SQL > Select Sal, Hiredate, TO_CHAR (Hiredate,' DD-DAY') from EMP
Where TO_CHAR (Hiredate, 'DD-DAY')='03-WEDNESDAY';

 DAY  specifies in Upper Casing.


 Day  Specifies in Initcap Casing.
 Day  Specifies in Lower Casing.

DDD  It indicates the day of the year ( 1  366)

SQL > Select TO_CHAR (sysdate, 'DDD') from dual;


SQL > Select Sal, Hiredate, TO_CHAR (Hiredate,' DDD')from EMP Where
TO_CHAR(Hiredate, 'DAY')='WEDNESDAY';

DY  It indicates the abbreviated name of the day.

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;

YEAR  Return the spelled out year.

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 ;

Q Return the quarter of the year.

Oracle_10g By Naresh A K
70

SQL > Select Sal, Hiredate, TO_CHAR (Hiredate,' Q') from EMP
Where TO_CHAR (Hiredate, 'Q')=5;

MM Returns two digit Numeric abbreviation of the month.


SQL > Select Sal, Hiredate, TO_CHAR (Hiredate,' MM-YYYY') from EMP
Where TO_CHAR (Hiredate, 'MM')=5;

MON Returns the abbreviated name of the month.


SQL > Select Sal, Hiredate, TO_CHAR (Hiredate,' MM-MON') from EMP;

MONTH spells the name of the month padded to a length of 9 characters.


SQL > Select Sal, Hiredate, TO_CHAR (Hiredate,' MON-MONTH') from EMP;

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;

MIReturns the minutes from the given date (0-59).

SQL >
SQL > Select Sysdate, TO_CHAR (Sysdate,' HH: MI’) from dual ;

SS Returns the seconds from the given date (0-59)

SQL > Select TO_CHAR (sysdate, 'SS') from dual;


SQL > Select TO_CHAR (Sysdate, 'MI') from dual;
Select Sysdate, TO_CHAR (Sysdate,' HH: MI:SS’) from dual ;
SQL > Select Sysdate, TO_CHAR (Sysdate,' dd-mon-yy HH: MI: SS’) from
dual;

Date Format Element Suffixes

TH  specifies the ordinal number.


SQL > Select Sysdate, TO_CHAR (Sysdate,' DDTH: MONTH: YYYY’) 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;

Date format model elements restrictions


 The suffixes when added to date return value always in English.
 Date suffixes are valid only on output, hence cannot be used to insert a date
into the data base.

TO_NUMBER Function

TO_NUMBER (char, fmt, 'nlsparam');


 It converts a CHAR, value of CHAR or VARCHAR2 data type containing a
number in the format specified by the optional format model fmt, to a value of
number data type.

SQL > Select TO_NUMBER (‘$10,000.00’,’L99, 999.99’) from dual;


SQL > Select TO_NUMBER (‘$10,000.00’,’L99, 999.99’) +800 from dual;

TO_DATE Function

TO_DATE (char, fmt, 'nlsparam');


 Converts Char of CHAR or VARCHAR2 data type to a value of Date data
type.
 The fmt is a date format specifying the format of char

SQL > select to_date ('24-feb-1999','dd-mm-yyyy') from dual;


SQL > select to_date ('24-feb-1999','dd-mm-yyyy') +1 from dual;

SQL > Select Ename, Hiredate, ADD_MONTHS (TO_DATE ('17-NOV-80','DD-


MON- YY'),3) from EMP Where Hiredate='17-DEC-80';

SQL > Select Ename, Hiredate, to char (ADD_MONTHS (Hiredate,1),'DD-


MON- YYYY') from EMP Where Ename='SMITH';

Oracle_10g By Naresh A K
72

SQL > Select TRUNC (TO_DATE ('17-NOV-80','DD-MON-YY'),'YEAR') NEW


YEAR From dual;

SQL>select to_date(10,’ddd’) from dual;

SQL>select to_date(1,’w’)from dual;

SQL>select to_date(1,’ww’)from dual;

SQL> select to_char(add_months(hiredate,1),’dd-mon-yyyy’)”next month” from


emp where empno=7788;
SQL>select concat(concat(ename,’is a’),job) designation from emp where
deptno=20;

SQL>select trunk(to_date(’27-oct-92’,’dd-mon-yy’),’year’)”new year” from


dual;

SQL>selct to_char(add_months(last_day(hiredate),5),’dd-mon-yyyy’)” five


months” from emp whre empnto=7788;

SQL>select months_between(to_date(’02-02-1995’,’mm-dd-yyyy’),to_date(’02-
02-1995’,’mm-dd-yyyy’))months from dual;

SQL>select next_day(’15-mara-95’,’tuesday’)from dual;

SQL>select ename,nvl(to_char(comm.),’nto applicatble’)”commission” from


emp where deptno=30;

SQL>select round(to_date(’27-oct-92’,’dd-mon-yy’),’year’)”new year” from


dual;

SQL>select to_char(hiredate,’MONTH dd,yyyy’) from emp where


ename=’FORD’;

SQL>select ename,to_char(hiredate,’FMMonth,dd yyyy’) hiredate from emp


where deptno=20;

Oracle_10g By Naresh A K
73

SQL>select to_char(to_date(’27-oct-98’,’dd-mon-rr’),’yyyy’) year from dual;

SQL>select to_char(sysdate,’FMDDTH’)||’ of ‘||to_char(sysdate,’month’)||’ ‘||


to_char(sysdate,’yyyy’) idea from dual;

SQL>select ename,job,nvl(to_char(mgr),’supreme authority’)”managerss” from


emp order by sal desc;

AGGREAGATE or GROUP FUNCTION

 These function return a single row based on groups of rows.


 This function can appear in Select lists and HAVING clauses.
 These functions operate on sets of rows to give one result per groups.
 The sets may be the whole table or the table split into groups.

GUIDELINES TO USER GROUP FUNCTION

 DISTINCT makes the functions consider only no duplicate values.


 ALL makes the function to consider every value including duplicates.

Syntax: GROUP_FUNCTION_NAME (distinct/all/n);

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

Syntax: AVG (distinct/all/n);


 It returns the average value of n.
 It ignores Null values.

SQL > Select AVG (Sal), AVG (distinct Sal) from EMP;
SQL > Select AVG (comm), AVG (distinct comm) from EMP;

SUM FUNCTION

Syntax: SUM (distinct/all/n);


 It returns the sum of the values of n.
 It ignores Null values.

SQL > Select SUM (Sal), SUM (distinct Sal) from EMP;
SQL > Select SUM (comm), SUM (distinct comm) from EMP;

MAXIMUM FUNCTION

Syntax: MAX (distinct/all/n);


 It returns the maximum values of n.
 It ignores Null values.

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

Syntax: MIN (distinct/all/n);


 It returns the minimum values of n.
 It ignores Null values.

SQL > Select MIN (Sal), MIN (distinct Sal) from EMP;
SQL > Select MIN (comm), MIN (distinct comm) from EMP;

COUNT FUNCTION

Syntax: COUNT (*/distinct/all/n);


 It returns the number of rows in the query.
 N evaluates to something other then Null.
 If * is used returns all rows , including duplicates and Nulls'.
 It can be used to specify the count of all rows or only distinct value of N.

SQL > Select COUNT (*) from EMP;


SQL > Select COUNT (Job), COUNT (distinct Job) from EMP;
SQL > Select COUNT (Sal) ,COUNT (comm) from EMP;
SQL > Select COUNT (Empno), COUNT (distinct mgr) from EMP;

GROUP FUNCTION and NULL VLAUES

 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;

GUIDELINES TO USE GROUP BY CLAUSE

 If a group function is included in a Select clause, we should not use


individual results columns.
 The extra non group functional columns should be declared in the GROUP
BY clause.
 Using Where clause, rows can be precluded before dividing them into groups.
 Columns aliases cannot be used in GROUP BY clause.
 By default, rows are sorted by ascending order of the columns included in the
GROUP BY list.
 The columns applied upon GROUP BY clause need not be part of Select list.

Oracle_10g By Naresh A K
76

SQL > Select AVG (comm) from EMP;


SQL > Select Deptno, AVG (Sal) from EMP GROUP BY Deptno;
SQL > Select Deptno, AVG (Sal) from EMP GROUP BY Deptno ORDER BY
AVG (Sal);
SQL > Select Deptno, MIN (Sal) , MAX(Sal)from EMP GROUP BY Deptno;
SQL > Select Deptno, SUM (Sal) from EMP GROUP BY Deptno, Job;

 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;

EXCLUDING GROUPS OF RESULTS

HAVING CLAUSE
 It is used to specify which group has to display.

 Steps performed by HAVING clause:


 Rows are grouped.
 The group function is applied to the group.
 The groups that match the criteria is the HAVING clause are displayed.
 The HAVING clause can precede GROUP BY clause, but it is more logical to
declare it before GROUP BY.
 GROUP BY clause can be used, without a group function in the Select list.
 If rows are restricted based on the result of a group function, we must have
a GROUP BY clause as well as the HAVING clause.

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

SQL: GROUP BY Clause

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.

Example using the SUM function


For example, you could also use the SUM function to return the name of the
department and the total sales (in the associated department).
SELECT department, SUM(sales) as "Total sales"
FROM order_details
GROUP BY department;
Because you have listed one column in your SELECT statement that is not
encapsulated in the SUM function, you must use a GROUP BY clause. The
department field must, therefore, be listed in the GROUP BY section.

Example using the COUNT function


For example, you could use the COUNT function to return the name of the
department and the number of employees (in the associated department) that
make over $25,000 / year.
SELECT department, COUNT(*) as "Number of employees"
FROM employees
WHERE salary > 25000
GROUP BY department;

Oracle_10g By Naresh A K
78

Example using the MIN function


For example, you could also use the MIN function to return the name of each
department and the minimum salary in the department.
SELECT department, MIN(salary) as "Lowest salary"
FROM employees
GROUP BY department;

Example using the MAX function


For example, you could also use the MAX function to return the name of each
department and the maximum salary in the department.
SELECT department, MAX(salary) as "Highest salary"
FROM employees
GROUP BY department;

SQL: HAVING Clause

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

Example using the SUM function


For example, you could also use the SUM function to return the name of the
department and the total sales (in the associated department). The HAVING
clause will filter the results so that only departments with sales greater than
$1000 will be returned.
SELECT department, SUM(sales) as "Total sales"
FROM order_details
GROUP BY department
HAVING SUM(sales) > 1000;

Example using the COUNT function


For example, you could use the COUNT function to return the name of the
department and the number of employees (in the associated department) that
make over $25,000 / year. The HAVING clause will filter the results so that only
departments with more than 10 employees will be returned.
SELECT department, COUNT(*) as "Number of employees"
FROM employees
WHERE salary > 25000
GROUP BY department
HAVING COUNT(*) > 10;

Example using the MIN function


For example, you could also use the MIN function to return the name of each
department and the minimum salary in the department. The HAVING clause will
return only those departments where the starting salary is $35,000.
SELECT department, MIN(salary) as "Lowest salary"
FROM employees
GROUP BY department
HAVING MIN(salary) = 35000;

Oracle_10g By Naresh A K
80

Example using the MAX function


For example, you could also use the MAX function to return the name of each
department and the maximum salary in the department. The HAVING clause will
return only those departments whose maximum salary is less than $50,000.
SELECT department, MAX(salary) as "Highest salary"
FROM employees
GROUP BY department
HAVING MAX(salary) < 50000;

NESTING OF GROUP FUNCTION.

 Group functions can be nested to a Depth of two.

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...);

 Returns the greatest of the list of expression.


 All expression after the first are implicitly converted to data type of the first

Oracle_10g By Naresh A K
81

exp, before the comparison.


 Oracle compares the expr using no padded comparison semantics.
 Character comparison is based on the value of the character in the database
character set.

SQL > Select GREATEST ('HARRY','HARRIOT') from dual;


SQL > Select GREATEST (1000, 2000, 3000) from dual;
SQL > Select GREATEST ('10-jul-06','20-jul-06') from dual;

LEAST FUNCTION

Syntax: LEAST (Exp1, Exp2...);


 It returns the least of the list of expression.
 All expression after the first are implicitly converted to the data type of the
first expression before the comparison.

SQL > Select LEAST ('HARRY','HARRIOT') from dual;


SQL > Select LEAST (1000, 2000, 3000) from dual;
SQL > Select LEAST ('10-jul-06','20-jul-06') from dual;

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.

SQL > Select USER from dual;

UID FUNCTION
Syntax: UID
 It returns an integer that uniquely identifies the current USER.

SQL > Select UID from dual;

Oracle_10g By Naresh A K
82

USERENV FUNCTION
Syntax: USERENV
 It returns information of VARCHAR2 data type above the current session.

The values in option are:


 ISDBAreturn 'TRUE' if DBA role is enabled.
 LANGUAGE returns the language and territory used in current session.
 TERMINAL  returns the OS identifier for the current session terminal.
 SESSIONID  returns the auditing session identifier.
 ENTRYID  returns the available auditing entry identifier.
 LANG  returns the INSTANCE identification on number of the current
instance

SQL > Select USERENV ('LANG')from dual;


SQL > Select USERENV ('SESSIONID')from dual;
SQL> Select USERENV ('ISDBA')from dual;

SOUNDEX FUNCTION

Syntax: SOUNDEX (CHAR);


SQL > Select SOUNDEX (Ename) from EMP Where SOUNDEX
(Ename)=SOUNDEX ('SMYTHE');
SQL > Select SOUNDEX (Ename) from EMP Where SOUNDEX
(Job)=SOUNDEX ('CLRK');
SQL > Select Ename, JOB from EMP Where SOUNDEX (Job)=SOUNDEX
('CLRK');

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

SELECT NULLIF (20,20), NULLIF(30,40) FROM DUAL;

DATA INTEGRITY IN DTABAES.

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.

CATEGORIES OF DATA INTEGRITY.

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.

USER DEFINED INTEGRITY


 It allows to define specific business rules that do not fall into any one of the
other integrity categories.

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

 In oracle constraints can be declared in two different styles.


 Column Level: they are declared as part of the definition of an
individual column or attribute. The style is called as INLINE
specification.
 Table Level: They are declared as part of the table definition. The
style is called as OUT-OF-LINE specification.
 NOT NULL constraint should be declared as INLINE only.

Example for Column/Table level:

SQL> CREATE TABLE SAMPLE3 (ID NUMBER, NAME VARCHAR2(30)


PRIMARY KEY);
SQL> DROP TABLE SAMPLE3;

Oracle_10g By Naresh A K
85

SQL >CREATE TABLE SAMPLE3 (ID NUMBER, NAME VARCHAR2 (30),


PRIMARY KEY (ID));

 The constraints clause can appear in


 CREATE TABLE
 ALTER TABLE
 CREATE VIEW
 ALTER VIEW
 Oracle does not support CONSTRAINT on columns or attributes whose type
is.
 User defined object
 NESTED TABLES.
 VARRAY
 LOB

EXCEPTIONS:
 NOT NULL constraints are supported for a column or attribute whose type
is user-defined object VARRAY, LOB

NOT NULL CONSTRAINTS


 A NOT NULL constraint prohibits a column from containing Nulls.
 NOT NULL, should be defined using only inline specification or only at
column level.
 The default if not specified is NULL.
 To satisfy a NOT NULL constraint, every row in the table must contain a
value for the column.

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.

CREATE TABLE Students (Studno number (6) CONSTRAINT studno_nn NOT


NULL,
StuDname VARCHAR2(25) CONSTRAINT studname_nn NOT NULL,
CourcEname VARCHAR2 (25) CONSTRAINT couname_nn NOT NULL,
JoinDate DATE CONSTRAINT jdate_nn NOT NULL);

UNIQUE CONSTRAINT

Oracle_10g By Naresh A K
86

 The UNIQUE constraint designates a column as a UNIQUE key.


 A composite UNIQUE key designates a combination of column as the
UNIQUE key.
 A composite UNIQUE key is always declared at the table level or out of line.
 To satisfy a UNIQUE constraint, no two rows in the table can have the same
value for the UNIQUE key.
 UNIQUE key made up of a single column can contain NULLs.
 Oracle creates an index implicitly on the UNIQUE key column.
 For better performance it is recommended that a UNIQUE index is explicitly
created.

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.

CREATE TABLE Promotions1 (Promo_ID NUMBER (6) CONSTRAINT


promo_id_unq UNIQUE,
PromoName VARCHAR (20),
PromoCategory VARCHAR (15),
PromoCost NUMBER (10,2),
PromoBegDate DATE,
PromoEndDate DATE);

CREATE table Promotions2 (


Promo_ID NUMBER(6) ,
PromoName VARCHAR (20),
PromoCategory VARCHAR (15),
PromoCost NUMBER (10,2),
PromoBegDate DATE,
PromoEndDate DATE, CONSTRAINT promo2_id_unq UNIQUE ( promo_id)) ;

Oracle_10g By Naresh A K
87

CREATE table WareHouse


(WareHuouseId NUMBER (20),
WareHousEname VARCHAR (15),
Area NUMBER (4),DockType VARCHAR (15),
WaterAccess VARCHAR (15),
RailAccess VARCHAR (15),
Parking VARCHAR (15),
Vclearance NUMBER (3),
CONSTRAINT WareHouse_unq UNIQUE (WareHuouseId , WareHousEname));

PRIMARY KEY CONSTRAINT

 A PRIMARY key constraint designates a column as the PRIMARY key of a


table or view.
 A composite PRIMARY key designates a combination of columns as the
PRIMARY key.
 When the constraint is declare at column level or inline only PRIMARY key
keyword is enough.
 A composite PRIMARY key is always defined at table level or out of line
only.
 A PRIMARY key constraint combines a NOT NULL and UNIQUE
constraint in one declaration.

RESTRICTIONS

 A table or view can have only one PRIMARY key.


 PRIMARY key cannot be implemented on columns having.
 LOB,LONG,LONG RAW,VARRAY,NESTED
TABLE,OBJECT,BFILE,TIMESTAMP WITH TIME ZONE

 A composite PRIMARY key cannot have more than 32 columns.


 The same column or combination of columns cannot be designated both as
PRIMARY key and UNIQUE key.

Oracle_10g By Naresh A K
88

 PRIMARY key can be specified only for the top level (root) table or view.

CREATE table Location


(LoactionID NUMBER (4) CONSTRAINT loc_id_pk PRIMARY KEY,
Address VARCHAR2 (12) NOT NULL,
PostCode VARCHAR2 (12) CONSTRAINT pc_nn NOT NULL,
City VARCHAR2 (12) CONSTRAINT city_nn NOT NULL);

CREATE table Location2


(LoactionID NUMBER (4),
Address VARCHAR2 (12) NOT NULL,
PostCode VARCHAR2 (12) CONSTRAINT pc_nn NOT NULL,
City VARCHAR2 (12) CONSTRAINT city_nn NOT NULL, CONSTRAINT
LoactionID_pk PRIMARY KEY (LoactionID));

CREATE table Sales_info (ProdId NUMBER (4) , CustId NUMBER(4) ,


SaleDate DATE NOT NULL,
SalesDesc LONG NOT NULL,
CONSTRAINT prod_cust_idpk primary key (prodid, custid));

NOTE: One column can contain much number of constraints, but the column
should contain different constraints.

FOREIGN KEY CONSTRAINT

 It is also called as REFERENTIAL INTEGRITY CONSTRAINT.


 It designates a column as a foreign key and establishes a relation between the
FOREIGN key and specified PRIMARY or UNIQUE key.
 A composite FOREIGN key designates a combination of columns as the
FOREIGN key.
 The table or view containing the FOREIGN key is called the CHILD object.
 The table or view containing the REFERENCED key is called the PARENT
object.
 The FOREIGN key and the REFERENCED Key can be in the same table
or view.
 The corresponding column or columns of the FOREIGN key and the
REDERENCED key must match in order and data type.
 A FOREIGN key constraint can be defined on a single key column either inlin
or out of line.

Oracle_10g By Naresh A K
89

 A composite FOREIGN key on attributes should be declared at table level or


out of line style.
 A composite FOREIGN key constraint must refer to a composite Unique Key
or a composite Primary key in the parent table or view.
 The same column or combination of columns can be designated a both a
FOREIGN key and Primary or Unique key.
 We can designate the same column or combination of columns as both a
FOREIGN key and Primary or Unique key.

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.

SQL > CREATE TABLE HOSPITAL (


HOSPITAL_ID NUMBER (4) CONSTRAINT HOSPITAL_ID_PK PRIMARY
KEY,
HOSPITAL_NAME VARCHAR2 (13)
);

SQL > CREATE TABLE PATIENT_DETAILS (


PATIENT_ID NUMBER CONSTRAINT PATIENT_ID_PK PRIMARY KEY,
PATIENT_NAME VARCHAR2 (13),
HOSPITAL_ID NUMBER (4) REFERENCES HOSPITAL

Oracle_10g By Naresh A K
90

(HOSPITAL_ID));

SQL > INSERT INTO PATIENT_DETAILS VALUES (2345,'KUMAR',10);


SQL > INSERT INTO HOSPITALVALUES (10,’GLOBAL’);

SQL > DROP TABLE HOSPITAL;


SQL > DROP TABLE PATIENT_DETAILS ;

ONDELETE CLAUSE

 The ONDELETE clause determines how oracle automatically maintains


referential integrity if the referenced primary or unique key value is remove.
 CASCADE option can be specified if we want oracle to remove dependent
foreign key values.
 Specify SET NULL if we want oracle to convert dependent foreign key
values to NULL.
 ONDELETE clause cannot be specified for a view constraint.

EXAMPLE:1

SQL > CREATE TABLE HOSPITAL2 (HOSPITAL_ID NUMBER (4)


CONSTRAINT HOSPITAL2_ID_PK
PRIMARY KEY,
HOSPITAL_NAME VARCHAR2 (13)
);

SQL > CREATE TABLE PATIENT_DET (PATIENT_ID NUMBER


CONSTRAINT PATIENT_ID_PK11 PRIMARY KEY,PATIENT_NAME
VARCHAR2 (13) ,HOSPITAL_ID NUMBER (4) CONSTRAINT

Oracle_10g By Naresh A K
91

HOSPITAL_ID_FK11 REFERENCES HOSPITAL2(HOSPITAL_ID) ON


DELETE CASCADE) ;

SQL > INSERT INTO HOSPITAL1 VALUES (10,'GLOBAL');


SQL > INSERT INTO PATIENT_DETAILS1 VALUES (2345,'KUMAR',10);

EXAMPLE:2

SQL > Drop table department;

Create table department ( Deptno NUMBER(2) CONSTRAINT Deptno_PK


PRIMARY KEY,
Dname VARCHAR2 (20) CONSTRAINT Dname_NN NOT NULL,
Location VARCHAR2 (20));

SQL > insert into department select * from Dept Where Deptno in (10,20);

SQL > Drop table employee;

SQL > create table employee (Employee_id NUMBER (6) CONSTRAINT


emp_id_pk PRIMARY KEY,
Ename VARCHAR2 (20) CONSTRAINT Ename_NN NOT NULL,
Designation VARCHAR2 (20) ,
Manager_id NUMBER (6) CONSTRAINT mgr_id_fk_self
REFERENCES EMPLOYEE (Employee_id) ON DELETE SET NULL,
Hiredate date NOT NULL,
Salary NUMBER (7,2),
Comm NUMBER (7,2),
Deptno number (2) CONSTRAINT Dept_ID_FK REFERENCES
departmenT(Deptno) ON DELETE CASCADE);

SQL > insert into employee select * from emp Where Deptno in (10,20);

SQL > Delete from emp Where Deptno=10;

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.

SQL > Drop table department2 ;

SQL > create table department2 ( Deptno NUMBER(2) CONSTRAINT


Deptno_CH
CHECK (Deptno BETWEEN 10 AND 30),
Dname VARCHAR2(20) CONSTRAINT Dname_CH CHECK
(Dname=UPPER(Dname) )DISABLE,
Location VARCHAR2(20));

SQL > INSERT INTO department2 (Deptno) VALUES (9);

Oracle_10g By Naresh A K
93

SQL > DESC department2;

SQL > alter table department2 enable constraint Dname_CH;

SQL > INSERT INTO department2 (Dname) values ('naresh');

DEFAULT OPTION (8i)


 The DEFAULT option is given to maintain a default value in a column.
 The option prevents NULL values from entering the columns, if a row is
inserted without a value from a column.
 The DEFAULT value can be a literal , and expression or a SQL function.
 The DEFAULT expression must match the data type of the column.

SQL > Drop table sample;

SQL > CREATE TABLE SAMPLE ( NAME VARCHAR2(14),SalARY


NUMBER(7,2) DEFAULT 200);

SQL > INSERT INTO SAMPLE(NAME) VALUES ('NARESH');

SQL >SELECT * FROM SAMPLE;

Adding Constraints To a Table


 A constraint can be added to a table at any time after the table was created by
using ALTER TABLE statement, using ADD clause.

Syntax:

ALTER TABLE <Table_Name> ADD [ constraint < constraint_name> ]


cons_type (column_name);

 The constraint name syntax is optional but recommended

Oracle_10g By Naresh A K
94

GUIDELINES

 We can ADD, DROP,ENABLE, OR DISABLE a constraint , but modify the


structure.
 A NOT NULL can be added to existing column by using the Modify clause
of the ALTER table statement.
 NOT NULL can be defined only when the table contains no rows.

SQL >ALTER TABLE EMP ADD constraint EMP_mgr_fk FOREIGN KEY


(mgr) REFERENCES EMP (Empno);

DROPPING CONSTRAINTS

 To drop a constraint identify the constraint name from the


USER_CONSTRAINTS and USER_CONS_COLUMNS data dictionary /
 views.
 The ALTER table statement is use with the DROP clause.
 The CASCADE option of the DROP clause caused any dependent constraints
also to be dropped.
 When a constraint is dropped, the constraint is no longer enforced and is no
longer available in the data dictionary.

SQL > alter table PATIENT_DETAILS drop primary key CASCADE;

SQL > ALTER TABLE EMP DROP CONSTRAINT EMP_MGR_FK


CASCADE;

SQL > SELECT CONSTRAINT_NAME ,TABLE_NAME FROM


USER_CONSTRAINTS Where TABLE_NAME IN ('EMP’);

Oracle_10g By Naresh A K
95

DISABLING CONSTRAINTS

 The constraints can be disabled without dropping it or recreating it.


 The ALTER TABLE statement is used with the disable clause.

GUIDELINES

 The DISABLE clause can be used both in create table and the alter table
statement.
 The CASCADE caluse disables dependent integrity constraints.

SQL >ALTER TABLE EMP DISABLE CONATRAINT EMP_Empno_pk


CASCADE;

ENABLING CONSTAINT
 The constraints can be enabled without dropping it or re-creating it.
 The ALTER TABLE statement with the ENABLE clause.

SQL >ALTER TABLE EMP ENABLE CONATRAINT EMP_Empno_pk ;

GUIDELINES

 Enabling a constraint applies to all the data in the table.


 When an UNIQUE or PIMARY key constraint is enabled, the UNIQUE or
PIMARY index is automatically created.
 The enable clause can be used both in create table as well as alter table.

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

SQL >Select constraint_name, constraint_type, search_condition from


USER_CONSTRAINTS Where table_name='EMP';

VIWING THE COLUMNS ASSOCIATED WITH CONSTRAINT.

 The names of the columns that are involved in constraint can be known by
quering the USER_CONS_COLUMNS data dictionary view.

SQL >Select constraint_name, column_name from


USER_CONS_COLUMNS Where
table_name='DEPARTMENT2’;

*****************************************************************
**************************

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.

EquiJoins / Simple Joins / Inner Joins

 An Equijoin is a join with a join condition containing an equality operator.


 It combines row that have equivalent values for the specified columns.
 The total size of columns in the equijoin condition in a single table may be
limited to the size of a data block minus some overhead.
 The size of the data block is specified by the initialization parameter
DB_BLOCK_SIZE.

SQL > Select EMP.Empno, EMP.Ename ,EMP.Deptno, Dept.Deptno,


Dept.Dname, Dept.loc
From EMP, Dept Where EMP.Deptno=Dept.Deptno;

Oracle_10g By Naresh A K
98

Qualifying Ambiguous Columns Names

 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.

SQL >Select Empno, Ename ,Deptno, Dname, loc


From EMP, Dept Where EMP.Deptno=Dept.Deptno;

Using Table Aliases.


 Table aliases can be used instead of table names.
 A table alias gives an alternate name for the existing queried table.
 Table aliases help in keeping the SQL code smaller, hence using less memory.
 The table alias is specified in the from clause.
 To specify a tables alias, specify the table name in full followed by space and
then the table alias.

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.

SQL >Select E.Empno, E.Ename ,E.Deptno, D.Deptno, D.Dname, D.loc


From EMP E, Dept D Where E.Deptno=D.Deptno;

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 “Employee Name”, E2.Ename “Managers Name”


From EMP E1, EMP E2 Where E1.mgr=E2.Empno;

SQL >Select E1.Ename ||'''s Manager is '|| ' '||E2.Ename “Employees and
Managers “
From EMP E1, EMP E2 Where E1.mgr=E2.Empno;

Cartesian Products

 The Cartesian Products is a join query without join condition.


 During Cartesian Products oracle combines each row of one table with each
row of the other.
 It tends to generate a large number of rows and the result is rarely useful.

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

ANSI/ISO SQL Support In Oracle 9i


Oracle 9i now supports the ANSI/ISO SQL: 1999 standards. This allows easier product migration and a
reduced learning curve when cross-training, but there is no performance increase compared to the
existing syntax.

 Joins

o CROSS JOIN ---Cartision product.

o NATURAL JOIN –simple,innder,equi

o JOIN ... USING --

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

The CROSS JOIN produces a cartesian product.


ANSI/ISO Syntax Existing Syntax

SELECT ename, SELECT ename,


job, job,
dname dname
FROM emp FROM emp,
CROSS JOIN dept; dept;

NATURAL JOIN

The NATURAL JOIN performs a join for all columns with matching names in the two tables.
ANSI/ISO Syntax Existing Syntax

SELECT dname, SELECT d.department_name,


loc l.city
FROM dept FROM departments d,
NATURAL JOIN emp; locations l
WHERE d.location_id = l.location_id
AND d.country = l.country;

select e.ename,e.sal ,deptno from emp e natural join dept d

JOIN ... USING

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

SELECT dname, SELECT d.department_name,


deptno l.city
FROM emp FROM departments d,
JOIN dept USING (deptno); locations l
WHERE d.location_id = l.location_id;

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

SELECT d.dname, SELECT d.department_name,


e.ename l.city
FROM dept d FROM departments d,
JOIN emp e ON (d.deptno = e.deptno); locations l

Oracle_10g By Naresh A K
102

WHERE d.location_id = l.id;

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

SELECT employee_id, SELECT employee_id,


city, city,
department_name department_name
FROM locations l FROM locations l,
JOIN departments d ON (d.location_id departments d,
= l.location_id) employees e
JOIN employees e ON (d.department_id WHERE d.location_id =
= e.department_id); l.location_id
AND d.department_id =
e.department_id;

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

SELECT e.ename, SELECT e.last_name,


d.dname d.department_name
FROM emp e FROM employees e,
LEFT OUTER JOIN dept d ON (e.deptno departments d
= d.deptno) WHERE e.department_id =
d.department_id(+);

SELECT e.ename, SELECT e.last_name,


d.dname d.department_name
FROM emp e FROM employees e,
RIGHT OUTER JOIN dept d ON (e.deptno departments d
= d.deptno) WHERE e.department_id(+) =
d.department_id;

SELECT e.ename,e.empno,e.deptno,d.deptno , No Equivalent!


d.dname
FROM emp e
full OUTER JOIN dept d ON (e.deptno
= d.deptno);

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.

SELECT last_name, commission_pct,


(CASE commission_pct
WHEN 0.1 THEN 'Low'
WHEN 0.15 THEN 'Average'
WHEN 0.2 THEN 'High'
ELSE 'N/A'
END) Commission
FROM employees
ORDER BY last_name;

A more complex version is the Searched case expression where a comparison expression is used to
find a match.

SELECT last_name, job_id, salary,


(CASE
WHEN job_id LIKE 'SA_MAN' AND salary < 12000 THEN '10%'
WHEN job_id LIKE 'SA_MAN' AND salary >= 12000 THEN '15%'
WHEN job_id LIKE 'IT_PROG' AND salary < 9000 THEN '8%'
WHEN job_id LIKE 'IT_PROG' AND salary >= 9000 THEN '12%'
ELSE 'NOT APPLICABLE'
END) pay_raise
FROM employees;

Return values cannot be the literal NULL.

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.

SELECT NULLIF(1,1) FROM dual;

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'.

SELECT COALESCE(NULL, NULL, '3') FROM dual;


SELECT COALESCE(NULL, ‘1’, '3') FROM dual;
SELECT COALESCE(‘5’, ‘1’, '3') FROM dual;

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

 VALUES clause of an INSERT statement

 WHERE clause

 ORDER BY clause

 As a parameter of a function

For example.

INSERT INTO my_table VALUES ((SELECT 1 FROM dual), NULL);

SELECT Substr((SELECT 'ABC' FROM dual), 1, 1) FROM dual;

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:

 Default values for columns

 RETURNING clauses

 Hash expressions for clusters

 Functional index expressions

 CHECK constraints on columns

 WHEN condition of triggers

 GROUP BY and HAVING clauses

 START WITH and CONNECT BY clauses

Explicit Defaults
The DEFAULT keyword can be used to explicit assign the columns default value during an INSERT or
UPDATE statement.

INSERT INTO my_table VALUES (1, 'OWNER', DEFAULT, NULL);

UPDATE my_table SET column1 = DEFAULT;

Oracle_10g By Naresh A K
105

OUTER JOIN

 An outer join extends the result of a simple join.


 An outer join return all rows that satisfy the join condition and also those rows
from on table for which no rows from the other satisfy the join condition.
 To perform an outer join of tables A and B and returns all rows from A, apply
the outer join aerator (+) to all columns of B outer join operator (+) to all
columns of B.
 For all rows in A that have no matching rows in B, oracle returns NULL for
any Select list expressions containing columns of B.

SQL > Select E.Empno, E.Ename ,E.Deptno, D.Deptno, D.Dname, D.loc


From EMP E, Dept D Where E.Deptno=D.Deptno;

SQL > Select E.Empno, E.Ename ,E.Deptno, D.Deptno, D.Dname, D.loc


From EMP E, Dept D Where E.Deptno(+)=D.Deptno;

Rules and Restriction


 The (+) operator can appear only in the Where clause.
 The (+) operator can appear in the context of the left correlation in the from
clause and can be applied only to a column of table or view.
 If A and B are joined by multiple join condition we must use the (+) operator
in all of these condition.
 The (+) operator can be applied only to a column, not to an arbitrary
expression.
 A condition containing the (+) operator cannot be combined with another
condition using the OR logical operator.
 A condition cannot use the IN comparison operator to compare a column
marked with the (+) operator with an expression .
 A condition cannot compare any column marked with the (+) operator a
sub query like Where E.Deptno(+)=(SELECT * FROM EMP)

SQL > Select E.Empno, E.Ename ,E.Deptno, D.Deptno, D.Dname, D.loc


From EMP E, Dept D Where E.Deptno(+)=D.Deptno OR D.LOC='NEW
YORK';

Oracle_10g By Naresh A K
106

SUB Queries /Nested Select / Sub Select / Inner Select

 A SUB Queries answer multiple part of questions.


 A SUB Queries in the from clause of a Select statement is called as INLINE
View.
 A SUB Queries in the Where clause of a Select statement is called as Nested
Sub query.
 A SUB Queries can contain another Sub query.
 Oracle imposes no limit on the number of SUB Queries levels in the “from
“clause of the top-level query.
 Within the Where clause up to 255 SUB Queries can be nested.
 A SUB Queries can be part of a column, in the Select list.
 To make the statements easier for readability, qualify the columns in a SUB
Queries with the table name or table alias.

PURPOSE OF A SUB QUERY

 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.

Sub Query principle

 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

 Single row operators (> , =, >=, < , <= , <>)


 Multiple row operators ( IN, ANY, ALL)

TYPE OF SUB QUERY

Single Row Sub Query


 These queries return only one row from the inner Select statement.

Multiple Row Sub Query


 These queries return more than one rows from the Inner Select statement.

Guidelines to Follow:

 A SUB Queries must be enclosed in parenthesis.


 SUB Queries must appear on the right side of the comparison operator.
 SUB Queries should not contain an ORDER BY clause.
 Only the ORDER BY clause can be implemented for the total Select
statement.

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;

Applying Group Function in Sub Query

 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

Applying Having Clause With Sub queries.

 A Sub query can be also applied in Having clause.


 The oracle server executes the Sub query and the results are returned into the
Having clause of the main query.

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);

Sub Queries returning more than one row


 The sub queries that return more than one row are called as multiple row sub
queries.
 In this case a multiple row operator should be used.
 The multiple row operator expects one or more values.
 The multiple row operation are IN, ANY, ALL

IN  Equal to ANY member in the list.


ANY  compares value to each value returned by the Sub Queries.
ALL  Compares value to every value returned by the Sub Queries.

SQL >Select Ename, Sal, Deptno from EMP Where Sal in (Select MIN(Sal)
from EMP Group By Deptno);

Here <ANY means less than the Maximum value.

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';

Here >ANY means more than the minimum.

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

Here <ALL means less the maximum.


SQL > Select Ename, Sal, Deptno from EMP Where Sal <ALL (Select AVG(Sal)
from EMP Group By Deptno);

Here >ALL means more the maximum.

SQL > Select Ename, Sal, Deptno from EMP Where Sal >ALL (Select AVG(Sal)
from EMP Group By Deptno);

Sub Queries Returning Multiple Columns


 In Sub Queries multiple columns can be compared in the Where clause, by
writing a compound Where clause using logical operators.
 Multiple column sub queries enable in to combine the duplicate Where
condition into a single Where clause.

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'));

 The column comparisons in a multiple column sub query can be:


 Pair wise comparisons.
 Non pair wise comparisons.
 In Pair wise comparison each candidate row in the Select statement must have
both the same values associated with each column in the group.
 In Non Pair wise comparison also called cross product, we can use a Where
clause with multiple condition.
 In Non Pair wise comparison, the candidate row must match the multiple
condition in the Where clause but the values are compared individually.

SQL > Select Job, Deptno, Sal from EMP


Where Deptno in (Select Deptno from Dept)
AND Job in (Select Job from EMP Where Deptno=20)

Having Null Values in Sub Query.

 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

Applying Subquery In FROM Clause.

 A sub query in the From clause is equivalent to a view.


 The sub query in the from clause defines a data source for that particular
Select Statement and only that Select statement.

Example INLine queries.

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;

CORRELATED SUB QUERIES

 It is another way of performing queries upon the data with a simulation of


Joins.
 In this the information from the outer Select statement participates as a
condition in the INNER Select statement.
 Correlated subquaries are used for row-by-row processing , each sub query is

Oracle_10g By Naresh A K
112

executed once for every row of the outer query.


/

SQL > Select X.DEPTNO,Ename, Sal from EMP X


Where Sal > (Select AVG(Sal) from EMP X1
Where X.Deptno=X1.Deptno )order by Deptno;

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.

EXISTS Operator in Correlated Sub Queries.

 The Exists operator test for existence of rows in a sub query.


 It returns True if a sub query returns at least one row.

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.

 START WITH  It specifies the root rows of the hierarchy.


 CONNECT BY  It is used to specify the relationship between parent rows
and child rows of the hierarchy.

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.

NOTE: To define hierarchical queries properly we must use the following


clauses.
 START WITH
 CONNECT BY

START WITH

 It identifies the rows to be used as the roots of a hierarchical query.


 It specifies a condition that the roots must specify.
 If START WITH is omitted, Oracle use all rows in the table as ROOT rows.
 A START WITH condition can contain a sub query.

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

Select m.empno empid , m.ename,m.mgr mgrempid,e.ename from emp e, emp m


where e.empno(+)=m.mgr
Select m.empno empid , m.ename,m.mgr mgrempid,e.ename from emp e, emp m
where e.empno(+)=m.mgr

SELECT level, Ename, Empno, Mgr , sys_connect_by_path(ename,'//') xyz


from emp
START WITH sal=5000
CONNECT BY PRIOR Empno=Mgr;

SELECT level, Ename, Empno, Mgr,connect_by_isleaf xyz from emp


START WITH sal=5000
CONNECT BY PRIOR Empno=Mgr;

SELECT level, Ename, Empno, Mgr,sal from emp


START WITH sal=3000
CONNECT BY nocycle Empno=Mgr;

Oracle_10g By Naresh A K
116

SELECT level, Ename, Empno, Mgr,sal ,connect_by_iscycle from emp


START WITH sal=5000
CONNECT BY nocycle Empno=Mgr;

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

LEVEL PSEUDO COLUMN

 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

START WITH Job='PRESIDENT' CONNECT BY PRIOR Empno=mgr;

SELECTING NTH HIGHES VALUE FROM TABLE:

SQL > Select LEVEL, MAX (sal) from EMP


WHERE LEVEL=&LEVELNO
CONNECT BY PRIOR SAL > SAL
GROUP BY LEVEL;

SQL > Select LEVEL, MIN (sal) from EMP


WHERE LEVEL=&LEVELNO
CONNECT BY PRIOR SAL < SAL
GROUP BY LEVEL;

ROWNUM PSEUDO COLUMNS


 For each row returned by a query the ROWNUM pseudo column returns a
number indicating the order in which oracle Selects the row from a set of
joined rows.
 The first row Selected has a ROWNUM of 1, the second has 2 and so on.
 The ROWNUM can be used to limit the number of rows returned by the
query.
 When ORDER BY clause follows a ROWNUM, the rows will be reordered by
the order by clause.
 If ORDER BY clause is embedded in a sub query and ROWNUM condition is
placed in the top level query, then the ROWNUM condition can be forced to
be applied after the ordering of the rows.
 Condition testing for ROWNUM values greater than a positive integer are
always false.

SQL > Select LPAD ( ' ', ROWNUM,' * ') from EMP;
SQL > Select ROWNUM, Ename, Sal from EMP;

Querying From Top 'N' Records

Oracle_10g By Naresh A K
118

 We can ask for nth largest or smallest values of a column.


 Never use ROWNUM and ORDER BY together as oracle first fetches the
rows according to ROWNUM and the sort the found rows.
 From oracle 8i, ORDER BY can be used in views and INLINE VIEWS.

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;

ROWID PSEUDO COLUMN

 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.

Uses of ROWID values


 ROWID is the fastest means of a accessing a single row.
 ROWID can show how table’s rows are stored.
 ROWID are unique identifiers for a row in a table.
 A ROWID can never change during the life time of its row.
 ROWID’s should not be assigned as Primary keys as there is a chance of
ROWID to change when the database is exported or imported.
 When a row is Deleted, oracle may re-adding its ROWID to a new row that is
inserted.
 The ROWID pseudo column can be used in Select and Where clause.

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 ROWNUM RN, EMPNO FROM EMP


WHERE (ROWID,0) IN (SELECT ROWID,MOD(ROWNUM,2) FROM
EMP);

SQL > SELECT * FROM (SELECT ROWNUM RN, EMPNO FROM EMP)E
WHERE MOD(E.RN,2)=0;

SQL > SELECT * FROM (SELECT ROWNUM RN,EMPNO FROM EMP)E


WHERE MOD(E.RN,2)=1;

select * from (select empno,rownum rn from emp) x where mod(x.rn,2)=0;

CURVAL AND NEXTVAL


 The Pseudo Columns are applied upon the SEQUENCE schema object.
 CURRVAL returns the current value of a sequence.

Oracle_10g By Naresh A K
120

 NEXTVAL increments the sequence and returns the next value.


 The CURRVAL and NEXTVAL can be used only in
 The Select list of a Select statement.
 The Value clause of an insert statement.
 The Set clause of an update statement.

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.

SEQUENCE_NAME.CURRVAL Returns the current value of the Sequence.


SEQUENCE_NAME.NEXTVAL Increments the Sequence value by the
declare specification.

 For SEQUENCE in other schema the qualifying syntax is

 SCHEMANAME.SEQUENCEname.CURRVAL
 SCHEMANAME.SEQUENCEname.NEXTVAL

 To refer to the value of a SEQUENCE on a remote database, the SEQUENCE


should be qualified with a complete or partial name of the database link.

 SCHEMANAME.SEQUENCEname.CURRVAL@dblink
 SCHEMANAME.SEQUENCEname.NEXTVAL@dblink

CREATING SEQUENCES

CREATE SEQUNCE Sequence_Name


INCREMENT BY integer
START WITH integer
MAXVALUE inter / NOMAXVALUE
MINVALUE integer/ NOMINVALUE
CYCLE / NOCYCLE
CHACHE integer / NOCHACHE
ORDER / NOORDER

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);

Creating of Incremental Sequence with NOCYCLE/NOCYCLE

SQL > CREATE SEQUENCE sample2


INCREMENT BY 1
START WITH 1
MAXVALUE 5
MINVALUE 0
NOCACHE
NOCYCLE;

Activating and attaching the sequence to a table

SQL > SELECT sample2 .CURRVAL FROM DUAL;

SQL >. INSERT into EMP (Empno, Ename) values (sample .nextval, '&Ename ');

SQL > INSERT into SAMPLE (SAMPLEID, SAMPLE_NAME,


SAMPLE_DATE) values (sample2.nextval,'&SAMPLE_NAME ',
SYSDATE);

SQL > DROP SEQUENCE SAMPLE2;

Creating of decremental sequence

Oracle_10g By Naresh A K
124

SQL >

GUIDELINES FOR ALTERING A SEQUENCE


 The ALTER privilege should be available.
 Only the future sequence numbers are affected by the ALTER sequence
statement.
 The START WITH option cannot be changed using ALTER sequence.
 To change the START WITH option, drop the sequence and then recreate
the sequence.
 Some validation performed, i.e. A new Maxvalue cannot be imposed that is
less than the current Sequences number.

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

SQL > ALTER SEQUENCE sample2


MAXVALUE 10
CACHE 2
CYCLE;

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.

SQL > Select sequence_name, min_value,max_value, increment_by, last_number


from USER_SEEQUENCES;

Viewing the current value of a sequence.

SQL > Select sample.currval from dual;

Oracle_10g By Naresh A K
125

Dropping an Existing Sequence

 A sequence can be dropped at any time.


 Once remove, the sequence an no longer be referenced.

SQL > Drop sequence Sample;

Simplified sequence expressions:

simplified sequence fetching


We will begin with Oracle 11g's support for sequence expressions in PL/SQL. As most
developers will be aware, sequences have never been directly supported in PL/SQL. In
versions prior to 11g, assigning a variable from a sequence (i.e. retrieving NEXTVAL or
CURRVAL) is a SQL-only operation (we typically use a SELECT..INTO..FROM DUAL
construct). In 11g, however, Oracle has added sequence fetching (using NEXTVAL and
CURRVAL) to the list of valid PL/SQL expressions. This means we can use sequence
expressions in PL/SQL anywhere we can validly use a number.
To demonstrate this, we will create a sequence ("S") and run some simple examples, as
follows.
SQL> CREATE SEQUENCE s;

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

PL/SQL procedure successfully completed.

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

PL/SQL procedure successfully completed.


The sequence pseudo-columns can be referenced directly, which means that we can bypass the
intermediate variable assignment if necessary, as follows.
SQL> BEGIN
2 DBMS_OUTPUT.PUT_LINE('Nextval=' || TO_CHAR(s.NEXTVAL));
3 END;
4 /
Nextval=3

PL/SQL procedure successfully completed.


We can see that, in this case, the sequence pseudo-column is used in a similar manner to a
function call. Note that we can also use CURRVAL in the same manner as NEXTVAL, as the
following example demonstrates.
SQL> BEGIN
2 IF s.NEXTVAL > 3 THEN
3 DBMS_OUTPUT.PUT_LINE('Currval=' || TO_CHAR(s.CURRVAL));
4 END IF;
5 END;
6 /
Currval=4

PL/SQL procedure successfully completed.


This new feature provides greater simplicity, but not improved performance. Oracle's
underlying implementation of sequences and sequence-fetching hasn't changed, as we will now
demonstrate. In the following example, we will use SQL trace to compare the performance of
sequence assignment expressions with the pre-11g method of selecting the next values from the
DUAL table. We will execute 10,000 assignments per method, as follows. Note how we alias
the pseudo-column as "NVAL" in the SQL method: this will be important when we examine
our trace file.
SQL> ALTER SESSION SET SQL_TRACE = TRUE;

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

8 SELECT s.NEXTVAL AS nval INTO n FROM dual;


9 END LOOP;
10 END;
11 /

PL/SQL procedure successfully completed.

SQL> ALTER SESSION SET SQL_TRACE = FALSE;

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

call count cpu elapsed disk query current


rows
------- ------ -------- ---------- ---------- ---------- ----------
----------
Parse 1 0.00 0.00 0 0 0
0
Execute 10000 0.17 0.19 0 0 0
0
Fetch 10000 0.39 0.42 0 0 500
10000
------- ------ -------- ---------- ---------- ---------- ----------
----------
total 20001 0.56 0.62 0 0 500
10000

Misses in library cache during parse: 1


Optimizer mode: ALL_ROWS
Parsing user id: 81 (recursive depth: 1)

Rows Row Source Operation


------- ---------------------------------------------------
1 SEQUENCE S (cr=0 pr=0 pw=0 time=0 us)
1 FAST DUAL (cr=0 pr=0 pw=0 time=0 us cost=2 size=0 card=1)

****************************************************************************
****
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

call count cpu elapsed disk query current


rows
------- ------ -------- ---------- ---------- ---------- ----------
----------
Parse 1 0.00 0.00 0 0 0
0
Execute 10000 0.20 0.19 0 0 0
0
Fetch 10000 0.42 0.42 0 0 500
10000
------- ------ -------- ---------- ---------- ---------- ----------
----------
total 20001 0.62 0.61 0 0 500
10000

Misses in library cache during parse: 1


Optimizer mode: ALL_ROWS
Parsing user id: 81 (recursive depth: 1)

Rows Row Source Operation


------- ---------------------------------------------------
1 SEQUENCE S (cr=0 pr=0 pw=0 time=0 us)
1 FAST DUAL (cr=0 pr=0 pw=0 time=0 us cost=2 size=0 card=1)

****************************************************************************
****
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

or more than one table.


 Data type of the corresponding columns in all the Select statement should be
same.

 The different types of SET operator are:


 UNION
 INTERSECT
 UNION ALL
 MINUS
 SET operator can combine tow or more queries into one result.
 The ORDER BY clause when implemented should be applied only upon the
column numbers in the Select list.

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.

SQL > Select Empno, Ename from EMP Where Deptno=10


UNION
Select Empno, Ename from EMP Where Deptno=30
ORDER BY 1;

Oracle_10g By Naresh A K
130

SQL > Select Empno, Ename, Job from EMP


Where Deptno =( Select Deptno from Dept Where Dname='SALES')
UNION
Select Empno, Ename, Job from EMP
Where Deptno = (Select Deptno from Dept Where
Dname='ACCOUNTING')
ORDER BY 1;

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

 These operator returns the rows unique to the first query.

SQL > Select DEPTNO, Empno, Ename from EMP Where Deptno=10
MINUS
Select DEPTNO, Empno, Ename from EMP Where Deptno=30
ORDER BY 1;

SQL > Select ROWNUM, Ename from EMP Where ROWNUM<7


MINUS
Select ROWNUM, Ename from EMP Where ROWNUM<6 ;

Oracle_10g By Naresh A K
131

VIEWS IN ORACLE

 It is a logical table based on one or more tables or Views.


 A view in practically contains no data by itself.
 The tables upon which a view is based are called as base table.
 Views can be created as object views or relational views.
 The object views support
 LOB, OBJECT TYPES, NESTED TABLES, VARRAYS.
 Object view is a views of a user defined type, where each row contains
objects, and each object with identifier.

PREREQUISITES

 Should have CREATE VIEW or CREATE ANY VIEW system privilege.


 To create a sub view, we need user any view system privilege or UNDER
OBJECT privilege on the SUPPER VIEW.
 The OWNER of the schema should have Select, Insert, Update or Delete rows
from all tables or views on which the View is based.
 The above privileges must be granted the privileges directly, rather then a role.

OR REPLACE  Specifies the view has to be replaced if already existing.


FORCE  Specifies the View has to be created even if the base tables down
not exist.
NOFORCE  Specifies the View should not be created if the base table does
not exist, which is default.
ALIAS_NAME  Specifies the Name of an alias for an expression in the
SubQuery.
WITH CHECK OPTION  Specifies that only rows that would be retrieved by
the Sub Query can be INSERTED, UPDATED or DELETED.
CONSTRAINT  Constraint Name Specifies the name of the WITH CHECK

Oracle_10g By Naresh A K
132

option of READ ONLY constraint.


WITH READ ONLY  Specifies that rows may only read from the base tables.

Types Of Views
 Simple Views
 Complex views

Simple Views Which contains a sub query that retrieves from one base table.

Complex Views

 Contain a sub query that can perform any of these actions.


 Retrieving from multiple base tables.
 Groups rows using a Group by or distinct clause.
 Contains a function all.

Simple View Example:

SQL > Create View EMPloyee AS Select Empno “ Id Number”, Ename “


EMPloyee Name”, Sal “Basic Salary”, Job Designation from EMP;

Select Data from A View

SQL > Select Ename, Job from EMPloyee.


SQL > Select “Id Number”, Ename, “Basic Salary” *12 From EMPlooyee.

Complex View

SQL > Create View EMPloyeeInf As Select E.Empno EMPlooyeeID, E.Ename


Name, D.Deptno DepartmentId, D.Dname DepartmentName from EMP E, Dept
D Where D.Deptno = E.Deptno Order by D.Deptno;

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);

SQL > insert into EMPloyeeInf (EMPLOOYEEID) values (33);

View in Data Dictionary

 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

 OR REPLACE option is used to modify an existing View with a new


definition.
 A view can be altered without dropping, recreating, and regenerating object
privileges.
 The assigned column aliases in the Crete view clause are listed in the same
order as the columns in the sub query.

Creating Views with Columns Declaration.

SQL > Create or replace view DeptSalSummary


( DepartmentName,
MinimumSalary,
MaxSalary,
AverageSalary,
SalarySum) As Select D.Dname, Min (E.Sal), Max (E.Sal), AVG
(E.Sal), Sum (E.Sal) from EMP E, Dept D Where E.Deptno=d.Deptno Group by
D.Dname;

SQL > Create View InsertDetp20 as Select * from EMP Where Deptno=20;

Inserting the Total Data of Employees from Department 20 using view.

SQL > Create table Dept20 As Select * from InsertDetp20;

SQL > Create table EMPGrades ( EMPloyee, Designation, BasicSalary, Grade )

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

 The DROP view statement is used to remove a view permanently.


 Dropping a view has no affect on the tables upon which the view is created.
 Views or applications based on deleted views become invalid.
 We need DROP ANY VIEW privilege to remove the views.

SQL > Drop view View_Name

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;

Rules for Performing DML Operations on a View

 DML operations can be performed upon a table through View.


 A row can be removed from a View unless it contains.
 Group Function.
 A Group By Clause
 The Rownum Pseudo Column.
 The Distinct Key words
 The columns defined by expression.

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;

Using WITH CHECK Option Clause

 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> insert into EDept30 (empno, deptno) values (333,30);

SQL> insert into EDept30 (empno, deptno) values (333,40);

SQL > Create Or Replace View Emanager As Select * from EMP Where
Job='MANAGER'
CHECK OPTION CONSTRAINT MANAGER View;

Applying WITH READ ONLY OPTION

 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

SQL> Create or Replace View EdpetRead (EMPid, Name, Designation) As


Select Empno, Ename, Job from EMP Where Deptno =20;

SQL> INSERT INTO EdpetRead (EMPID, NAME) VALUES (777,'NARESH');

SQL > Create Or Replace View EdpetRead (EMPid, Name, Designation) As


Select Empno, Ename, Job from EMP Where Deptno =20 WITH READ
ONLY;

SQL> insert into EdpetRead (empid, name) values (3454,'naresh');

SQL> delete from edpetread;

SQL> update EdpetRead set name ='kumar' where empid=7369;

WORKING WITH INDEXES

 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

 They are default indexes.


 They are created with B-Tree Principle.

 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.

Restriction On index columns:


 An Index cannot be created on columns or attributes whose type is
 LOB LONG, USER DEFINED

Simple Index Example:

SQL > Create INDEX EMP_idx ON EMP (Empno);


SQL > Create INDEX Dept_idx on Dept (Deptno);

Unique Index Example:

Oracle_10g By Naresh A K
138

SQL > Create UNIQUE Index Empno_Uind on EMP (Empno);

Creating Composite Indexes:


 Composite index is an Index on Multiple columns.

SQL > Create Index Empno_Deptno_ind (Empno, Deptno);

Creating Function Based Indexes:

 These are indexes based on expressions.


 The index expressions are built from table columns, SQL Function and user
defined function.
 Function based indexes defined with the UPPER (column_name) or Lower
(column_name) allow case insensitive searches.
 To ensure that oracle uses the index rather than performing a full table scan,
we should be sure that the value of the functions is not NOT NULL in
subsequent queries.
 Oracle treats INDEXES with columns marked desc as function based indexes.

Index Example:

SQL > Create IndexUpperCase_ind ON EMP (UPPER (Ename));

Note: The Function based indexes are used only when the query statement is
executed through the specified function.

Creating Bitmap Indexes:


 These indexes are used to tune queries that use non Selective columns in their
limiting conditions.
 Bitmap indexes should be used only when the data is infrequently updated.
 Bitmap indexes add to the cost of all data manipulation transaction against the
tables they index.
 The oracle optimizer can dynamically convert bitmap indexes entries to
rowId's during the query processing.

Example:

SQL > Create Bitmap index EMPbimap_Job_ind on EMP (Job);

Oracle_10g By Naresh A K
139

Specification of an Index:

 Index is a schema object.


 Index is used by the ORACLE SERVER to speed up retrieval or rows by
using a pointer.
 Index reduces the disk I/O by using rapid path access method to locate the
data quickly.
 Indexes are independent of the table it indexes, both logically and physically.
 Index is used and maintained automatically by the ORACLE SERVER.
 Index's can be created or dropped at any time and have no effect on the
base tables or other indexes.
 When a table is dropped, the corresponding indexes are also dropped.
 Index creation is of two types:
 Automatic and Manual.
 One table can contain more than one index can be created, but this does not
mean that, more the indexes lead to faster performance.
 Each DML, operations that is committed on a table with indexes means
that the indexes must be updated.

When to Create an Index:


 The columns is used frequently in the Where clause or in a join condition.
 The columns contain a wide range of values.
 The columns contain a large number of NULL Values.
 Two or more columns are frequently used together in a Where clause of join
condition.
 The table is large and most queries are expected to retrieve less than 2-4%
of the rows.

When Not to Create an Index


 The table is too small.
 The columns are not often used as condition in the query.
 Most queries are expected to retrieve more than 2-4% of the rows.
 The table is updated frequently.

 The indexes can be confirmed from the USER_INDEXES Data Dictionary.


 The column that are involved in an index by querying
USER_IND_COLUMNS

Oracle_10g By Naresh A K
140

 To Drop an index Drop command is used

SQL > Drop index INDEX_NAME;


SQL> ALTER INDEX IND2 DISABLE;
SQL> ALTER INDEX IND2 ENABLE;
SQL> ALTER INDEX IND2 INVISIBLE;
SQL> ALTER INDEX IND2 VISIBLE;
SQL> ALTER INDEX IND2 REBUILD;
SQL> ALTER INDEX IND2 RENAME TO IND3;

DATABASE SECURITY

 The Security upon databases is applied by defining and describing separate


SCHEMA objects and GRANTING required privileges upon them.
 In Oracle the privileges can be granted as well as Revoked.
 GRANT command is used when we want the database to be shared with other
users.
 The other users are GRANTED with contain type of rights.
 GRANT can be issued not only on Table Object, but also on Views,
Synonyms, Indexes, and Sequences etc.

Syntax for GRANT

SQL > Grant < privileges Name > ON <Object Name > TO < User Name >

Oracle_10g By Naresh A K
141

SQL > Grant Select on EMP to Naresh;


SQL > Grant Insert, Select, Delete on EMP to Naresh;
SQL > Grant Insert (Empno, Ename, Job) ON EMP to Naresh.
SQL > Grant Insert (Empno, Ename, Job) ON EMP to Naresh;

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.

Syntax for REVOKE

SQL > REVOKE < privileges Name > ON <Object Name > FROM < User Name
>

SQL > REVOKE Insert, Delete ON EMP FROM Naresh;

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.

Checking the Object privilege Granted

 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.

Checking the Object privilege Received:

 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

WORKING WITH ROLES:

 A ROLE is a group of privileges that can be assigned to a USER or another


ROLE.

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:

 To create a ROLE we should have the CREATE ROLE SYSTEM privileges.


 The steps in implementing the ROLES.
 Roles Creation.
 Granting Privileges to those Roles.
 Granting Roles to Users or Objects.

Syntax:

Create ROLE < Role Name > [IDENTIFIED BY < Password>];

SQL > Create ROLE sample_Role IDENTIFIED BY sample;

Granting Privileges to Role:

 The Roles are granted privileges using the Grant Statement.


 A Role can be granted both systems as well as object privileges.

SQL > Grant Select, Insert, Update, Delete on EMP To sample_Role ;

Oracle_10g By Naresh A K
143

Granting a Role to a USER:

SQL > Grant sample_Role to Naresh;

Granting Multiple Roles to Another Roles:

SQL > Grant Role1, Role2 …… TO < Role_Name>;

Checking Roles Granted to a User:

 The Schema objects USER_ROLE_PRIVS Specifies the roles granted to a


USER.
 The Schema Object USER_ROLE_PRIVS contains the following columns.
 UserName , Granted_Role, Admin_Option Default_Role, Os_Granted.

Checking System Privileges Granted to A Role:

 The Schema Object ROLE_SYS_PRIVS Specifies the System Privileges


granted to a Role.
 The Columns present are
 Role , Owner , Table_Name, Column_Name, Privileges , Grantable.

Revoking a Role:

SQL > Revoke sample_Role from Naresh;

Revoking Privileges from a Role:

SQL > Revoke ALL on EMP from sample_Role;

Dropping a Role:

SQL > Drop role <Rol_Name>;


SQL >Drop role sample_Role;

WORKING WITH SYNONYMS:

Oracle_10g By Naresh A K
144

 A synonym is a schema object, which acts as and alternate name for an


existing object.
 By using a synonym, we can avoid the entry of the schema name, when
referencing upon objects that belong to another schema.
 The create synonym privileges is necessary to execute the creation of a
synonym.

Syntax:
SQL > Create synonym < synonym _Name > FOR < Schema_Name > .
<Object_Name >

SQL > Create synonym EMPInformation FOR Naresh.EMP;

Synonym Types.

 The synonym are practically of two types


 Private synonym and Public synonym.
 We should have Create Public synonym Privilege, and it can be accessed by
all Users.
 If you drop the base table synonyms also droped.

SQL > Create PUBLIC synonym EMPInformation FOR Naresh. EMP;

OLAP FEATURES IN ORACLE:

 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

 It is a Group By operation and is used to produce subtotals at any level of the


aggregation.

Oracle_10g By Naresh A K
145

 The generated subtotals Roll UP to produce Grant Total.


 The totaling is based on a one dimensional Data Hierarchy of grouped
information.

SQL > Select Deptno, SUM (Sal ) from EMP group by Deptno;

Passing Single Column To Rollup.

SQL >Select Deptno, SUM (Sal ) from EMP group by ROLLUP (deptno);

Passing Multiple Columns To Roll Up:

 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:

 It is an extension similar to ROLLUP.


 CUBE allows to take a specifies set of grouping columns and create sub totals
for all possible combinations of them,
 The result of CUBE is a summary that shows subtotals for every combination
of columns or expressions in the GROUP By clause.

SQL > Select Deptno, Job, SUM (Sal) Salary from EMP group by CUBE (Job,
Deptno);

Applying Grouping () Function:

 The Grouping() Function accepts a column and returns 0 or 1;


 Grouping() Function returns 1 when the column value is NULL , and return 0
when the column values is NOT NULL
 Grouping () Function is used only upon queries that use ROLLUP or CUBE.
 Grouping () Function is useful when we want to display a value when a NULL

Oracle_10g By Naresh A K
146

would otherwise be returned.

SQL > Select Grouping (Deptno), Deptno, SUM (Sal) Salary from EMP group by
ROLLUP (Deptno);

SQL> SELECT Grouping (Deptno), DECODE (NVL (DEPTNO, 0),


0,'TOTALSAL', deptno), SUM (Sal) Salary from EMP
Group by ROLLUP (Deptno);

DECODE FUNCTION:

 It is a single row function.


 The function works on the same principle as the if-then-else.
 We can pass a variable number or values into the call of the DECODE()
function.
 The first item is always the name of the column that need to be DECODE.
 Once all value-substitute pairs have been defined, we can optionally specify a
DEFAULT value.
 The function has no restriction on the input and output data type.

Example:

SQL > Select Ename, DECODE (Deptno, 10,


'Accounting',20,'Reseach',30,'Sales',40,'Operations','Other') Departments from
EMP Order By Departments;

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;

Grouping with Decode:

Oracle_10g By Naresh A K
147

 The DECODE () function can be used to convert 1 and 0 returned through


Grouping() into meaningful output.

Example:

SQL > Select DECODE (Grouping (Deptno), 1,'All Departments', Deptno)


Departments,
Sum (Sal) from EMP Group by Rollup (Deptno);

SQL > Select DECODE (Grouping (Deptno), 1,'All Departments', Deptno)


Departments,
Sum (Sal) from EMP Group by CUBE (Deptno);

WORKING WITH CASE:

 The CASE expression can be used to perform if-then-else logic in SQL.


 CASE is similar to DECODE but is ANSI compliant.
 CASE expressions are of tow types.
 Simple CASE Expressions.
 Searched CASE Expressions.

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:

SQL > Select Ename, Deptno, CASE Deptno


When 10 Then 'Accounting'

Oracle_10g By Naresh A K
148

When 20 Then 'Research'


End from EMP;

Searched CASE Expression:


 They use conditions to determine the retuned value.

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:

SQL > Select Ename, Deptno, CASE


When Deptno = 10 Then 'Accounting'
When Deptno = 20 Then 'Research'
When Deptno = 30 Then 'Sales'
When Deptno = 10 Then 'Operations'
Else 'Not Specified'
End from EMP;

SQL > Select Ename, Sal, CASE


When Sal >=500 and Sal <= 3000 Then 'Lowest Pay'
When Sal >=1000 and Sal <= 4000 Then 'Moderate Pay'
Else 'High Pay' end from EMP;

ANALYTIC FUNCTION:

 The built in analytic functions enable to perform complex calculation.


 Analytic functions categories.

Oracle_10g By Naresh A K
149

 Ranking Function and Dense Ranking Function.

SQL > CREATE TABLE EMPLOYEE2 (ID NUMBER,DEPTNO


NUMBER,NAME VARCHAR2(10),SAL NUMBER,HIREDATE DATE);

SQL> SELECT * FROM EMPLOYEE2;

ID DEPTNO NAME SAL HIREDATE


---- ------ ---------- ----- ---------
12 40 NARESH 1000 26-JUN-09
13 50 KUMAR 2000 26-JUN-09
14 40 SUJATHA 2000 26-JUN-09
15 50 AK 1000 26-JUN-09
16 60 MAHESH 500 26-JUN-09

SQL> INSERT INTO EMPLOYEE2 VALUES


(&ID,&DEPTNO,'&NAME',&SAL,&HIREDATE);

SQL> SELECT DEPTNO, SUM (SAL) FROM EMPLOYEE2 GROUP BY


DEPTNO;

SQL> SELECT DEPTNO, SUM (SAL), RANK () OVER (ORDER BY SUM


(SAL) DESC) Ranking FROM emp
GROUP BY DEPTNO;

SQL> SELECT DEPTNO, SUM (SAL), DENSE_RANK () OVER (ORDER BY


SUM (SAL) DESC) RANK_ALLIASE FROM emp
GROUP BY DEPTNO;

SQL> SELECT DEPTNO, SUM (SAL), RANK () OVER (ORDER BY SUM


(SAL) DESC) RANK_ALLIASE,
DENSE_RANK () OVER (ORDER BY SUM (SAL) DESC)
DENSE_RANK_ALLIAS
FROM DEPT

Oracle_10g By Naresh A K
150

WHERE TO_CHAR (HIREDATE,'YYYY')=2009


GROUP BY DEPTNO;

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

 Analytic Function Syntax

o query_partition_clause

o order_by_clause

o windowing_clause

 Using Analytic Functions

Related articles.

 RANK, DENSE_RANK, FIRST and LAST Analytic Functions

 FIRST_VALUE and LAST_VALUE Analytic Functions

 LAG and LEAD Analytic Functions

 LISTAGG Analystic Function in 11g Release 2

 Top-N Queries

 Pattern Matching (MATCH_RECOGNIZE) in Oracle Database 12c Release 1 (12.1)

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.

SELECT deptno, AVG(sal)


FROM emp
GROUP BY deptno
ORDER BY deptno;

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.

Analytic functions also operate on subsets of rows, similar to aggregate functions


in GROUP BY queries, but they do not reduce the number of rows returned by the
query. For example, the following query reports the salary for each employee, along
with the average salary of the employees within the department.

Oracle_10g By Naresh A K
152

SET PAGESIZE 50
BREAK ON deptno SKIP 1 DUPLICATES

SELECT empno, deptno, sal,


AVG(sal) OVER (PARTITION BY deptno) AS avg_dept_sal
FROM emp;

EMPNO DEPTNO SAL AVG_DEPT_SAL


---------- ---------- ---------- ------------
7782 10 2450 2916.66667
7839 10 5000 2916.66667
7934 10 1300 2916.66667

7566 20 2975 2175


7902 20 3000 2175
7876 20 1100 2175
7369 20 800 2175
7788 20 3000 2175

7521 30 1250 1566.66667


7844 30 1500 1566.66667
7499 30 1600 1566.66667
7900 30 950 1566.66667
7698 30 2850 1566.66667
7654 30 1250 1566.66667

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.

Analytic Function Syntax


There are some variations in the syntax of the individual analytic functions, but the
basic syntax for an analytic function is as follows.

analytic_function([ arguments ]) OVER (analytic_clause)

The analytic_clause breaks down into the following optional elements.

[ 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

SELECT empno, deptno, sal,

Oracle_10g By Naresh A K
154

AVG(sal) OVER () AS avg_sal


FROM emp;

EMPNO DEPTNO SAL AVG_SAL


---------- ---------- ---------- ----------
7369 20 800 2073.21429
7499 30 1600 2073.21429
7521 30 1250 2073.21429
7566 20 2975 2073.21429
7654 30 1250 2073.21429
7698 30 2850 2073.21429
7782 10 2450 2073.21429
7788 20 3000 2073.21429
7839 10 5000 2073.21429
7844 30 1500 2073.21429
7876 20 1100 2073.21429
7900 30 950 2073.21429
7902 20 3000 2073.21429
7934 10 1300 2073.21429

SQL>

If we change the OVER clause to include a query_partition_clause based on the


department, the averages presented are specifically for the department the employee
belongs too.

BREAK ON deptno SKIP 1 DUPLICATES

SELECT empno, deptno, sal,


AVG(sal) OVER (PARTITION BY deptno) AS avg_dept_sal

Oracle_10g By Naresh A K
155

FROM emp;

EMPNO DEPTNO SAL AVG_DEPT_SAL


---------- ---------- ---------- ------------
7782 10 2450 2916.66667
7839 10 5000 2916.66667
7934 10 1300 2916.66667

7566 20 2975 2175


7902 20 3000 2175
7876 20 1100 2175
7369 20 800 2175
7788 20 3000 2175

7521 30 1250 1566.66667


7844 30 1500 1566.66667
7499 30 1600 1566.66667
7900 30 950 1566.66667
7698 30 2850 1566.66667
7654 30 1250 1566.66667

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

BREAK ON deptno SKIP 1 DUPLICATES

SELECT empno, deptno, sal,


FIRST_VALUE(sal IGNORE NULLS) OVER (PARTITION BY deptno) AS
first_sal_in_dept
FROM emp;

EMPNO DEPTNO SAL FIRST_SAL_IN_DEPT


---------- ---------- ---------- -----------------
7782 10 2450 2450
7839 10 5000 2450
7934 10 1300 2450

7566 20 2975 2975


7902 20 3000 2975
7876 20 1100 2975
7369 20 800 2975
7788 20 3000 2975

7521 30 1250 1250


7844 30 1500 1250
7499 30 1600 1250
7900 30 950 1250
7698 30 2850 1250
7654 30 1250 1250

SQL>

Now compare the values of the FIRST_SAL_IN_DEPT column when we include


an order_by_clause to order the siblings by ascending salary.

Oracle_10g By Naresh A K
157

SELECT empno, deptno, sal,


FIRST_VALUE(sal IGNORE NULLS) OVER (PARTITION BY deptno
ORDER BY sal ASC NULLS LAST) AS first_val_in_dept
FROM emp;

EMPNO DEPTNO SAL FIRST_VAL_IN_DEPT


---------- ---------- ---------- -----------------
7934 10 1300 1300
7782 10 2450 1300
7839 10 5000 1300

7369 20 800 800


7876 20 1100 800
7566 20 2975 800
7788 20 3000 800
7902 20 3000 800

7900 30 950 950


7654 30 1250 950
7521 30 1250 950
7844 30 1500 950
7499 30 1600 950
7698 30 2850 950

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.

It is important to understand how the order_by_clause affects display order.


The order_by_clause is guaranteed to affect the order of the rows as they are

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.

RANGE BETWEEN start_point AND end_point


ROWS BETWEEN start_point AND end_point

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.

 value_expr FOLLOWING : As above, but an offset after the current row.

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.

SELECT empno, deptno, sal,


AVG(sal) OVER (PARTITION BY deptno ORDER BY sal ROWS
BETWEEN 2 PRECEDING AND 2 PRECEDING) AS avg_of_current_sal
FROM emp;

EMPNO DEPTNO SAL AVG_OF_CURRENT_SAL


---------- ---------- ---------- ------------------
7934 10 1300 1300
7782 10 2450 2450
7839 10 5000 5000

7369 20 800 800


7876 20 1100 1100
7566 20 2975 2975
7788 20 3000 3000
7902 20 3000 3000

7900 30 950 950


7654 30 1250 1250
7521 30 1250 1250
7844 30 1500 1500
7499 30 1600 1600
7698 30 2850 2850

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.

SELECT empno, deptno, sal,


AVG(sal) OVER (PARTITION BY deptno ORDER BY sal) AS
avg_dept_sal_sofar
FROM emp;

EMPNO DEPTNO SAL AVG_DEPT_SAL_SOFAR


---------- ---------- ---------- ------------------
7934 10 1300 1300
7782 10 2450 1875
7839 10 5000 2916.66667

7369 20 800 800


7876 20 1100 950
7566 20 2975 1625
7788 20 3000 2175
7902 20 3000 2175

7900 30 950 950


7654 30 1250 1150
7521 30 1250 1150

Oracle_10g By Naresh A K
161

7844 30 1500 1237.5


7499 30 1600 1310
7698 30 2850 1566.66667

SQL>

There are two things to notice here.

 The addition of the order_by_clause without a windowing_clause means the query


is now returning a running average.

 The default windowing_clause is "RANGE BETWEEN UNBOUNDED PRECEDING AND


CURRENT ROW", not "ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT
ROW". The fact it is RANGE, not ROWS, means it stops at the first occurrence of the value in
the current row, even if that is several rows earlier. As a result, duplicate rows are only included
in the average when the salary value changes. You can see this in the last two records of
department 20 and in the second and third records of department 30.

In my opinion, the default windowing_clause should have been "ROWS BETWEEN


UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING". This would make the
accidental inclusion of the windowing_clause much less confusing.

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

SELECT empno, deptno, sal,


FIRST_VALUE(sal) OVER (ORDER BY sal ROWS BETWEEN 1
PRECEDING AND CURRENT ROW) AS previous_sal,
LAST_VALUE(sal) OVER (ORDER BY sal ROWS BETWEEN CURRENT ROW
AND 1 FOLLOWING) AS next_sal
FROM emp;

EMPNO DEPTNO SAL PREVIOUS_SAL NEXT_SAL

Oracle_10g By Naresh A K
162

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


7369 20 800 800 950
7900 30 950 800 1100
7876 20 1100 950 1250
7521 30 1250 1100 1250
7654 30 1250 1250 1300
7934 10 1300 1250 1500
7844 30 1500 1300 1600
7499 30 1600 1500 2450
7782 10 2450 1600 2850
7698 30 2850 2450 2975
7566 20 2975 2850 3000
7788 20 3000 2975 3000
7902 20 3000 3000 5000
7839 10 5000 3000 5000

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

The following single-set aggregate example lists all of the employees in


Department 30 in the hr.employees table, ordered by hire date and last name:
SELECT LISTAGG(ename, '; ')
WITHIN GROUP (ORDER BY hiredate, ename) "Emp_list",
MIN(hiredate) "Earliest"
FROM emp
WHERE deptno = 30;

Oracle_10g By Naresh A K
164

SELECT deptno "Dept",


LISTAGG(ename, ';| ') WITHIN GROUP (ORDER BY hiredate) "emp"
FROM emp
GROUP BY deptno
ORDER BY deptno;

SELECT deptno "Dept", hiredate "Date", ename "Name",


LISTAGG(ename, '; ') WITHIN GROUP (ORDER BY hiredate, ename)
OVER (PARTITION BY deptno) as "Emp_list"
FROM emp
WHERE hiredate < '01-SEP-2003'
ORDER BY "Dept", "Date", "Name";

SELECT deptno, ename, sal


FROM
(
SELECT
deptno, ename,sal,
ROW_NUMBER() OVER ( order by 1 ) RN
FROM emp
)
WHERE RN <= 5

SELECT ename, sal,


ROW_NUMBER() OVER(PARTITION BY deptno ORDER BY sal) "NO#"
FROM emp;

SELECT ename, sal,


(ROW_NUMBER( ) OVER(PARTITION BY deptno ORDER BY sal)) RN
FROM emp
where deptno=10

Oracle_10g By Naresh A K
165

SELECT hiredate, ename,


LEAD(hiredate, 1) OVER (ORDER BY hiredate) AS "NextHired"
FROM emp;

SELECT hiredate, ename,


lag(hiredate, 1) OVER (ORDER BY hiredate) AS "NextHired"
FROM emp;

SELECT hiredate, ename,


LEAD(hiredate, 1) OVER (ORDER BY hiredate) AS "NextHired"
FROM emp
WHERE deptno = 30
ORDER BY hiredate;

SELECT hiredate, ename,


lag(hiredate, 1) OVER (ORDER BY hiredate) AS "NextHired"
FROM emp
WHERE deptno = 30
ORDER BY hiredate;

Using Analytic Functions


The best way to understand what analytic functions are capable of is to play around
with them. This article contains links to other articles I've written about specific analytic
functions and the following documentation links list all analytic functions available in
Oracle 12c Release 1. The "*" indicates that these functions allow for the full analytic
syntax, including thewindowing_clause.

 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

 REGR_ (Linear Regression) Functions *

 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

 The Merge statement is convenient to combine multiple operations and avoid


multiple INSERT, UPDATE and DELETE.
 Merge is a deterministic statement, using which the same row of the target
table multiple times in the same merger statements.

SQL> DROP TABLE BONUS;

SQL > CREATE TABLE Bonus


(Empno NUMBER, Bonus NUMBER DEFAULT 100);

SQL> SELECT * FROM BONUS;

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

Changing the name of the Object:

 The RENAME command can be use to change the name of a


 Table.
 View
 Sequence
 To RENAME the object we must be the owner of the object.

SQL > RENAME < old name > TO < new name >;

SQL > RENAME Dept TO Department;

APPLYING COMMENTS UPON A TABLE:

 The comments command is used to add comments to a table or a column or


view etc.
 Each comment can be up to 2000 bytes.
 The data dictionary is which comments are stored are:
 ALL_COL_COMMENTS
 USER_COL_COMMENTS
 ALL_TAB_COMMENTS
 USER_TAB_COMMENTS

SQL > Comment ON table EMP is ' the table storing Employees information';

Dropping A Comments:

 A comment is dropped from the database by setting it to an Empty sting.

SQL > Comment on table EMP is ' ';

ADVANCE TABLE CEATION STRATEGIES:

Oracle_10g By Naresh A K
170

comment on column emp.empno is 'emplyee no';

 Creating a table from an existing table.


 Oracle allows the creation of a new table on_the_fly, depending on a Select
statement on an already existing table.
 The create table as Select command will not work if one of the Select columns
use LONG data type.
 When the new table is described it reveals that it has “INHERITED” the
column definition from the existing table.
 Using this style we can include all columns using asterisk is a subset of
columns from table.
 The new table can contain “invented columns” which are the product of
function of the combination of other columns.
 The column definition will adjust to the size necessary to contain the data is
the invented columns.

SQL > Create table SampDept as Select * from Dept;


SQL > create table SampDept1 (Deptid, Deptname, Place) as Select * from Dept;
SQL > Create table SampDept2 as Select Deptno, Dname from Dept;

Creating a table with columns definitions and without data:

SQL > Create table SampDept3 AS Select * from Dept Where 1=3;

Creating a table without generating redo log entries:


Redo log entries are chronological records of database action used during
database recoveries.
 The REDO log entries generating can be avoided by using the NOLOGING
keyword.
 By circumventing the performance of the create table command will improve
as less work is being done.
 As the new table creation is not being written to the redo log files, the table
will not be re-create following a database failure.
 The redo log files are used to recover the database.

SQL > Create table SampleDept4 NOLOGGING as Select * from Dept;

Oracle_10g By Naresh A K
171

PL/SQL

 PL/SQL stands for PROCEDURAL Language Extensions to SQL.


 PL/SQL extent SQL by adding programming structures and subroutines
available in any high level language.
 PL/SQL can be used for both server side and client side development.
 PL/SQL has syntax and rules that determine how programming statement
work together.
 PL/SQL is not a stand alone programming language.
 PL/SQL is apart of the Oracle RDBMS, and hence can reside in to
environments, the Client and the Server.
 Any Module that is developed using PL/SQL can be moved easily between
Server side and Client side application.
 Either Cline/Server environments any PL/SQL block or the PL/SQL engine
processes subroutine.
 PL/SQL engine is a special component that processes and executes any
PL/SQL statements and send it any SQL statement to the SQL statement
processor.
 The SQL statement processes are always located on the Oracle Server.
 As per the necessity the PL/SQL engine can be located either at Client
and Server.
 When PL/SQL engine is located upon the server, the whole PL/SQL block
is passed to the PL/SQL engine on the oracle server.
 When the PL/SQL engine is located upon the Client, the PL/SQL
processing is done on the Client side. All SQL statements that are
embedded within the PL/SQL block, are sent to the Oracle Sever for
further processing.

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.

PL/SQL IN CLIENT –SERVER ARCHITECHTURE

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.

Main Features of PL/SQL:

Oracle_10g By Naresh A K
173

 It combines the DATA Manipulating power of SQL with processing power of


Procedural language.
 Program flow can be controlled using the statements like IF and LOOP.
 We can declare variable, define procedures and Functions and Trap Runtime
errors.
 Can be used to break complex problems down into easily understandable
procedural code.
 The code can be reused for multiple applications.
 SQL commands can be directly embedded inside the PL/SQL without learning
an API's
 The PL/SQL data types correspond with SQL's columns types making
learning process easier.

Block structure approach:


 The basic units that make up a PL/SQL program are logical blocks.
 The block in PL/SQL can be nested with one another.
 A block groups related declarations and statements.
 The declarations are local to the block and ease to exit when the block
completes.
 Block structure approach avoids cluttered namespaces for variables and
procedures.
 The basic parts of a block are:
 Declarative Part (Optional)m
 Executable part (mandatory)
 Exception Handling Part (Optional)

 Declarative Part: It is used to define type’s variables and similar items.


 Executable Part: It contains the operational code for the program. The items in
declarative part are manipulated here.
 Exception Handling Part: Any exceptions that are raised during the programs
execution are handled here.
 Blocks can be nested in the executable and exception handling parts or a
PL/SQL block, a sub program.
 Local sub programs can be defined declarative part of any block.
 Local sub programs can be called from the block in which they are declared.

The Pseudo structure of a block:

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.

Executing Statements and PL/SQL Blocks from SQL*Plus.

 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.

Types of blocks in PL\SQL

 In the PL\sql there are various types of blocks

ANONYMOUS BLOCKS

 They are unnamed blocks


 They are declared at the point in an application ,where they are to be
executed and are passed to the PL\SQL Engine for exception at runtime
 An anonymous block can be embedded within a precompiled program
and within SQL*plus or server manger.

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

LET US UNDERSTAND VARIABLES IN PL\SQL

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

 All variables are declared and initialized only in the DECLARATIVE


SECTION
 Declarations allocate storage space for a value.
 Declarations can be assigned with an initial value and can be imposed
with a NOT NULL Constraint.

 Assign new values to variables in the executable section.


 The existing value of the variable is replaced with a new one
 Forward references are not allowed.
 Pass values into PL\SQL subprograms through parameters
 There are there parameters modes; they are in (the default). OUT
and IN OUT.

 View the results from a PL\sql block through output variables.


 Reference variables can be used for input or output in SQL data
manipulation statements.

VARABLES TYPES IN PL\SQL:

· All PL\SQL variables have a data type specifying

1) Storage format
2) Constraints
3) Valid range

 PL\SQL supports four data type categories

 Scalar Data types.

1) They hold a single value


2) Main data type is those that correspond to column type in oracle
server.
3) Support Boolean variables.

 Composite Data types:

Records allow groups of fields to be defined and manipulated in

Oracle_10g By Naresh A K
177

PL\SQL blocks.

 Reference data types:

They hold values called pointers, which designate other


program items.

1. LOB Data types:

They hold values called locations, specifying the location of


large objects that are stored out of line.

DECLARING PL\SQL VARIABLES:

SYNTAX:

Identifier [constant] Data type [not null][:=|DEFULT Expr];

 Identifier  Specifies the name of the variable.


 Constant  Constants the variables such that its value cannot change.
Constants must be initialized
 Data type it is a scalar, compsite, reference or LOB Data type
 not null Constants the variables such that it must contain a value. Should
be initialized
 Expr it is any PL\SQL Expression that can be a literal, another
variable or an expression involving operations and functions.

Character Aspects of PL\SQL Language:

 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:

1) A group of characters that are contained within a line of PL\SQL


statements are called as Lexical Units.
2) The types of lexical Units are
 DELIMITERS
 IDENTIFIERS
 LITERALS
 COMMENTS
 Delimiters:
o it is a simple or compound syntax that has special meaning to PL\
SQL
o The Delimiters are used to represent arithmetic operations etc.

 Identifiers:
They are used to name PL\SQL program items and units
 Identifiers can be include
Constants, variables, exception, cursors variables,
subprograms, packages.

 An identifiers consists of letter followed by set of letter,


numerals, dollar sign etc
EX: &,_,/, ''
O Valid identifiers: invalid identifier
X This &that
P2 You –me
V_phone# show/off
V_phone$number EMP Name

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

 Reserved words have special syntactic meaning to PL\SQL


 Reserved words can be used in combination with other words
for declaration.
 It is better to represent reserved words in upper casing.

 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:

 Identifiers declared in double quotes are called quoted


identifiers.
 The Maximum size of a quoted identifier cannot exceed 30
characters
 Using PL\SQL reserved words as quoted identifiers is not
advisable.
Example: “Employee(s)”
“Status on\off”

 LITERALS:
A Literal is a numeric, character, string or Boolean values not
represented by identifier

 NUMERIC LITERALS:

 They are of two types: integers & Reals.


 An integer literal is an optionally signed whole number
without a decimal point.
Example: 030,8,-180,+56798.

Oracle_10g By Naresh A K
180

o A Real literal is an optionally signed whole number without a


decimal point.
Example: 6.6666, 0.0,-12.0, and 3.14,5,25.
o Numerical literals cannot contain dollar signs or fractional number
with decimal point.
o The double asterisk operator(* *) is the exponentiation operator.
o If the value of a numeric literal falls outside the range ,its generates
compilation error .
Example: DECLARE
MyNumber NUMBER
BEGIAN
MyNumber =10E127;
END;/*the range is 1E-130..10E125 */
o Real literals can use the letters f and d to specify the BINARY-
FLOAT and BINARY-DOUBALE
Example:
DECLARE
MyFloat BINARY-FLOAT=SQRT(2.of)
MyDuoble BINARY-DUOBLE=SQRT(2.oD)
BEGIAN
NULL
END;
 CHERACTER LITERALS:

 It is an individual character enclosed by single quotes.


 In includes all printable characters in the PL\SQL character
set.
Example : 'A’,’a’,’C’,’7’

 Characters literals are case sensitive.


 Characters literals in the form of number is not equivalent to
integer.
 Even through pure character literals declared only with
numbers are implicitly converted, it is better to use explicit
conversion.

 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’

o to implementation single quotation marks with easiness, select any


character that is not part of the string and declare the style Ex: Q’!
….!’
Example: Q’! We’re a group, in you’s group!’
 BOOLEAN LITERAILS
o They are predefined values TRUE,FALSE AND NULL.
o BOOLEAN LITERAILS are values, but not strings.

 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 (/*……*)

o Comments should appear within a statement at the end of the line.


Comments cannot be nested.
o It is must preferable to use multi line comments rather than single
line comments
o Its must be preferable to use multi line comments rather at the end of
line.
 DETAILED SPECIFICATION OF PL\SQL DATATYPE:
They let the programmer to store numeric data, represent quantities
and apply calculations.

BINARY_INTEGER

 It is used to store signed integers

Oracle_10g By Naresh A K
182

 Its magnitude range is -2 31….2 31.


 They occupy less storage space than number values
 Arithmetic operations on binary_integer values are faster than
number arithmetic.

BINARY_INTEGER SUBTYPES

o A base type is the data type from which a subtype is derived.


o A subtype associates a base type with a constraint and hence defines a subset
of values .
o The subtype available are

NATURAL * NATURALN * POSITIVE * POSITIVEN *


SIGNTYPE

 Natural and Positive: They restrict an integer variable to Non-


negative or positive values.
 Naturaln and Positiven: Prevent the assign of Nulls to an
integer variable.
 Sign type: lets you restrict an integer variable to the values -
1,0,1 ,used in programming to stage logic.

BINARY_FLOAT AND BINARY_ DUOBLE

 These data types are used primarily for high-speed scientific


computation.
 Literals of these type will be end with f( for biner_float) or
d( for biner_duoble)
 Computations involving these datatypes produce special
values, rather than raising exceptions
 Need special functions to deal with overflow, underflow and
other conditions.

 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:

 These subtypes are used for more descriptive name.


 The NUMBER subtypes are used for compatibility with ANSI/ISO AND
IBM types
 These subtypes available are
  The subtypes DEC, DECIMAL, and NUMBER are used to
declare fixed point numbers with maximum precision of 38 decimal
digits.
  The subtype DOUBLE PRECESION AND FLOAT are used
to declare floating point numbers with a maximum precision of 126 binary
digits
  The real subtype is used to declare floating point numbers
with maximum precision of 63 binary digits, roughly equivalents to 18
decimal digits.
  The subtypes INTEGER ,INT and SMALLINT are used to
declare integers with a maximum precision of 38 decimal digits

PLS_INTERGES

 PLS_INTERGES datatype is used to store singed integers.


 The magnitude range is -2 31 ..2 31.
 PLS_INTERGES value require less storage than NUMBER values
 They use machine arithmetic, hence result in faster calculation.

PL/SQL Character and String Types:


 Character types let you store alphanumeric data, represent words and test, and
also manipulate character strings.

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

CHAR Subtype (character);


 It has the same range of values as its base type.
 CHARACTER is just another name for CHAR, having compatibility with
ANSI/ISO and IBM types.

BOOLEAN TYPES:

 It is used to represent Boolean values TRUE and FALSE.


 It is used to store high logical values TRUE, FALSE and NULL.
 It takes no parameters, inserts and Selects not accepted.

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;

ASSIGNING VALUES TO A VARIABLE


 In PL/SQL a variable can be assigned in three ways:
 By using assignment operator (: =)
 By selecting or fetching database values.
 By passing it as an OUT or INPUT parameter to subprogram.

PRESENTING DATA ON THE SCREEN:


 For producing outputs on the video device we need the assistance of

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;

APPLYING SUBSTITUTION VARIABLES:

 PL/SQL is not a stand alone programming language; it only exists as a tool


within the oracle programming environment.
 Because of the alone mentioned standard it does not really have capabilities to
accept input from user.
 For accepting input the substitutions variables can be used, which can be
either '&’ or '&&’.
 Substitutions variables cannot be used to output the values.
 The substitution of the values is actually done by the SQL*Plus environment,
before the PL/SQL block is sent to the database.

VERY SIMPLE WAY TO START:

SQL > DECLARE


V_string1 VARCHAR2 (10):='Naresh';
V_string2 VARCHAR2 (10):='Krishna';
BEGIN
DBMS_OUTPUT.PUT_LINE ('My first Name is: '|| ' '||V_string1 );

Oracle_10g By Naresh A K
186

DBMS_OUTPUT.PUT_LINE ('My Second Name is: '|| ' '||V_string2);


END;

STEPS TO COMPILE & PRODUCE OUTPUT.

 At SQL prompt type.


 SET SERVEROUTPUT ON;
 Place forward slash and press Enter Key to execute the procedure.

OPERATOR in PL/SQL:

 Logical
 Arithmetic
 Concatenation
 Parenthesis to control order of operations.
 Exponentiation.
 Comparison.
 SQL*Plus

NESTED BLOCKS & VARIABLE SCOPE:

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

DBMS_OUTPUT.PUT_LINE ('The value of X:=' || ' '||X);


END;

USING NAMED BLOCKS TO INCREASE VISIBILITY:

<< FIRSTBLOCK >>


DECLARE
X NUMBER :=10;
BEGIN
DBMS_OUTPUT.PUT_LINE ('The value of X: =' || ' '||X); --10
<< SECBLOCK >>
DECLARE
X NUMBER :=20;
BEGIN
DBMS_OUTPUT.PUT_LINE ('The value of X:=' || ' '||
FIRSTBLOCK.X); --10
END;
DBMS_OUTPUT.PUT_LINE (' The value of X:=' || ' '||X); --10
END;

VARIABLE TYPES IN PL/SQL PROGRAMMING:

 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:

SQL > VARIABLE G_SALARY NUMBER;

SQL > DECLARE


V_SAL NUMBER;
BEGIN
Select sal INTO V_SAL from EMP where empno=7566;
:G_SALARY := V_Sal;
Dbms_output.put_line(:g_salary);
END;

SQL > PRINT G_SALARY;

Example2:

SQL > VARIABLE BIND_VARIABLE NUMBER;


SQL > DECLARE
V_NUM1 NUMBER :=&NUM1;
V_NUM2 NUMBER :=&NUM2;
BEGIN
:BIND_VARIABLE := (V_NUM1 / V_NUM2) + V_NUM2;
END;

SQL > PRINT BIND_VARIABLE;

Oracle_10g By Naresh A K
189

CONTROLL STURCTURES IN PL/SQL:


 To write programs that reflect the real time requirement, we need.
 Branching.
 Selection.
 Looping.

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;

 IF is a reserved word and marks the beginning of the IF statement.


 The End IF is a reserved phrase that indicates the end of the IF….Than
contract.
 When IF ... Then is executed, a condition is evaluated to either TRUE or
FALSE.

SQL >

IF - THEN -ELSE STATEMENT:

Oracle_10g By Naresh A K
190

 IF --THEN--ELSE statement enables to specify two group of statements.


 One group is evaluated when the condition evaluates to TRUE , the next
group is evaluated when the condition evaluated to FALSE.

Syntax:

IF Condition THEN
Statement1;
ELSE
Statement2;
END IF;
 This concept should be used when trying to choose between two mutually
exclusive actions.

Example:

SQL > DECLARE


V_NUM NUMBER :=&EnterNumber;
BEGIN
If mod (V_NUM, 2) = 0 THEN
Dbms_output.put_line (V_NUM || 'Is Even’);
ELSE
Dbms_output.put_line (V_NUM || 'Is Odd’);
End if;
End;

BEHAVIOR OF Null’s:

 If a confection is evaluated to NULL, then the statements will not be


executed, instead the control will be passed to the first executable statement
after the end if;
 In IF … THEN …ELSE construct the FALSE block is executed whenever the
condition evaluates to NULL.

Oracle_10g By Naresh A K
191

SQL > DECLARE

V_NUM1 NUMBER :=&EnterNumber1;


V_NUM2 NUMBER :=&EnterNumber2;
BEGIN

IF V_NUM1 is null THEN

Dbms_output.put_line ('Given Number are Equal’);

END IF;

Dbms_output.put_line ('Did you watch the NULL Effects’);


END;

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

 In this construct for every false of an IF condition another IF follows.


 This construct is also specified as ELSIF ladders.
 The application syntax can also be produced with ELSE if condition structure.
 For clarity purpose rather than ELSIF, ELSE IF construct is suggested.

Example:

SQL > DECLARE


V_day VARCHAR2 (3):=TO_CHAR (TO_DATE ('&YourDate’,
’DD-MON-YY’),’DY’);
BEGIN
IF V_day = 'SAT’ THEN
Dbms_output.put_line ('Enjoy Weekend’);

ELSIF V_day ='SUN’ THEN


Dbms_output.put_line ('Enjoy Weekend’);

ELSE
Dbms_output.put_line ('Have a Nice Day’);

END IF;
END;

SQL > SYSDATE

NESTED IF STATEMENTS:

Oracle_10g By Naresh A K
193

 The IF statements can be nested into one another as per requirements.


 NESTED IF is a situation in which an IF follows another IF immediately for
every true statement of an IF.
 Each IF is considered as an individual block of IF and needs proper nesting.

Syntax:

IF Condition THEN
IF Condition THEN
Statement1;
ELSE
IF Condition THEN
Statement2;
ELSE
Statement3;
END IF;
END IF;
ELSE
Statement4;
END IF;

SQL > DECLARE


V_Year NUMBER :=&YEAR;
BEGIN
IF MOD (V_Year,4) =0 THEN
IF MOD (V_Year, 100) <> 0 THEN
Dbms_output.put_line (V_Year || 'is a Leap Year’);
ELSE
IF MOD ( V_Year,4) =0 THEN
Dbms_output.put_line (V_Year || 'is a Leap Year’);
ELSE
Dbms_output.put_line (V_Year || 'is Not a Leap Year’);
END IF;
END IF;
ELSE

Oracle_10g By Naresh A K
194

Dbms_output.put_line (V_Year || 'is Not a Leap Year’);


END IF;
END;

ELSE IF LADDER:

 This is a situation where a condition is followed for every FALSE state of an


IF condition.
 Each FALSE state is immediately associated with a condition of its own.

Syntax:

IF condition THEN
Statement1;
ELSIF condition THEN
Statement2;
ELSIF condition THEN
Statement3;
ELSE
Statement4;
END IF;

SQL > DECLARE


V_OPERATOR VARCHAR2(2) :='&OPERATOr';
V_NUM1 NUMBER :=&EnterNumber1;
V_NUM2 NUMBER :=&EnterNumber2;

BEGIN

IF V_OPERATOR = '+'THEN
Dbms_output.put_line (TO_NUMBER (V_NUM1 + V_NUM2) );

ELSIF V_OPERATOR = '-' THEN


Dbms_output.put_line (TO_NUMBER (V_NUM1 -V_NUM2) );

ELSIF V_OPERATOR = '*' THEN


Dbms_output.put_line (TO_NUMBER (V_NUM1 * V_NUM2) );

ELSIF V_OPERATOR = '/'THEN


Dbms_output.put_line (TO_NUMBER (V_NUM1 / V_NUM2) );
ELSE

Oracle_10g By Naresh A K
195

Dbms_output.put_line ('Check Operator');


END IF;
END;

SELECTIONS IN PL/SQL

 The Selection strategy is implemented in PL/SQL using CASE Statements.


 The CASE statements in PL/SQL has two forms:
 Simple CASE
 Searched CASE
 In simple CASE we have to specify a Selector, which determines which group
of action to get executed.
 In Searched CASE, the Selector is not present, it has search Conditions that
are evaluated in .

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

TRUE , FASLE or NULL.


 When a particular search condition evaluates to True, the group of statements
associated with this condition are executed.

Syntax:

CASE
WHEN SearchCondtion1 THEN Statement;
WHEN SearchCondtion1 THEN Statement;
ELSE
END CASE;

 When a Search condition evaluates to True, control is passed to the statement


associated with it.
 If no Search condition yields to True, then statements associated with Else
caluse are executed.

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:

 The result of an expression yields a single value that is assigned to a variable.


 A CASE expression is an expression where the CASE evaluates an
expression to a single value and it is assigned to a variable.
 A CASE expression has a structure similar to a CASE statement.
 In CASE expression the END CASE is not implemented , instead only END,
is used.
 If any value is returned through CASE expression , then ensure that it always
returns the same data type as executed.

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;

BASIC OR SIMPLE LOOP:

 It is the simplest form of the LOOP construct in PL/SQL.


 It encloses a sequence of statements between the keywords LOOP and END
LOOP.
 It allows execution of its statements at least once.
 The keep the LOOP in finite state the EXIT statement is used.

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;

IF V_num > 5 THEN


EXIT;
END IF;
END LOOP;
Dbms_output.put_line('The Total lines of outputs are '||to_char(V_num -
1));
END;

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

Dbms_output.put_line('The Line' ||V_num ||'Output is' ||V_num );

Oracle_10g By Naresh A K
201

V_num :=V_num + 1;

EXIT WHEN V_num > 5;

END LOOP;
Dbms_output.put_line('The Total lines of outputs are '||to_char(V_num -1));

END;

NESTED LOOPS:

 It is a situation where one loop is embedded into the other.


The outer loop and the inner loop get associated with one another and execute
DECLARE
V_num NUMBER := &1;

BEGIN

LOOP

Dbms_output.put_line('The Line' ||V_num ||'Output is' ||V_num );


V_num :=V_num + 1;

EXIT WHEN V_num > 5;

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:

 It can be used to repeat a sequence of statements until the controlling


condition is no longer TRUE.
 The condition is evaluated at the start of each iteration.
 The loop terminates when the condition is FALSE.

Syntax:

WHILE condition LOOP


Statement1;
Statement2;
END LOOP;

Oracle_10g By Naresh A K
203

 If the condition yields NULL, the loop is bypassed and control passes to the
next statement.

NESTED LOOPS & LABLES:

 Loop’s can be nested to multiple levels.


 All the LOOP can be nested into one another.
 LOOP can be labeled as per the requirements.
 A label is placed before the statement, either on the same line or on a separate
line.
 Labels loops by placing the label before the word loop within the label
delimiters.
 When the loop is labeled, the label name can be optionally included after the
END LOOP statement for clarity.

Example1:

DECLARE
V_num NUMBER (2) := &1;
V_output VARCHAR2(100);

BEGIN

WHILE V_num <=10


LOOP
V_output := V_output || ' '||V_num ;
Dbms_output.put_line(V_output);
V_num := V_num +1;
END LOOP;
-- Dbms_output.put_line(V_output);

END;

Example2:

DECLARE
V_num NUMBER :=&EntNoForReverse;
V_output NUMBER :=0;
V_Position NUMBER ;

Oracle_10g By Naresh A K
204

BEGIN

WHILE V_num > 0


LOOP
V_Position :=MOD(V_num ,10);
V_output :=(V_output*10) + V_Position ;
V_num :=TRUNC(V_num /10);
Dbms_output.put_line(V_output);
END LOOP;

END;

FOR LOOP:

 It has the same general structure as the basic loop.


 FOR LOOP contains a control statement at the front of the LOOP keyword, to
determine the number of iterations that pl/sql performs.

Syntax:

FOR counter IN [ REVERSE ]


Lower Bound .. Upper Bound LOOP

Statement1;
Statement2;
END LOOP;

Counter: It is an implicitly declared integer whose value automatically increased


or decreased by 1 on each iteration of the LOOP until the upper bound or lower
bound is reached.

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

 The counter need not be declared, as it is implicitly declared as an integer.


 The lower bound and the upper bond of the loop can be literals, variables, or
expressions, but they should be evaluated to integers.
 The lower and upper bonds of LOOP statements need not be numeric literals,
they can be expressions that convert to numeric values.

Example:

SQL > DECLARE


V_Startvalue NUMBER :=&Startvalue;
v_EndValue NUMBER :=&EndValue;
V_output VARCHAR2(200) :=NULL;

BEGIN
Dbms_output.put_line('FOR LOOP START........!');

FOR i IN V_Startvalue .. v_EndValue


LOOP
V_output := V_output ||' '||I ;

END LOOP;
Dbms_output.put_line(V_output);

END;

REVERSE OF A NUMBER USING FOR LOOP:

Oracle_10g By Naresh A K
206

SQL > DECLARE


V_Startvalue NUMBER :=&Startvalue;
v_EndValue NUMBER :=&EndValue;
V_output VARCHAR2(200) :=NULL;

BEGIN
Dbms_output.put_line('FOR LOOP START........!');

FOR i IN REVERSE V_Startvalue .. v_EndValue


LOOP

V_output := V_output ||' '||I ;

END LOOP;
Dbms_output.put_line(V_output);
END;

Example: Factorial of a number.

SQL > DECLARE


V_FactNo NUMBER :=&FactNo;
V_Factorial NUMBER :=1;

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

PRINTING THE NAME IN VERTICAL ORDER USING FOR LOOP:

SQL > DECLARE


V_Name VARCHAR2(30):='&NAME';
V_Position VARCHAR2(100) :=NULL;

BEGIN
Dbms_output.put_line('FOR LOOP START........!');

FOR i IN reverse 1 ..LENGTH (V_Name)


LOOP

V_Position := V_Position || ' '||SUBSTR(V_Name,I,1);

Dbms_output.put_line(V_Position );
V_Position :=NULL;
END LOOP;

END;

USING SQL WITH PL/SQL:

DATA RETRIEVAL STANDARDS:

 Data retrieval options range from basic Select statement to pattern matching
with regular expressions

SQL > Select statement

Syntax: SELECT selectList


[ INTO variable List ]
FROM table list

Oracle_10g By Naresh A K
208

[ WHERE where clause ]


[ ORDER BY columnList ]
 The SlectList can be columns, strings, Built in functions or * retrieve data.
 Arithmetic operations are allowed in the SelectList.
 Variables can be declared as a single data type, or anchored data type or entire
record types.
 The table list can be one or more tables, views or inline views.
 The Where clause restricts the result set.
 When selecting a value into a variable, be sure to return one and only one
variable.
 Only one record can be returned into a Select statement in PL/SQL.
 The common error encountered are;

ORA-01403-NO DATA FOUND.


ORA-01422 -Exact fetch returns more than requested number of rows.

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;

Dbms_output.put_line('The Name:' ||' '||V_Ename );


Dbms_output.put_line('The job:' ||' '|| V_JOB);
Dbms_output.put_line('The sal:' ||' '|| V_SAL);

END;

%TYPE VARIABLE DECLARATION:


 The % Type variable is used to anchor pl/sql variable to the database type
columns.
 This methodology is more suitable where the variable that is declared into the
program is mapping directly to a column in the database table.

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:

SQL > DECLARE

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;

Dbms_output.put_line('The Name:' ||' '||V_Ename );


Dbms_output.put_line('The job:' ||' '|| V_JOB);
Dbms_output.put_line('The sal:' ||' '|| V_SAL);

END;

%ROWTYPE ATTRIBUTES:

 To declare a record based on a collection of columns in a database table or


view, we can use the %ROWTYPE attribute.
 The fields in the records take their names and data types from the columns of
the table or view.
 The record can also store an entire row of data fetched from cursor or cursor
variable.
 Prefix %ROWTYPE with the database table.

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:

SQL > DECLARE


V_DEPTNO EMP.DEPTNO%TYPE:=&EnterDEPTNO;
v_EmpRecord EMP%ROWTYPE;

BEGIN
SELECT * INTO v_EmpRecord
from emp where DEPTNO=V_DEPTNO;

Dbms_output.put_line('The Name:' ||' '||v_EmpRecord.ENAME);


Dbms_output.put_line('The job:' ||' '|| v_EmpRecord.JOB);
Dbms_output.put_line('The sal:' ||' '|| v_EmpRecord.SAL);

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;

Dbms_output.put_line('The Name:' ||' '||v_EmpRecord.ENAME);


Dbms_output.put_line('The job:' ||' '|| v_EmpRecord.JOB);
Dbms_output.put_line('The sal:' ||' '|| v_EmpRecord.SAL);

END;

SQL > DECLARE

V_EMPNO EMP.EMPNO%TYPE:=&EnterEMPNO;
v_EmpRecord EMP%ROWTYPE;

BEGIN
SELECT * INTO v_EmpRecord
from emp where EMPNO=V_EMPNO ;

Dbms_output.put_line('The Name:' ||' '||v_EmpRecord.ENAME);


Dbms_output.put_line('The job:' ||' '|| v_EmpRecord.JOB);
Dbms_output.put_line('The sal:' ||' '|| v_EmpRecord.SAL);
Dbms_output.put_line('The sal:' ||' '|| v_EmpRecord.HIREDATE);

END;

Oracle_10g By Naresh A K
212

CURSOR IN PL/SQL

 To process SQL statements Oracle needs to create an area of memory know as


the Context Area, or Process Global Area (PGA).
 The Context Area contains the information needed to process the statement.
 The Context Area information includes.
 The number of rows processed by the statement.
 A pointer to parsed representation of the statements.
 Every query contains an Active Set, which refers to the rows that will be
returned by the Query.

Definition: Cursor is handle, or pointer to the Context Area.

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.

The Process flow of an implicit Cursor is:

 Any given PL/SQL block issued an implicit Cursor whenever an SQL


statement is executed, as long as explicit cursor does not exist.
 A Cursor is automatically associated with every DML statement.
 All Update and Delete statements have Cursors that identify the set of rows
that will be affected by the operations.
 An Insert statement needs a place to receive the data that is to be inserted in
the database, which is handled by the implicit cursor.
 The most recently opened cursor is called SQL% cursor.
 During processing of an implicit cursor, oracle automatically perform Open,
Fetch and Close.

CURSOR ATTRIBUTES:
 The attributes return information about the execution of a data manipulation
statement.

 %ISOPEN: Evaluate to True if the Cursor is open.


 %NOTFOUND : Evaluates to True if the most recent fetch does not returns a
row.
 %FOUND : Evaluates to True if the most recent fetch return a row.
 %ROWCOUNT : Evaluates the total number of row returned so far.

SQL > DECLARE


V_Deptno EMP.Deptno%TYPE :=&Deptno;
V_Sal EMP.SAL%Type :=&Sal;
BEGIN

Update EMP Set Sal= V_Sal where deptno =V_Deptno ;


Dbms_Output.Put_Line (SQL%ROWCOUNT ||'Rows Updated');

If SQL %NOTFOUND then


Dbms_Output.Put_Line ('Not Found');

Oracle_10g By Naresh A K
214

End if;
END;

SQL> select * from sample;

 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.

The Pseudo Structure:

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.

CURSOR WITH SIMPLE LOOPS:


 It can be used with the same syntax as discussed in simple loops or basic
loops.
 Within the loop each record in the active set is retrieved and used.

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:

SQL > DECLARE


Cursor EMPCur is Select * from EMP;
V_EMPcur EMPcur%ROWTYPE;

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;

CUSOR WITH FOR LOOP

 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:

SQL > DECLARE


Cursor EMPCur is Select * from EMP;
V_EMPcur EMPcur%ROWTYPE;
BEGIN

Oracle_10g By Naresh A K
217

FOR V_EMPcur in EMPcur LOOP


Dbms_Output.Put_Line (V_EMPcur.Ename ||' '||V_EMPcur.Deptno);
END LOOP;
END;

CURSOR FOR LOOPS USING SUBQURIES


 If a Sub query is instituted into a Pl/SQL block then a Cursor Declaration is
not necessary.
 In this case the Sub Query is embedded into the For Loop.

Example:

SQL > DECLARE


V_Dname Dept.Dname%Type;
V_Loc Dept.Loc%Type;

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;

APPLYING CURSOR ATTRUBUTE INTO PRACTICE:


 FETCH rows only when the cursor is Open.
 Use the %ISOPEN cursor attributes before performing a Fetch to test whether
the Cursor is Open or Not.
 Use the %ROWCOUNT cursor attributes to retrieve an exact number of
rows.
 Use the %NOTFOUND cursor attribute to determine when to exit the loop;

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;

Cursor EMPcurs is Select Empno, Ename, Sal, Job from EMP;


Begin
OPEN EMPcurs;
LOOP

FETCH EMPcurs INTO v_Empno ,V_Ename , V_Sal ,V_Disig ;


EXIT WHEN EMPcurs%NOTFOUND OR EMPcurs%ROWCOUNT >5;
Dbms_Output.Put_Line (v_Empno || '' ||V_Ename ||' '|| V_Disig );
END LOOP;

CLOSE EMPcurs ;
End;

APPLYING TRANSACTION BASED ON DATA FETCHED THROUGH


CURSOR;

SQL > CREATE TABLE sample (Ename Varchar2 (20), Salary number (10,2));

SQL > DECLARE


V_Number Number (4):=&GiveTheNumber;
V_Ename EMP.Ename%Type;
V_Sal EMP.Sal%Type;
Cursor EMPCur is Select Ename, Sal from EMP Where Sal is Not NULL order
by Sal desc;
BEGIN
Open EMPcur;
Fetch EMPcur INTO V_Ename, V_Sal;

WHILE EMPcur%ROWCOUNT <=V_Number AND EMPcur%FOUND


LOOP

INSERT INTO sample (Ename, Salary) VALUES (V_Ename,V_Sal );


Fetch EMPcur INTO V_Ename, V_Sal;

END LOOP;

Oracle_10g By Naresh A K
219

Close EMPcur;
END;

Example:2

SQL > DECLARE


V_Number Number (4):=&GiveTheNumber;
V_Ename EMP.Ename%Type;
V_CurrentSal EMP.Sal%Type;
V_LastSal EMP.Sal%Type;
V_Job EMP.Job%Type;
Cursor EMPCur is Select Ename, Sal, Job from EMP Where Sal is Not NULL
order by Empno desc;

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;

CORSOR WITH PARAMETERS:


 A cursor can be declared with parameters.
 The advantages are:
 Enables generation of specific result sets.

Oracle_10g By Naresh A K
220

 Marks the cursor reusable.


 Cursor parameters can be assigned with DEFAULT value.
 The Mode of cursor parameters can be only INMODE.
 If a Cursor is declared as taking parameters then it must be called with a
values for that parameter.

Syntax:

CURSOR < cusor_name > ( Parameter DATAtype) is Select statement………..

Example:

Declare
Cursor EMPCur (PDeptno NUMBER, Pdesig VARCHAR2) IS
Select Empno, Ename, Job from EMP Where Deptno = V_Deptno and
Job=V_desig;

SELECT * FROM ZON_LINE_TEST;

SQL > DECLARE


V_Empno EMP.Empno%Type;
V_Ename EMP.Ename%Type;
Cursor EMPCur (P_Deptno NUMBER, P_Job VARCHAR2) IS
Select Empno, Ename from EMP Where Deptno = P_Deptno and
Job=P_Job;

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

SQL > DECLARE


V_Empno EMP.Empno%Type;
V_Ename EMP.Ename%Type;
Cursor EMPCur (P_Deptno NUMBER, P_Job VARCHAR2) IS
Select Empno, Ename from EMP Where Deptno = P_Deptno and
Job=P_Job;

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.

WORKING WITH CURSOR COMMUNICATION.

 The values that are fetched by one cursor can be passed as a parameters to the
other cursor and make the programming more dynamic.

SQL > DECLARE

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;

Cursor EMPcurs is Select Empno, Ename, Sal, Job from EMP;


Begin
IF NOT EMPcurs%ISOPEN THEN
OPEN EMPcurs;
END IF;

LOOP

FETCH EMPcurs INTO v_Empno ,V_Ename , V_Sal ,V_Disig ;


EXIT WHEN EMPcurs%NOTFOUND OR EMPcurs%ROWCOUNT >5;
Dbms_Output.Put_Line (v_Empno || '' ||V_Ename ||' '|| V_Disig );
END LOOP;

CLOSE EMPcurs ;
End;

CURSOR WITH FOR UPDATE CLAUSE:

 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

Cursor sample_cur is Select ……


From …..
FOR UPDATE [ OF ColumnReerence] [ NOWAIT ]

 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:

 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.

Where CURRENT OF CURSORNAME:

 We can update rows based on criteria from a Cursor.


 We can Write Delete or Update statement to contain the Where Current OF
Cursor Name to refer to the latest row processed by the Fetch statement.
 Where Current of when used, the Cursor must contain the For Update clause.

Example:

SQL > DECLARE


Cursor c1 is Select Sal from EMP Where Deptno=10 FOR UPDATE OF
Sal nowait;

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

CURSOR WITH SUBQUERIES:

 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.

SQL > DECLARE


V_Deptno Dept.Deptno%Type;
V_Staff NUMBER(4);
Cursor StaffCountCur is Select T1.Deptno, T2.Staff from Dept T1, (Select
Deptno, Count(*) Staff from EMP Group by Deptno ) T2 Where T1.Deptno =
T2.Deptno and T2.Staff >=5;
BEGIN
OPEN StaffCountCur;
LOOP
FETCH StaffCountCur INTO V_Deptno ,V_Staff ;
EXIT WHEN StaffCountCur%NOTFOUND;
Dbms_output.put_line( V_Deptno || ' ' ||V_Staff );
END LOOP;
CLOSE StaffCountCur ;

END;

Oracle_10g By Naresh A K
225

WORKING WITH EXCEPTION:

 It is an IDENTIFIER in PL/SQL, raised during the execution of a block that


termination its main body of Actions.
 A block terminates when PL/SQL raises an Exceptions, by specifying and
Exception Handler we can perform final action.

METHODS TO RAISE AN EXCEPTION


 When An Oracle Error occurs and the associated exception is raised
automatically.
 Raise the Exception explicitly by issuing the Raise statement with in the
block.
 The RAISED EXCEPTION can be either User Defined or Predefined.

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:

 If an Exception is raised in the executable section of the block and there is no


corresponding exception handler than the Pl/SQL block terminates with
failure and the exception is propagated to the calling encampment.

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:

EXCEPTION TYPE: Predefined Oracle Server Errors.


 Description: These are one of appropriately 20 errors that occur most often in
the PL/SQL code.
 Handling Tip: Do not declare and allow the Oracle Server to Raise them
implicitly.

Oracle SQLCODE
Exception Error Value
ACCESS_INTO_NULL ORA-06530 -6530

CASE_NOT_FOUND ORA-06592 -6592

COLLECTION_IS_NULL ORA-06531 -6531

CURSOR_ALREADY_OPEN ORA-06511 -6511

DUP_VAL_ON_INDEX ORA-00001 -1

Oracle_10g By Naresh A K
227

Oracle SQLCODE
Exception Error Value
INVALID_CURSOR ORA-01001 -1001

INVALID_NUMBER ORA-01722 -1722

LOGIN_DENIED ORA-01017 -1017

NO_DATA_FOUND ORA-01403 +100

NOT_LOGGED_ON ORA-01012 -1012

PROGRAM_ERROR ORA-06501 -6501

ROWTYPE_MISMATCH ORA-06504 -6504

SELF_IS_NULL ORA-30625 -30625

STORAGE_ERROR ORA-06500 -6500

SUBSCRIPT_BEYOND_COUNT ORA-06533 -6533

SUBSCRIPT_OUTSIDE_LIMIT ORA-06532 -6532

SYS_INVALID_ROWID ORA-01410 -1410

TIMEOUT_ON_RESOURCE ORA-00051 -51

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR/ numeric or value error: ORA-06502 -6502

ZERO_DIVIDE ORA-01476 -1476

ORA-01001 -1001

INVALID_CURSOR

INVALID_NUMBER ORA-01722 -1722

Oracle_10g By Naresh A K
228

 Exception Type: Non-Predefined Oracle Server Errors.


 Description: it is any other standard Oracle Server Errors.
 Handling Tip: Declare with in the declarative Section and allow the Oracle
Server to raise them implicitly

 Exception Type: User Defined Errors.


 Description: It is any condition that the develops determines, which is
abnormal.
 Handling Tip: Declare within the declarative section and raise explicitly.

WHEN ‘OTHER’ EXCEPTION HANDLER:

 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.

TRAPPING EXCEPTION GUIDELINES.

 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.

HANDLING PREDEFINED EXCEPTION

 A predefined oracle Server Error is Trapped by referencing its standard name


within the corresponding Exception Handling at Runtime.
 All predefined exceptions are declared by PL/SQL is the Standard package.

Oracle_10g By Naresh A K
229

Predefined Exception Syntax:

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

SQL > DECLARE


V_Ename EMP.Ename%Type;
V_Sal EMP.Sal%Type;

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;

****************************************************************

SQL > DROP TABLE EMESSAGE;

SQL > CREATE TABLE EMESSAGE (MESSAGE VARCHAR2(50),ERROR


VARCHAR2(20));

Example:1

Oracle_10g By Naresh A K
230

SQL > DECLARE


V_Ename EMP.Ename%Type;
V_Sal EMP.Sal%Type :=&Sal;

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 );

Dbms_output.put_line('No such EMPloyee exists with Salary' ||' ' ||V_Sal );


WHEN TOO_MANY_ROWS THEN
INSERT INTO Emessage (message) Values ('More than one EMPloyee
with that Salary'||' ' ||V_Sal );
WHEN OTHERS THEN
INSERT INTO Emessage (message) Values ('Un Recognized Error
Occurred');
End;

****************************************************************
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;

TRAPPING NON PREDEFINED ORACLE SERVER ERROR:

 The Non predefined oracle server error is trapped by declaring it first or by


using the OTHERS handles.
 The declared exception is raised implicitly.
 The PL/SQL PRAGAMA EXCEPTION_INIT can be used for associating
exception name with an oracle error number.
 The PRAGAMA EXCEPTION_INIT tells the Pl/SQL compiler to associate
an exception name with an oracle error number.
 The PRAGAMA EXCEPTION_INIT allows the programmer to refer to any
internal exception by name and write that to specific handles.
 The statement is not processed when that PL/SQL block is executed rather the
PRAGMA directs the PL/SQL compiles to interpret all occurrences of the
exception name within the block as the associated oracle server error number.

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

SQL> ALTER TABLE EMP ADD CONSTRAINT EMP_DEPTNO_FK


FOREIGN KEY(DEPTNO) REFERENCES DEPT(DEPTNO);

SQL> DELETE FROM DEPT;

SQL > DECLARE


V_ErroCode Number;
V_ErrMessage VARCHAR2(200);
V_Deptno Dept.Deptno%Type :=&Deptno;
E_EMPRemaining Exception;
PRAGMA EXCEPTION_INIT ( E_EMPRemaining ,-02292);

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;

****************************************************************

SQL > DECLARE


E_EMPExists Exception;
PRAGMA EXCEPTION_INIT ( E_EMPExists ,-2292);
V_Empno EMP.Empno%Type := &EMPlyeeNumber;

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 E_EMPExists THEN


DBMS_OUTPUT.PUT_LINE('Cannot be deleted as Dependent EMPloyee
Exits');
END;

FUNCTIONS FOR TRAPPING 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.

SQL CODE VALUES:


 0  No exception encountered.
 1  User Defined Exception
 +100  NO_DATA_FOUND Exception
 Negative Number  Any other oracle server error number.
 The maximum length of a message returned by the SQLERRM function 512
bytes.
 These functions are more specific usage when we used OTHER then
exception handle such that the unknown error can be treated and handed it's a
more proper way.

Oracle_10g By Naresh A K
234

SQL > DECLARE

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;

SQL > DECLARE


V_ErroCode Number;
V_ErrMessage VARCHAR2(200);
E_EMPRemaining Exception;
PRAGMA EXCEPTION_INIT ( E_EMPRemaining ,-02292);
V_Deptno Dept.Deptno%Type :=&Deptno;

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

DBMS_OUTPUT.PUT_LINE ('Error Message:'||V_ErrMessage );


DBMS_OUTPUT.PUT_LINE('Unable to delete as EMPloyee exist');
END;
****************************************************************
SQL> CREATE TABLE Audittable (Modified_By VARCHAR2(30),
Modified_date DATE, Message VARCHAR2(300));

SQL> CREATE TABLE TRAPPED_MESSAGE ( ErrNum NUMBER, ErrMsg


VARCHAR2(300));

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

INSERT INTO trapped_Message (ErrNum, ErrMsg) VALUES (V_ErroCode, V_ErrMessage);


End;
END;

TRAPPING USER DEFINED EXCEPTION

 PL/SQL helps to determine customized exceptions.


 User define PL/SQL exception must be
 Declared in the Declare section of the PL/SQL block.
 Raised explicitly with RAISE statements.
 The general process followed is as follows:

 The steps followed are:


1. Declare the Name for the defined exception.
2. Use the RAISE statement to raise the exception writing the executable
section.

Oracle_10g By Naresh A K
236

3. Reference the declared exception within the corresponding exception


handling runtime.

SQL> ALTER TABLE DEPT ADD CONSTRAINT DEPT_DEPTNO_PK PRIMARY KEY


(DEPTNO);

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

WHEN E_InvalidDept THEN


--INSERT INTO Audittable (Modified_By, Modified_date, Message) values
(USER, Sysdate, 'Tried Illegal Update');
DBMS_OUTPUT.PUT_LINE(‘YES’);

END;

EXCEPTION PROPAGATION:

 Instead of trapping an exception within the Pl/SQL block we can propagate


the exception to allow the calling environment to handle ti.
 Each calling environment has its own way of displaying and accessing errors.
 If a Pl/SQL raises an exception and the current block does not have a handles
then the exception propagates in successive enclosing blocks until it finds a
handles.

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;

RE-RAISING AND EXCEPTION:

 It is a situation Where we want to handle an exception in the inner block and


then pass ti to the outer block.

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:

 RAISE APPLICATION_ERROR is a procedure that lets us to issue


USER_DEFINED error message from stored sub program.
 It is used to communicate a predefined exception interactively by retiring a
non standard error code and error message.
 Using the procedure we can report error to application and avoid returning
unhandled exceptions.

Syntax;

RAISE_APPLICATION_ERROR ( error no, message, [true | false]);

 Error no is a user specified number for the exception between -20000 to -

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;

DBMS_OUTPUT.PUT_LINE('The total EMPloyee are: '||' '||V_TotEMP );

WORKING WITH PROCEDURE

 Benefits of modular coding


 It is more reusable.
 It is more manageable.

BLOCK STRUCTURE:

 Block structure is common for all modules.


 The block begin with a
 Header (for named block only)
 Name of the module

Oracle_10g By Naresh A K
240

 The parameter list if used.


 The declaration section
 VARIABLE
 CURSORS
 SUB BLOCKS
 The main part of the module is the execution section.
 Contains all calculations and processing.
 IF THEN ELSE
 LOOPS
 Calls to there PL/SQL modules.
 The last section is exception handles.

Syntax:

CREATE OR REPLACE PROCEFUE < procedure name > ( paramerter ) IS/AS


KEYWORD
< Variable declaration >
BEGIN
EXECUTABLE STATEMENT…..

EXCEPTION
Exception handler………
End <Procedure Name >;

 Procedure can have 0 or many parameters.


 Every procedure consist of Two part.
 The header
 The body
 The header
 It comes before the AS keword.
 It contains the procedure name and the parameter list.
 The body
 It is any thing or every thing that is existing after the AS
keyword
 The word REPLACE is optional.

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;

 To execute a procedure we can follow any one of the follwing method.


 Use EXECUTE procedure in SQL*Plus

EXEC MYBONUS;

 Call the procedure in another PL/SQL block.

Begin
mybonus;
End;

QUERING THE DATA DICTIONARY FOR INFORMATION ON


PROCEDURES:

 The information upon procedures is provided in


 USER_OBJECTS VIEWS
 USER_SOURCE VIEWS

SQL > SQL> Select object_name, object_type, status from USER_OBJECTS


Where object_name='MYBONUS';

SQL > COLUMN TEXT FORMAT a70;

Oracle_10g By Naresh A K
242

SQL > Select TO_CHAR (line,99) || '>',text from USER_SOURCE Where


name='MYBONUS';

RECOMPILE AN EXISTING PROCEDURE

SQL > Alter procedure < procedure name > compile;


SQL > Alter procedure mybonus compile;

PASSING PARAMETER IN AND OUT OF PROCEDURES:

 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.

 MODE: OUT  passes a valued back from the program.


 It is WRITE ONLY value.
 Cannot assign default values.
 Value assigned only if the program is successful.

 MODE: INOUT  Passes values is and also sends values back.


 Has to be variable.
 Values will be read and then written.

Example:

Create or replace procedure ODDNUMBER (num1 NUMBER, num2


NUMBER) IS

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;

SQL> EXEC ODDNUMBER(1,10);

****************************************************************

Create or replace procedure FindEMP ( I_Empno IN NUMBER, O_Ename OUT


VARCHAR2,O_Job OUT VARCHAR2) IS

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;

Calling the procedure

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;

****************************************************************

CREATE OR REPLACE PROCEDURE EMPInfo (I_Deptno IN NUMBER) IS


Cursor EMPinfoCur is Select Ename, Job, Sal, Commfrom EMP Where
Deptno=I_Deptno ;
EMPRecord EMPinfoCur%ROWTYPE;

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);

TSalary: =TSalary + EMPRecord.Sal ;


NEMPloyee := NEMPloyee+1;
END LOOP;
AVGSalary : =Salary / NEMPloyee;
Dbms_output.put_line('No of EMPloyee :' || NEMPloyee);
Dbms_output.put_line('Total Salary :'|| TSalary);
Dbms_output.put_line('Avg Salary:'||AvgSalary );
Close EMPinfoCur;
End EMPinfo;

SQL> exec EMPInfo(10);

WORKING WITH USER DEFINED FUNCTIONS:

 Functions in PL/SQL are stored code and are similar to procedures


 The function is a PL/SQL block that return a single value.

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.

CREATE OR REPLACE FUNCTION Factorial (Num NUMBER) RETURN


NUMBER
IS
Fact NUMBER(4) :=1;
BEGIN
FOR I IN REVERSE 1..Num LOOP
Fact:=Fact*I;
End loop;
RETURN Fact;
End;

Oracle_10g By Naresh A K
246

CALLING A FUNCTION FOR EXECUTION.


Method1 :
SQL > Select Factorial (4) from dual;

Method2 :

Declare
V_fact NUMBER(4):=0;
Begin
V_Fact :=Factorial(6);
Dbms_output.put_line('the factorial is :' ||' '|| V_fact );
End;

Example2:

CREATE OR REPLACE FUNCTION EMPExp ( V_Empno NUMBER)


RETURN NUMBER
IS
V_Hiredate EMP.Hiredate%Type;
V_Exp NUMBER(3):=0;
begin
Select Hiredate into V_Hiredate from EMP Where Empno=V_Empno ;
v_Exp :=MONTHS_BETWEEN (Sysdate, V_Hiredate )/12;
RETURN V_Exp ;
END;

SQL> select EMPExp (7566) from dual;

SQL > CREATE OR REPLACE FUNCTION is_socsecno(string_in IN


VARCHAR2)RETURN BOOLEAN IS
incorrect EXCEPTION;
delim CHAR(1);
part1 NUMBER(3,0);
part2 NUMBER(2,0);
part3 NUMBER(4,0);

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;

SQL > BEGIN


IF is_socsecno('123-45-6789') THEN
dbms_output.put_line('True');
ELSE
dbms_output.put_line('False');
END IF;
END;

Oracle_10g By Naresh A K
248

SQL > CREATE OR REPLACE PROCEDURE PROD1


(N1 NUMBER, N2 NUMBER, TOTAL OUT NUMBER) IS
BEGIN
TOTAL :=N1 +N2;
END;

SQL > DECLARE


TOTAL NUMBER;
BEGIN
PROD1 (10,20,TOTAL);
DBMS_OUTPUT.PUT_LINE(TOTAL);
END;

WORKING WITH PACKAGES:

A package is a group of procedures, functions, variables and SQL statements


created as a single unit. It is used to store together related objects. A package has
two parts, Package Specification or spec or package header and Package Body.
Package Specification acts as an interface to the package. Declaration of types,
variables, constants, exceptions, cursors and subprograms is done in Package
specifications. Package specification does not contain any code.
Package body is used to provide implementation for the subprograms, queries for
the cursors declared in the package specification or spec.

NOTE: If the specification of the package declares only types, constants,


variables, exceptions, and call specs the package body is not required there.

Oracle_10g By Naresh A K
249

This type of packages only contains global variables that will be used by
subprograms or cursors.

 PACKAGE is a method to handle all the required functions and procedures


together.
 A well designed package is a logical grouping of objects such as
 FUNCTION
 PROCEDURE
 GLOBAL VARIABLES.
 CURSORS.
 All of the code is loaded on the first call of the package.
 The first call to the package is very expansion but all subsequent calls will
result is an improved performance.
 PACKAGE should be taken very seriously in all such applications Where
PROCEDURE and FUNCTION are used repeatedly.
 PACKAGE does not provide any additional level of security.
 The structure of a PACKAGE encourages the TOP Down approach.

PACKAGE SPECIFICATION:

 The PACKAGE Specification contains information about the contents of the


PACKAGE.
 PACKAGE Specification contains declaration of GLOBAL / Public
variables.
 Anything placed in the declarative section of a PL/SQL block can be coded
in the PACKAGE body.
 All objects placed in the PACKAGE specification are called Public Objects.
 Any Function or Procedure not in the PACKAGE Specification, but coded
in the PACKAGE body is called private function or procedure.

Example:

SQL > Create or Replace Package empinfor AS

Oracle_10g By Naresh A K
250

Procedure Findemp ( I_empno IN Emp.empno%Type,


O_Ename OUT Emp.ename%Type,
O_job OUT Emp.job%Type);
Function EmpXp( V_empno NUMBER)RETURN NUMBER;
End empinfor ;

SQL> drop package empinfor;

Example:

SQL > Create or replace package PACK1 AS


PROCEDURE PROC1;
FUNCTION FUN1 RETURN VARCHAR2;
END PACK1;

SQL > CREATE OR REPLACE PACKAGE BODY PACK1 AS


PROCEDURE PROC1 IS
BEGIN
DBMS_OUTPUT.PUT_LINE('MY FIRST PACKAGE');
END PROC1;

FUNCTION FUN1 RETURN VARCHAR2 IS


BEGIN
RETURN ('HELLO FROM FUN1');
END FUN1;
END PACK1;

Executing Procedure and function from above package

SQL> exec pack1.proc1;

SQL> select pack1.fun1 from dual;

Oracle_10g By Naresh A K
251

Example2:

SQL > CREATE or replace package deptpack as


PROCEDURE address (deptno NUMBER, Dname VARCHAR2,
Loc VARCHAR2);

PROCEDURE Delrecord (i_deptno NUMBER);


END DEPTPACK;

SQL > CREATE OR REPLACE PACKAGE BODY DEPTPACK AS


PROCEDURE address (deptno NUMBER, Dname VARCHAR2,
Loc VARCHAR2) IS
BEGIN
INSERT INTO DEPT VALUES (DEPTNO,DNAME,LOC);
END ADDRESS;

PROCEDURE Delrecord (i_deptno NUMBER) IS


Begin
DELETE FROM DEPT WHERE DEPTNO=I_DEPTNO;
End DELRECORD;
END DEPTPACK;

SQL > EXEC DEPTPACK.DELRECORD(40);


SQL> EXEC DEPTPACK.ADDRESS(50,'APPS','HYD');

Overloading Packaged Subprograms:

Similar to the overloading concept in other programming languages PL/SQL also


allows you to overload its subprograms.
We can have more than one subprogram with the same name within a package

Oracle_10g By Naresh A K
252

Following examples better explain this concept.

SQL > CREATE OR REPLACE PACKAGE MYPACK2 AS


PROCEDURE AMOUNT (N NUMBER);
PROCEDURE AMOUNT (N VARCHAR2);
END MYPACK2;

SQL > CREATE OR REPLACE PACKAGE BODY MYPACK2 AS


PROCEDURE AMOUNT (N NUMBER) IS
BEGIN
DBMS_OUTPUT.PUT_LINE('Rs.'||TO_CHAR(TO_DATE(N,'J'),'JSP')||'O
NLY');
END AMOUNT;

PROCEDURE AMOUNT (N VARCHAR2) IS


BEGIN
DBMS_OUTPUT.PUT_LINE ('Rs.'||N||'ONLY');
END AMOUNT;

END MYPACK2;

SQL > EXEC MYPACK2.AMOUNT(1200);

SQL > EXEC MYPACK2.AMOUNT('TWELVE THOUDAND');

Private and Public Items in packages

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.

SQL > CREATE OR REPLACE PACKAGE PACK3 AS


PROCEDURE EMPInfo (I_Deptno IN NUMBER);

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);

TSalary :=NVL(TSalary ,0)+ EMPRecord.Sal ;


NEMPloyee := NEMPloyee+1;
END LOOP;
AVGSalary :=TSalary / NEMPloyee;
Dbms_output.put_line('No of EMPloyee :' || NEMPloyee);
Dbms_output.put_line('Total Salary :'|| TSalary);
Dbms_output.put_line('Avg Salary:'||AvgSalary );
Close EMPinfoCur;
End EMPinfo;

FUNCTION EMPExp ( V_Empno NUMBER)


RETURN NUMBER
IS
V_Hiredate EMP.Hiredate%Type;
V_Exp NUMBER(3):=0;
begin
Select Hiredate into V_Hiredate from EMP Where Empno=V_Empno ;
v_Exp :=MONTHS_BETWEEN (Sysdate, V_Hiredate )/12;
RETURN V_Exp ;

Oracle_10g By Naresh A K
254

END;

END PACK3 ;

SQL > select pack3.empexp(7566) from dual;

APPLYING COMPOSIT DATATYES IN PL/SQL


 The composite data types in PL/SQL are also called as COLLECTION.
 The types of composite data types in PL/SQL are:
 RECORD type
 PLSSQL TABLE OR ASSOCIATE ARRAY
 NESTED TABLE
 VARRAY

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

A collection method is a built-in function or procedure that operates on collections and is


called using dot notation.
collection_name.method_name[(parameters)]
Collection methods cannot be called from SQL statements.
Only the EXISTS method can be used on a NULL collection.
all other methods applied on a null collection raise the COLLECTION_IS_NULL error.

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.

SQL > Declare


TYPE TYP_TAB IS TABLE OF NUMBER;
my_tab TYP_TAB := TYP_TAB( 1, 2, 3, 4, 6 );
Begin
Dbms_output.Put_line( 'COUNT = ' || To_Char( my_tab.COUNT ) ) ;
End ;

LIMIT
Returns the maximum number of elements that a varray can contain.
Return NULL for Nested tables and Index-by tables

SQL > Declare


TYPE TYP_ARRAY IS ARRAY(30) OF NUMBER ;
my_array TYP_ARRAY := TYP_ARRAY( 1, 2, 5 ) ;
Begin
dbms_output.put_line( 'Max array size is ' || my_array.LIMIT ) ;
End;

Oracle_10g By Naresh A K
256

FIRST and LAST


Returns the first or last subscript of a collection.
If the collection is empty, FIRST and LAST return NULL

SQL > Declare


TYPE TYP_TAB IS TABLE OF NUMBER;
my_tab TYP_TAB := TYP_TAB( 1, 2, 3, 4, 5 );

Begin

For i IN my_tab.FIRST .. my_tab.LAST Loop


Dbms_output.Put_line(my_tab(i) ) ;
End loop ;
End ;

PRIOR(index) and NEXT(index)


Returns the previous or next subscript of the index element.
If the index element has no predecessor, PRIOR(index) returns NULL. Likewise, if index has
no successor, NEXT(index) returns NULL.

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:

TYPE TYPE_NAME IS RECORD


( FIELD_DECLARATION [ FIELD_DECLARATION ]…..)
IDENTIFIER TYPE-NAME;

Defining and Declaring a PL/SQL RECORD.

 To create a record, we define a record type and then declare record of that type.

 Type Name  is the name of the Record Type.

Oracle_10g By Naresh A K
258

 FieldName  is the name of the field within the Record.


 Field Type  is the data type of the field.
 Expr  is the field type or an initial value.

 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:

SQL > DECLARE


TYPE EmpRecordType is RECORD
( Empno NUMBER (4) NOT NULL :=1000,
Ename Emp.ename%type,
Job Emp.job%type);
EmpRecord EmpRecordType ;
Begin
-------------------
------------------
End;

Example:

DECLARE
V_Empno NUMBER(4):=&EnterEmpno;

TYPE EmpRecordType is RECORD


( V_Ename Emp.ename%type,
V_Job Emp.job%type,
V_Deptno Emp.deptno%Type
);

EmpRecord EmpRecordType ;

BEGIN

SELECT Ename, Deptno, Job INTO


EmpRecord.V_Ename,EmpRecord.V_Deptno ,EmpRecord.v_Job
FROM EMP
WHERE Empno=V_Empno;

Oracle_10g By Naresh A K
259

dbms_output.put_line('Employee Name' || EmpRecord.V_Ename);


dbms_output.put_line('Employee Name' || EmpRecord.V_Deptno);
dbms_output.put_line('Employee Name' || EmpRecord.v_Job);

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.

SQL> CREATE TYPE MIMBERS_VA3 AS VARRAY (10) OF VARCHAR2 (20);

SQL > CREATE TABLE PROJECT2


(PROJID NUMBER (5),
PROJNAME VARCHAR2 (25),
TEAMLEAD VARCHAR2 (25),
TEAMMEMBERS MIMBERS_VA3);

SQL> DESC PROJECT ;

We use the following query to see the datatype of MEMBERS_VA

Oracle_10g By Naresh A K
260

SQL > SELECT * FROM USER_COLL_TYPES WHERE


TYPE_NAME='MEMBERS_VA3';

SQL> DESC MEMBERS_VA1;

SQL> INSERT INTO PROJECT2 VALUES (1,'EMPLOYEE


PAYROLL','NARESH',MIMBERS_VA3('KUMAR','AK','SUJATHA'));

Varrays (short for variable-size arrays) hold a fixed number of elements


(although you can change the number of elements at runtime). They use
sequential numbers as subscripts. You can define equivalent SQL types, allowing
varrays to be stored in database tables. They can be stored and retrieved through
SQL, but with less flexibility than nested tables.

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 ;

SQL > DECLARE


TYPE NUMLIST IS TABLE OF NUMBER;
V_NUMLIST NUMLIST :=NUMLIST(10,20,30,40,50);

BEGIN

V_NUMLIST.DELETE(2);
V_NUMLIST(3):=100;

FOR I IN V_NUMLIST.FIRST .. V_NUMLIST.LAST LOOP


IF V_NUMLIST.EXISTS(I) THEN
DBMS_OUTPUT.PUT_LINE(I);
DBMS_OUTPUT.PUT_LINE(V_NUMLIST(I));
END IF;
END LOOP;
END;

SQL > DECLARE


TYPE NUMLIST IS TABLE OF NUMBER;
V_NUMLIST NUMLIST :=NUMLIST(10,20,30,40,50);

BEGIN

FOR I IN V_NUMLIST.FIRST .. V_NUMLIST.LAST LOOP


DBMS_OUTPUT.PUT_LINE(V_NUMLIST(I));

END LOOP;
END;

Oracle_10g By Naresh A K
262

SQL > DECLARE


TYPE LIST1 IS TABLE OF EMP.ENAME%TYPE;
V_LIST1 LIST1;

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;

SQL > DECLARE


TYPE LIST1 IS TABLE OF EMP.ENAME%TYPE;
V_LIST1 LIST1;

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;

Index-by binary integer


TYPE type_name IS TABLE OF element_type [NOT NULL]
INDEX BY [BINARY_INTEGER | PLS_INTEGER |
VARCHAR2(size_limit)];
INDEX BY key_type;

The key_type can be numeric, either BINARY_INTEGER or PLS_INTEGER .

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 ;

SQL > DECLARE


TYPE TYP_TAB IS TABLE OF NUMBER
INDEX BY PLS_INTEGER ;
my_tab TYP_TAB ;

Begin
my_tab(1) := 5 ;
my_tab(2) := 10 ;
my_tab(3) := 15 ;

FOR I IN MY_TAB.FIRST.. MY_TAB.LAST LOOP


DBMS_OUTPUT.PUT_LINE(MY_TAB(I));
END LOOP;
End ;

Bulk Binds (BULK COLLECT & FORALL) and Record


Processing in Oracle
This article is an update of one written for Oracle 8i (Bulk Binds) which includes new
features available in Oracle 9i Release 2 and beyond.

 Introduction

 BULK COLLECT

 FORALL

 SQL%BULK_ROWCOUNT

 SAVE EXCEPTIONS and SQL%BULK_EXCEPTION

 Bulk Binds and Triggers

 Updates

Oracle_10g By Naresh A K
264

Related articles.

 FORALL Support for Sparse Collections (10gR1)

 PLS-00436 Restriction in FORALL Statements Removed (11gR1)

 APPEND_VALUES Hint (11gR2)

 Collections in Oracle PL/SQL

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.

CREATE TABLE bulk_collect_test AS


SELECT owner,
object_name,
object_id
FROM all_objects;

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;

l_tab t_bulk_collect_test_tab := t_bulk_collect_test_tab();


l_start NUMBER;
BEGIN
-- Time a regular population.
l_start := DBMS_UTILITY.get_time;

FOR cur_rec IN (SELECT *


FROM bulk_collect_test)
LOOP
l_tab.extend;
l_tab(l_tab.last) := cur_rec;
END LOOP;

Oracle_10g By Naresh A K
266

DBMS_OUTPUT.put_line('Regular (' || l_tab.count || ' rows): ' ||


(DBMS_UTILITY.get_time - l_start));

-- Time bulk population.


l_start := DBMS_UTILITY.get_time;

SELECT *
BULK COLLECT INTO l_tab
FROM bulk_collect_test;

DBMS_OUTPUT.put_line('Bulk (' || l_tab.count || ' rows): ' ||


(DBMS_UTILITY.get_time - l_start));
END;
/
Regular (42578 rows): 66
Bulk (42578 rows): 4

PL/SQL procedure successfully completed.

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;

-- Process contents of collection here.


DBMS_OUTPUT.put_line(l_tab.count || ' rows');
END LOOP;
CLOSE c_data;
END;
/
10000 rows
10000 rows
10000 rows
10000 rows
2578 rows

Oracle_10g By Naresh A K
268

PL/SQL procedure successfully completed.

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;

FOR cur_rec IN (SELECT *


FROM bulk_collect_test)
LOOP

Oracle_10g By Naresh A K
269

NULL;
END LOOP;

DBMS_OUTPUT.put_line('Regular : ' ||
(DBMS_UTILITY.get_time - l_start));

-- Time bulk with LIMIT 10.


l_start := DBMS_UTILITY.get_time;

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));

-- Time bulk with LIMIT 100.


l_start := DBMS_UTILITY.get_time;

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;

DBMS_OUTPUT.put_line('LIMIT 100: ' ||


(DBMS_UTILITY.get_time - l_start));

-- Time bulk with LIMIT 1000.


l_start := DBMS_UTILITY.get_time;

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;

DBMS_OUTPUT.put_line('LIMIT 1000: ' ||


(DBMS_UTILITY.get_time - l_start));
END;
/
Regular : 18
LIMIT 10 : 80
LIMIT 100: 15
LIMIT 1000: 10

PL/SQL procedure successfully completed.

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.

CREATE TABLE forall_test (


id NUMBER(10),
code VARCHAR2(10),
description VARCHAR2(50));

ALTER TABLE forall_test ADD (


CONSTRAINT forall_test_pk PRIMARY KEY (id));

ALTER TABLE forall_test ADD (


CONSTRAINT forall_test_uk UNIQUE (code));

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;

l_tab t_forall_test_tab := t_forall_test_tab();


l_start NUMBER;

Oracle_10g By Naresh A K
272

l_size NUMBER := 10000;


BEGIN
-- Populate collection.
FOR i IN 1 .. l_size LOOP
l_tab.extend;

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;

EXECUTE IMMEDIATE 'TRUNCATE TABLE forall_test';

-- Time regular inserts.


l_start := DBMS_UTILITY.get_time;

FOR i IN l_tab.first .. l_tab.last LOOP


INSERT INTO forall_test (id, code, description)
VALUES (l_tab(i).id, l_tab(i).code, l_tab(i).description);
END LOOP;

DBMS_OUTPUT.put_line('Normal Inserts: ' ||


(DBMS_UTILITY.get_time - l_start));

EXECUTE IMMEDIATE 'TRUNCATE TABLE forall_test';

-- Time bulk inserts.


l_start := DBMS_UTILITY.get_time;

Oracle_10g By Naresh A K
273

FORALL i IN l_tab.first .. l_tab.last


INSERT INTO forall_test VALUES l_tab(i);

DBMS_OUTPUT.put_line('Bulk Inserts : ' ||


(DBMS_UTILITY.get_time - l_start));

COMMIT;
END;
/
Normal Inserts: 305
Bulk Inserts : 14

PL/SQL procedure successfully completed.

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 t_id_tab := t_id_tab();


l_tab t_forall_test_tab := t_forall_test_tab ();
l_start NUMBER;
l_size NUMBER := 10000;
BEGIN
-- Populate collections.
FOR i IN 1 .. l_size LOOP
l_id_tab.extend;
l_tab.extend;

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;

-- Time regular updates.


l_start := DBMS_UTILITY.get_time;

FOR i IN l_tab.first .. l_tab.last LOOP


UPDATE forall_test
SET ROW = l_tab(i)
WHERE id = l_tab(i).id;
END LOOP;

DBMS_OUTPUT.put_line('Normal Updates : ' ||


(DBMS_UTILITY.get_time - l_start));

Oracle_10g By Naresh A K
275

l_start := DBMS_UTILITY.get_time;

-- Time bulk updates.


FORALL i IN l_tab.first .. l_tab.last
UPDATE forall_test
SET ROW = l_tab(i)
WHERE id = l_id_tab(i);

DBMS_OUTPUT.put_line('Bulk Updates : ' ||


(DBMS_UTILITY.get_time - l_start));

COMMIT;
END;
/
Normal Updates : 235
Bulk Updates : 20

PL/SQL procedure successfully completed.

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.

CREATE TABLE bulk_rowcount_test AS


SELECT *
FROM all_users;

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);

-- Report affected rows.


FOR i IN l_array.first .. l_array.last LOOP
DBMS_OUTPUT.put_line('Element: ' || RPAD(l_array(i), 15, ' ')
||
' Rows affected: ' || SQL%BULK_ROWCOUNT(i));
END LOOP;
END;
/
Element: NARESH Rows affected: 1
Element: SYS Rows affected: 1

Oracle_10g By Naresh A K
277

Element: SYSTEM Rows affected: 1


Element: DBSNMP Rows affected: 1
Element: BANANA Rows affected: 0

PL/SQL procedure successfully completed.

SQL>

So we can see that no rows were deleted when we performed a delete for the
username "BANANA".

SAVE EXCEPTIONS and SQL%BULK_EXCEPTION


We saw how the FORALL syntax allows us to perform bulk DML operations, but what
happens if one of those individual operations results in an exception? If there is no
exception handler, all the work done by the current bulk operation is rolled back. If
there is an exception handler, the work done prior to the exception is kept, but no
more processing is done. Neither of these situations is very satisfactory, so instead we
should use the SAVE EXCEPTIONS clause to capture the exceptions and allow us to
continue past them. We can subsequently look at the exceptions by referencing
the SQL%BULK_EXCEPTION cursor attribute. To see this in action create the following
table.

CREATE TABLE exception_test (


id NUMBER(10) NOT NULL
);

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;

l_tab t_tab := t_tab();


l_error_count NUMBER;

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;

EXECUTE IMMEDIATE 'TRUNCATE TABLE exception_test';

-- Perform a bulk operation.


BEGIN
FORALL i IN l_tab.first .. l_tab.last SAVE EXCEPTIONS
INSERT INTO exception_test
VALUES l_tab(i);
EXCEPTION
WHEN ex_dml_errors THEN

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 ()

PL/SQL procedure successfully completed.

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:

1. Unbounded (Specify the size)

3. Take negative subscripts

4. Not stored in dB

5. Not reusable.

6. Can’t be created @ SQL level

78. We can’t delete individual values from an AA.

9. We can’t use “Extend” method.

10. Acess value from a missing subscript then it will raise not data found.

11. Initialization is not required during the creation of the variable.

12. AA are also called as plsql tables or index by tables.

Nested Tables:

1. Unbounded

Oracle_10g By Naresh A K
281

3. Can’t take negative sub scripts.

4. Can’t take character sub scripts.

5. Can be stored in DB

6. It is reusable

7. Can delete individual elements

8. Dense in nature initially but they will become sparse in nature after deletions.

9. Exten method can be used.

10. No data found error.

11. Initialization is required.

Varrays:

1. Bounded

3. Can’t take negative sub scripts.

4. Stored in db

5. Reusable

6. Can be created at SQL level

7. Extend is required.

Oracle_10g By Naresh A K
282

Bulk Binds and Triggers


For bulk updates and deletes the timing points remain unchanged. Each row in the
collection triggers a before statement, before row, after row and after statement timing
point. For bulk inserts, the statement level triggers only fire at the start and the end of
the the whole bulk operation, rather than for each row of the collection. This can cause
some confusion if you are relying on the timing points from row-by-row processing.

You can see an example of this here.

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).

Working with Trigger:


What is a Trigger?
A trigger is a pl/sql block structure which is fired when a DML statements like Insert, Delete, Update is
executed on a database table. A trigger is triggered automatically when an associated DML statement is
executed.
Syntax of Triggers

Syntax for Creating a Trigger


CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }

Oracle_10g By Naresh A K
283

{INSERT [OR] | UPDATE [OR] | DELETE}


[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
BEGIN
--- sql statements
END;

 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.

1) Create the 'product' table and 'product_price_history' table

Oracle_10g By Naresh A K
284

CREATE TABLE product_price_history


(product_id number(5),
product_name varchar2(32),
supplier_name varchar2(32),
unit_price number(7,2) );

CREATE TABLE product


(product_id number(5),
product_name varchar2(32),
supplier_name varchar2(32),
unit_price number(7,2) );

2) Create the price_history_trigger and execute it.


CREATE or REPLACE TRIGGER price_history_trigger
BEFORE UPDATE OF unit_price
ON product
FOR EACH ROW
BEGIN
INSERT INTO product_price_history
VALUES
(:old.product_id,
:old.product_name,
:old.supplier_name,
:old.unit_price);
END;

3) Lets update the price of a product.

UPDATE PRODUCT SET unit_price = 800 WHERE product_id = 100


Once the above update query is executed, the trigger fires and updates the
'product_price_history' table.

4)If you ROLLBACK the transaction before committing to the database, the data inserted to
the table is also rolled back.

Types of PL/SQL Triggers


There are two types of triggers based on which level it is triggered.
1) Row level trigger - An event is triggered for each row upated, inserted or deleted.
2) Statement level trigger - An event is triggered for each sql statement executed.

PL/SQL Trigger Execution Hierarchy


The following hierarchy is followed when a trigger is fired.
1) BEFORE statement trigger fires first.
2) Next BEFORE row level trigger fires, once for each row affected.

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;

SELECT * FROM product_check;


Output:

Mesage Current_Date

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

Before update, statement level 26-Nov-2008


Before update, row level 26-Nov-2008
After update, Row level 26-Nov-2008
Before update, row level 26-Nov-2008
After update, Row level 26-Nov-2008
After update, statement level 26-Nov-2008

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.

How To know Information about


Triggers.
We can use the data dictionary view 'USER_TRIGGERS' to obtain information about any trigger.

The below statement shows the structure of the view 'USER_TRIGGERS'


DESC USER_TRIGGERS;

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'.

You can drop a trigger using the following command.


DROP TRIGGER trigger_name;

CYCLIC CASCADING in a TRIGGER


This is an undesirable situation where more than one trigger enter into an infinite loop.
while creating a trigger we should ensure the such a situtation does not exist.

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.

Trigger Enhancements in Oracle Database 11g Release 1


 Execution Order of Triggers

Oracle_10g By Naresh A K
288

 Compound Triggers

 Enable and Disable Triggers

Execution Order of Triggers


Oracle allows more than one trigger to be created for the same timing point, but it has
never guaranteed the execution order of those triggers. The Oracle 11g trigger syntax
now includes the FOLLOWS clause to guarantee execution order for triggers defined with
the same timing point. The following example creates a table with two triggers for the
same timing point.

CREATE TABLE trigger_follows_test (


id NUMBER,
description VARCHAR2(50)
);

CREATE OR REPLACE TRIGGER trigger_follows_test_trg_1


BEFORE INSERT ON trigger_follows_test
FOR EACH ROW
BEGIN
DBMS_OUTPUT.put_line('TRIGGER_FOLLOWS_TEST_TRG_1 - Executed');
END;
/

CREATE OR REPLACE TRIGGER trigger_follows_test_trg_2


BEFORE INSERT ON trigger_follows_test
FOR EACH ROW
BEGIN
DBMS_OUTPUT.put_line('TRIGGER_FOLLOWS_TEST_TRG_2 - Executed');
END;
/

If we insert into the test table, there is no guarantee of the execution order.

SQL> SET SERVEROUTPUT ON


SQL> INSERT INTO trigger_follows_test VALUES (1, 'ONE');
TRIGGER_FOLLOWS_TEST_TRG_1 - Executed
TRIGGER_FOLLOWS_TEST_TRG_2 - Executed

1 row created.

SQL>

We can specify that the TRIGGER_FOLLOWS_TEST_TRG_2 trigger should be executed before


the TRIGGER_FOLLOWS_TEST_TRG_1 trigger by recreating
the TRIGGER_FOLLOWS_TEST_TRG_1 trigger using the FOLLOWS clause.

CREATE OR REPLACE TRIGGER trigger_follows_test_trg_1


BEFORE INSERT ON trigger_follows_test
FOR EACH ROW

Oracle_10g By Naresh A K
289

BEGIN
DBMS_OUTPUT.put_line('TRIGGER_FOLLOWS_TEST_TRG_1 - Executed');
END;
/

Now the TRIGGER_FOLLOWS_TEST_TRG_1 trigger always follows


the TRIGGER_FOLLOWS_TEST_TRG_2 trigger.

SQL> SET SERVEROUTPUT ON


SQL> INSERT INTO trigger_follows_test VALUES (2, 'TWO');
TRIGGER_FOLLOWS_TEST_TRG_2 - Executed
TRIGGER_FOLLOWS_TEST_TRG_1 - Executed

1 row created.

SQL>

Don't forget to clean up the test table.

DROP TABLE trigger_follows_test;

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.

CREATE OR REPLACE TRIGGER <trigger-name>


FOR <trigger-action> ON <table-name>
COMPOUND TRIGGER

-- Global declaration.
g_global_variable VARCHAR2(10);

BEFORE STATEMENT IS
BEGIN
NULL; -- Do something here.
END BEFORE STATEMENT;

BEFORE EACH ROW IS

Oracle_10g By Naresh A K
290

BEGIN
NULL; -- Do something here.
END BEFORE EACH ROW;

AFTER EACH ROW IS


BEGIN
NULL; -- Do something here.
END AFTER 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.

CREATE TABLE compound_trigger_test (


id NUMBER,
description VARCHAR2(50)
);

CREATE OR REPLACE TRIGGER compound_trigger_test_trg


FOR INSERT OR UPDATE OR DELETE ON compound_trigger_test
COMPOUND TRIGGER

-- 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;

BEFORE EACH ROW IS


BEGIN
l_tab.extend;
CASE
WHEN INSERTING THEN

Oracle_10g By Naresh A K
291

l_tab(l_tab.last) := 'BEFORE EACH ROW - INSERT (new.id=' || :new.id


|| ')';
WHEN UPDATING THEN
l_tab(l_tab.last) := 'BEFORE EACH ROW - UPDATE (new.id=' || :new.id
|| ' old.id=' || :old.id || ')';
WHEN DELETING THEN
l_tab(l_tab.last) := 'BEFORE EACH ROW - DELETE (old.id=' || :old.id
|| ')';
END CASE;
END BEFORE EACH ROW;

AFTER EACH ROW IS


BEGIN
l_tab.extend;
CASE
WHEN INSERTING THEN
l_tab(l_tab.last) := 'AFTER EACH ROW - INSERT (new.id=' || :new.id
|| ')';
WHEN UPDATING THEN
l_tab(l_tab.last) := 'AFTER EACH ROW - UPDATE (new.id=' || :new.id
|| ' old.id=' || :old.id || ')';
WHEN DELETING THEN
l_tab(l_tab.last) := 'AFTER EACH ROW - DELETE (old.id=' || :old.id
|| ')';
END CASE;
END AFTER EACH ROW;

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;

FOR i IN l_tab.first .. l_tab.last LOOP


DBMS_OUTPUT.put_line(l_tab(i));
END LOOP;
l_tab.delete;
END AFTER STATEMENT;

END compound_trigger_test_trg;
/

create or replace trigger t8


for update on emp
COMPOUND TRIGGER
before statement is
begin
dbms_output.put_line('T8');
end before statement;

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.

SQL> SET SERVEROUTPUT ON


SQL> INSERT INTO compound_trigger_test VALUES (1, 'ONE');
BEFORE STATEMENT - INSERT
BEFORE EACH ROW - INSERT (new.id=1)
AFTER EACH ROW - INSERT (new.id=1)
AFTER STATEMENT - INSERT

1 row created.

SQL> INSERT INTO compound_trigger_test VALUES (2, 'TWO');


BEFORE STATEMENT - INSERT
BEFORE EACH ROW - INSERT (new.id=2)
AFTER EACH ROW - INSERT (new.id=2)
AFTER STATEMENT - INSERT

1 row created.

SQL> UPDATE compound_trigger_test SET id = id;


BEFORE STATEMENT - UPDATE
BEFORE EACH ROW - UPDATE (new.id=2 old.id=2)
AFTER EACH ROW - UPDATE (new.id=2 old.id=2)
BEFORE EACH ROW - UPDATE (new.id=1 old.id=1)
AFTER EACH ROW - UPDATE (new.id=1 old.id=1)
AFTER STATEMENT - UPDATE

2 rows updated.

SQL> DELETE FROM compound_trigger_test;


BEFORE STATEMENT - DELETE
BEFORE EACH ROW - DELETE (old.id=2)
AFTER EACH ROW - DELETE (old.id=2)
BEFORE EACH ROW - DELETE (old.id=1)
AFTER EACH ROW - DELETE (old.id=1)
AFTER STATEMENT - DELETE

2 rows deleted.

SQL>

Don't forget to clean up the test table.

DROP TABLE compound_trigger_test;

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.

CREATE OR REPLACE TRIGGER tab1_compound_trigger


FOR INSERT OR UPDATE ON tab1
COMPOUND TRIGGER

TYPE t_change_tab IS TABLE OF tab1_audit%ROWTYPE;


g_change_tab t_change_tab := t_change_tab();

AFTER EACH ROW IS


BEGIN
g_change_tab.extend;
g_change_tab(g_change_tab.last).id := tab1_audit_seq.NEXTVAL;
IF INSERTING THEN
g_change_tab(g_change_tab.last).action := 'INSERT';
ELSE
g_change_tab(g_change_tab.last).action := 'UPDATE';
END IF;
g_change_tab(g_change_tab.last).tab1_id := :new.id;
g_change_tab(g_change_tab.last).created_time := SYSTIMESTAMP;
END AFTER EACH ROW;

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;

FORALL i IN g_change_tab.first .. g_change_tab.last


INSERT INTO tab1_audit VALUES g_change_tab(i);

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

Enable and Disable Triggers


It has been possible to enable and disable triggers for some time using the ALTER
TRIGGER and ALTER TABLE commands.

 ALTER TRIGGER <trigger-name> DISABLE;

 ALTER TRIGGER <trigger-name> ENABLE;

 ALTER TABLE <table-name> DISABLE ALL TRIGGERS;

 ALTER TABLE <table-name> ENABLE ALL TRIGGERS;

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.

CREATE TABLE trigger_control_test (


id NUMBER,
description VARCHAR2(50)
);

CREATE OR REPLACE TRIGGER trigger_control_test_trg


BEFORE INSERT ON trigger_control_test
FOR EACH ROW
ENABLE
BEGIN
DBMS_OUTPUT.put_line('TRIGGER_CONTROL_TEST_TRG - Executed');
END;
/

SQL> SET SERVEROUTPUT ON


SQL> INSERT INTO trigger_control_test VALUES (1, 'ONE');
TRIGGER_CONTROL_TEST_TRG - Executed

1 row created.

SQL>

CREATE OR REPLACE TRIGGER trigger_control_test_trg


BEFORE INSERT ON trigger_control_test
FOR EACH ROW
DISABLE
BEGIN
DBMS_OUTPUT.put_line('TRIGGER_CONTROL_TEST_TRG - Executed');
END;
/

SQL> INSERT INTO trigger_control_test VALUES (2, 'TWO');

1 row created.

SQL>

Don't forget to clean up the test table.

Oracle_10g By Naresh A K
295

DROP TABLE trigger_control_test;

Follows Ordered Execution in Triggers


Since Oracle8, you have had the ability to define multiple triggers of the same type on
one table—e.g., two triggers both after each row on insert on the same table. The type
of triggers determine ordering of the execution: before statement, before row, after
statement, and after row. However, if you have two after-row triggers—T1 and T2—
which one will fire first?
The execution of triggers of the same type is somewhat random or at least not
guaranteed to follow a pattern. Does that pose a problem? Let's see an example of a
table called PAYMENTS, as shown below:
Name Null? Type
-----------------------------------------
-------- ----------------------------
PAY_ID NUMBER(10)
CREDIT_CARD_NO
VARCHAR2(16)
AMOUNT
NUMBER(13,2)
PAY_MODE VARCHAR2(1)
RISK_RATING VARCHAR2(6)
FOLLOW_UP VARCHAR2(1)

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;

Now, if you update the table:


SQL> get upd_pay
1 update payments set
2 credit_card_no = '1234567890123456',
3 amount = 100000,
4* pay_mode = 'K'

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

SQL> select * from payments;

PAY_ID CREDIT_CARD_NO AMOUNT P RISK_R F


---------- ---------------- ---------- -
------ -
1 1234567890123456 100000 C HIGH N

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.

SQL> select * from payments;

PAY_ID CREDIT_CARD_NO AMOUNT P RISK_R F


---------- ---------------- ---------- -
------ -
1 1234567890123456 100000 C HIGH Y

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.

When OTHERS Then Do Something


Many PL/SQL programmers resort to the dangerous practice of leaving the OTHERS
exception ignored, as shown below:
when OTHERS then
NULL;

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

SP2-0804: Procedure created with compilation warnings

SQL> show error


Errors for PROCEDURE MYPROC:

LINE/COL ERROR
--------
---------------------------------------------------------------
--
8/7 PLW-06009: procedure "MYPROC" OTHERS handler does not
end in
RAISE or RAISE_APPLICATION_ERROR

Materialized Views in Oracle

A materialized view, or snapshot as they were previously known,


is a table segment whose contents are periodically refreshed
based on a query, either against a local or remote table. Using
materialized views against remote tables is the simplest way to
achieve replication of data between sites. The example code in
this article assumes DB1 is the master instance and DB2 is the
materialized view site.

Basic Syntax

Check Privileges
Create Materialized View
Create Materialized View Logs
Refresh Materialized Views
Cleaning Up
Aggregations and Transformations

Considerations

The full syntax description for the CREATE MATERIALIZED VIEW


command is available in the documentation. Here we will only
concern ourselves with the basics.
-- Normal
CREATE MATERIALIZED VIEW view-name

Oracle_10g By Naresh A K
300

BUILD [IMMEDIATE | DEFERRED]


REFRESH [FAST | COMPLETE | FORCE ]
ON [COMMIT | DEMAND ]
[[ENABLE | DISABLE] QUERY REWRITE]
AS
SELECT ...;

-- 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.

The following refresh types are available.

FAST : A fast refresh is attempted. If materialized view logs


are not present against the source tables in advance, the
creation fails.

COMPLETE : The table segment supporting the materialized view


is truncated and repopulated completely using the associated
query.

FORCE : A fast refresh is attempted. If one is not possible a


complete refresh is performed.

A refresh can be triggered in one of two ways.

ON COMMIT : The refresh is triggered by a committed data change


in one of the dependent tables.

ON DEMAND : The refresh is initiated by a manual request or a


scheduled task.

The QUERY REWRITE clause tells the optimizer if the


materialized view should be consider for query rewrite
operations. An example of the query rewrite functionality is
shown below.

Oracle_10g By Naresh A K
301

The ON PREBUILT TABLE clause tells the database to use an


existing table segment, which must have the same name as the
materialized view and support the same column structure as the
query.

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

GRANT CREATE MATERIALIZED VIEW TO ak;


GRANT CREATE DATABASE LINK TO ak;
Create Materialized View
Connect to the materialized view owner and create the database
link and the materialized view itself.
CONNECT ak/ak@xe

CREATE DATABASE LINK xe.WORLD1 CONNECT TO naresh IDENTIFIED BY


naresh USING 'XE';

CREATE MATERIALIZED VIEW emp_mv


BUILD IMMEDIATE
REFRESH Fast
ON DEMAND
AS
SELECT * FROM emp@xe.world1;

CREATE MATERIALIZED VIEW emp_mv


BUILD IMMEDIATE
REFRESH FORCE
ON DEMAND
AS
SELECT * FROM emp@xe.world1;

EXEC DBMS_MVIEW.refresh('EMP_MV');

CREATE MATERIALIZED VIEW emp_mv


BUILD IMMEDIATE
REFRESH complete
ON DEMAND
AS

Oracle_10g By Naresh A K
302

SELECT * FROM emp@xe.world1;

Alternatively, we could have used a prebuilt table, as shown


below.
-- Create the tale first. This could be populated
-- using an export/import.

CREATE TABLE emp_mv AS


SELECT * FROM emp@db1.world;

-- Build the materialized view using the existing table


segment.
CREATE MATERIALIZED VIEW emp_mv
REFRESH FORCE
ON DEMAND
ON PREBUILT TABLE
AS
SELECT * FROM emp@xe.world;

Remember to gather stats after building the materialized view.


BEGIN
DBMS_STATS.gather_table_stats(
ownname => 'NARESH',
tabname => 'EMP_MV');
END;
/
Create Materialized View Logs

Since a complete refresh involves truncating the materialized


view segment and re-populating it using the related query, it
can be quite time consuming and involve a considerable amount
of network traffic when performed against a remote table. To
reduce the replication costs, materialized view logs can be
created to capture all changes to the base table since the last
refresh. This information allows a fast refresh, which only
needs to apply the changes rather than a complete refresh of
the materialized view.
To take advantage of the of the fast refresh, connect to the
master instance and create the materialized view log.
CONNECT naresh/nareshak@db1

CREATE MATERIALIZED VIEW LOG ON naresh.emp


--TABLESPACE users
WITH PRIMARY KEY
INCLUDING NEW VALUES;

Oracle_10g By Naresh A K
303

Refresh Materialized Views

If a materialized view is configured to refresh on commit, you


should never need to manually refresh it, unless a rebuild is
necessary. Remember, refreshing on commit is a very intensive
operation of a base tables. It makes sense to use fast
refreshes where possible.

For on demand refreshes, you can choose to manually refresh the


materialized view or refresh it as part of a refresh group.
The following code creates a refresh group defined to refresh
every minute and assigns a materialized view to it.
BEGIN
DBMS_REFRESH.make(
name => 'ak.MINUTE_REFRESH1',
list => '',
next_date => SYSDATE,
interval => '/*1:Mins*/ SYSDATE + 1/(60*24)',
implicit_destroy => FALSE,
lax => FALSE,
job => 0,
rollback_seg => NULL,
push_deferred_rpc => TRUE,
refresh_after_errors => TRUE,
purge_option => NULL,
parallelism => NULL,
heap_size => NULL);
END;
/

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.

Rather than using a refresh group, you can schedule


DBMS_MVIEW.REFRESH called using the Oracle Scheduler

Oracle_10g By Naresh A K
304

Cleaning Up

To clean up we must remove all objects.

CONNECT naresh/nareshak@db2

DROP MATERIALIZED VIEW emp_mv;


DROP DATABASE LINK xe.WORLD1;

BEGIN
DBMS_REFRESH.destroy(name =>'ak.MINUTE_REFRESH');
END;
/

CONNECT naresh/nareshak@db1
DROP MATERIALIZED VIEW LOG ON ak.emp;

Aggregations and Transformations


Materialized views can be used to improve the performance of a
variety of queries, including those performing aggregations and
transformations of the data. This allows the work to be done
once and used repeatedly by multiple sessions, reducing the
total load on the server.
The following query does an aggregation of the data in the EMP
table.

CONN naresh/nareshak
SET AUTOTRACE TRACE EXPLAIN

SELECT deptno, SUM(sal)


FROM emp
GROUP BY deptno;

---------------------------------------------------------------
------------
| 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

Create a materialized view to perform the aggregation in


advance, making sure you specify the ENABLE QUERY REWRITE
clause.

CREATE MATERIALIZED VIEW emp_aggr_mv


BUILD IMMEDIATE
REFRESH FORCE
ON DEMAND
ENABLE QUERY REWRITE
AS
SELECT deptno, SUM(sal) AS sal_by_dept
FROM emp
GROUP BY deptno;

EXEC DBMS_STATS.gather_table_stats(USER, 'EMP_AGGR_MV');


The same query is now rewritten to take advantage of the pre-
aggregated data in the materialized view, instead of the
session doing the work for itself.
--ALTER SESSION SET QUERY_REWRITE_INTEGRITY = TRUSTED;
--ALTER SESSION SET QUERY_REWRITE_ENABLED = TRUE;
SET AUTOTRACE TRACE EXPLAIN

SELECT deptno, SUM(sal)


FROM emp
GROUP BY deptno;

---------------------------------------------------------------
-----------------------------
| 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:

Populating a materialized view adds load to both servers


involved. The source server is queried to capture the data,
which is inserted into the destination server. Be sure the
additional load does not adversely affect your primary system.
Although materialized view logs improve the performance of
materialized view refreshes, they do increase the work needed
to perform DDL on the base table. Check the additional work
does not adversely affect performance on the primary system.

Oracle_10g By Naresh A K
306

If regular refreshes are not performed, materialized view logs


can grow very large, potentially reducing the performance of
their maintenance and blowing tablespace limits.
Depending on the Oracle version and the complexity of the
associated query, fast refreshes may not be possible.
When using materialized views to improve performance of
transformations and aggregations, the QUERY_REWRITE_INTEGRITY
and QUERY_REWRITE_ENABLED parameters must be set or the server
will not be able to automatically take advantages of query
rewrites. These parameters may be set in the pfile or spfile
file if they are needed permanently. Later releases have them
enabled by default.

CREATE MATERIALIZED VIEW


CREATE MATERIALIZED VIEW LOG

Package Name:

DBMS_REFRESH
DBMS_MVIEW

CREATE MATERIALIZED VIEW mv_test


AS
SELECT * from emp;

materialized view:

grant CREATE ANY MATERIALIZED VIEW to ak;

grant ON COMMIT REFRESH to ak;

alter session set query_rewrite_enabled=true;

alter table mv_test add(sal2);

alter table mv_test drop column sal2;

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;

Oracle PL/SQL – INSTEAD OF Trigger example


This article shows you how to use INSTEAD OF TRIGGER to update
1. A noneditioning view

2. A nested table column of a noneditioning view


This INSTEAD OF triggers provide a way to modify views that cannot be
modified directly through DML statements like INSERT, UPDATE and DELETE
An INSTEAD OF trigger is
1. Always a row-level trigger.

2. Can read OLD and NEW values, but cannot change them.

3. Cannot be conditional. Means we can not add WHEN or IF condition.

1. Insert Data into a View


In this example, we have created a INSTEAD OF trigger which will insert rows
into respective tables of a view when we execute the insert statement on a
view.

CREATE TABLE customer_details


(
customer_id number(10) primary key,
customer_name varchar2(20),
country varchar2(20)

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)
);

Create CPVIEW view to get results of customers and their projects.


CPVIEW

CREATE OR REPLACE VIEW CPVIEW AS


SELECT cust.customer_id, cust.customer_name, cust.country,
projectdtls.project_id, projectdtls.project_name,
projectdtls.project_start_Date
FROM customer_details cust, projects_details projectdtls
WHERE cust.customer_id = projectdtls.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

Instead, we should create a INSTEAD OF trigger on the view to perform the


actual operation.
T1
CREATE OR REPLACE TRIGGER T1
INSTEAD OF INSERT ON CPVIEW
DECLARE
duplicate_info EXCEPTION;
PRAGMA EXCEPTION_INIT (duplicate_info, -00001);
BEGIN

INSERT INTO customer_details


(customer_id,customer_name,country)
VALUES (:new.customer_id, :new.customer_name, :new.country);

INSERT INTO projects_details (project_id, project_name,


project_start_Date, customer_id)
VALUES (
:new.project_id,
:new.project_name,
:new.project_start_Date,
:new.customer_id);

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

INSERT INTO CPVIEW VALUES (2,'ABC Infotech','India',202,'HR


management',sysdate);

SELECT * FROM customer_details;


SELECT * FROM projects_details;
SELECT * FROM CPVIEW;

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');

insert into emp(empno,ename)values (10,'kumar');


end;

CREATE OR REPLACE TRIGGER T1


AFTER UPDATE OF SAL ON EMP
FOR EACH ROW

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.

SQL> UPDATE EMP


SET SAL = 800
WHERE DEPTNO = '10';

JOINS:

The rules of joins>


1. N-1 rule  No of Tables -1 for example: if you want
to join two tables then 2-1=1 join condition.
2. Where should I write this join condition. ( you have
to join in WHERE CLAUSE)
3. We required a common columns in both the table to
join.

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.

No of records from one table * no of records from another


table.

3. NoN equi join.  I need to find all the employees Grade


based on their respective Salary?
4. Outer joins.(+)  we can’t use IN and OR operators in
Outer joins.But we can use AND OPERATOR
5. Self join  if the information is coming from same table
then we are calling Self join.

Oracle_10g By Naresh A K
312

I need to find the location of each employees?

select empno,ename, Loc from emp,dept where deptno=deptno;

select empno,ename, Loc from emp,dept ;

What is schema?
Collection of objects.

What is object?  each object having its own Data Dictionary.


1. Table  USER_TABLES
2. Sequence  USER_SEQUENCES
3. Views  user_views
4. Role
5. Constraints
6. synonyms.

What is Data Dictionary ? -> it hold the specific information


about the objects.

DD  will start with User_ and All_ and dba_

What is sequences-> order might be Ase/Desc order.


User_sequences , all_sequences , dba_sequences.

Sequence will generate only numeric values.

1. I want to generate the sequence from 1 to 5?


There are two virtual columns called, CURRVAL AND NEXTVAL USED
ONLY WITH SEQUENCE.

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.

2. How to generate sequence in descending order.

create sequence s1
start with 5
increment by -1
minvalue 1
maxvalue 5
cycle

1 2 3 4 5 and this sequence is over. But again I want to start


from 1 to 5

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.

VIEWS: This is a schema object.


This is also a kind of table.

View is a logical or virtual table of a base table(emp) which


don’t hold the data.
1. Performance
2. Reporting
3. Re-usability.
4. Security. 1. WITH CHECK OPTION, WITH READ ONLY

 We have two types of views.


Simple view -> we can perform DML statement.
Complex View  if view created with, JOINS,Group
function,subquery,DISTINCT we are called complex views

Oracle_10g By Naresh A K
314

In complex view we can’t perform DML statement.if you want


to perform we have use “Instead of Trigger”

SUB-QUERY: - (SELECT STATEMENT ONLY)

WHAT IS QUERY?

Can I compare this?

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.

Instead of that we have to use SQ operators;


 IN /NOT IN
 <ANY / >ANY /<=ANY />=ANY
 Exists / not exists  internally it will work like
Boolean operator. True/False

Types of SQ:1.Inline view 2. Corelated subquery


1. Select
2. Aliease
3. Joins
4. Views
5. Group function

DEPTNO SUM(SAL) ename


------ -------- ---------
10 8750 king
10 8750 Miller
10 8750 clark

DEPTNO SUMSAL
------ ------
30 9400
20 11375
10 8750
E1

select e.deptno,e.sal from emp e where e.sal>(select avg(sal)


from emp e1 where
e.deptno=e1.deptno group by deptno) order by deptno

Oracle_10g By Naresh A K
315

Admin: DCL—DATA CONTROL LANGUAGE. This work is done Oracle DBA


guys.
 GRANT
 REVOKE

Object Name ROLES: is a collection of access/priveleges

Total 100 peoples are joining to IBM?

40 employees are freshers


40 employees are TL
20 employees are Manager.

Employee Id ,email id,account#,Access we have to create for all


100 employees?

We need to follow three steps:


1- Create the role.
2- Grant the piveleges to role. R1-select
3- Grant role(R1) to users (priya,Mahesh)………40 freshers..

Role data dictionary: user_tab_privs , user_sys_privs

Object Synonyms: it’s a alternate name for objects.

Type of synonyms: 1. Public 2. Private.

Security purpose.

User_synonyms

Oracle_10g By Naresh A K

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy