Sunteți pe pagina 1din 230

Information Technology For JTOs PH-II- IT

Bharat Sanchar Nigam Limited

Hkkjr lapkj fuxe fyfeVsM


JTO Ph-II
(Information Technology)
JUN-2011

BSNL
ORACLE RDBMS
WEEK-3

ES & IT FACULTY
COURSE CODE BRBCOIS113
BHARAT RATNA BHIMRAO AMBEDKAR
INSTITUTE OF TELECOM TRAINING,
RIDGE ROAD, JABALPUR 482 001
(ISO-9001: 2008 Certified)

BRBRAITT- June-2011

Information Technology For JTOs PH-II- IT

INDEX
S.No Title

Page No.

1. Overview of Oracle RDBMS

2. SQL Commands

17

3. Orace Built-in Functions

64

4. Joins, Subqueries

78

5. Oracle Schema ,Objects, views,sequence,


index, synonyms

90

6. Constraints

105

7. PL/SQL Engine, Block, Data Types

113

8. Control Structure, Exceptions, Triggers, Cursor

129

9. Stored Procedures, Functions & Packages

175

10. Oracle Architecture and User Management

193

BRBRAITT- June-2011

Information Technology For JTOs PH-II- IT

Chapter 1
Overview of Oracle RDBMS
Introduction
Oracle is the relational database management system (RDBMS) sold by
Oracle Corporation. It is the most widely used database.

Terminology used in RDBMS


The following terminologies are used in RDBMS.
Data : It is simply a collection of facts such as employees name,

desgn, tel.no
Database : It is the collection of interrelated data, stored together

w/o dupication which serves as a base for running one or more


applications in an optimized fashion. Physically database is a
collection of datafiles which stores all the database data. This
datafiles are stored in one of the storage device such as
Harddisk/floppy/CD.
DBMS : There is a layer between physical Database and user

which is nothing but called Database Management System which


manages & organises the physical Database for the users by
hiding the hardware details from the user such as in which
HD/Track/Sector the data is stored. Further data are added,
existing data are updated/queried.
RDBMS : RDBMS is BDBMS which manages the different sets of

data by setting relations among them.


Users : Those who enters data, running reports , maintains the
system such as taking backup, develops applications for using the
data are users

BRBRAITT- June-2011

Information Technology For JTOs PH-II- IT

User types
There are 3 types of users

DBA (routine users)

End users (Frequent users)

Application Programmers (Non Frequent users)

Advantageous of DBMS
A DBMS provides the following Advantageous

Minimal Redundancy

Privacy & Security

Data Integrity

Flexible Database Architecture

Minimal Redundancy
This is achieved by a process known as Normalization of Database
which is having 3 Forms

First Normal Form : Putting different sets of data separately without

redundancy by using primary key


Second Normal Form : Removing the data which partly depend on the
key & putting is separately

Third Normal Form : Removing the data which does not solely depend
on the key & putting is separately

BRBRAITT- June-2011

Information Technology For JTOs PH-II- IT

Privacy & Security


Users are protected against other users / external agents and
Communications mechanisms are protected against snooping /tampering. At the
same time administration provides adequate access to user and system data by
setting Authentication permission to access and controls the extent of access.

Data Integrity
The Integrity of data is ensured by various methods such as provision of
many Data types, defining of range of values, defining various Integrity
constraints like uniqueness, primary key, foreign key DBMS also protects the
data items and their association. It is having adequate protection against loss of
data due to h/w failure by BackUp & Recovery.

Characteristics of DBMS
Generally all DBMSs are having certain Characteristics in common as
follows.

Data abstraction

Data independence

Data Models

Data abstraction
It is the method of capturing data. There are 3 methods as follows.

BRBRAITT- June-2011

Information Technology For JTOs PH-II- IT

Physical Level : It is the lowest level of abstraction. Describes how


the data are actually stored for eg. In which sector/block of HD
etc.)

Conceptual Level : This is the next higher level of abstraction.


Describes what data are actually stored in the database & the
relationships that exists among the data. Here the entire database
is described in terms of a small no of relatively simple structures.
This is used by DBAs.

View/External Level : This is the highest level of abstraction.


Describes only part of entire database in different combination. The
system may provide many views for the same database.

Data independence
It is the ability to change the scheme definition in one level w/o
affecting other levels. The different types of independence are

Physical Data independence : It is the ability to modify the physical

scheme w/o causing application programs to be rewritten


Logical Data independence : It is the ability to modify the
conceptual scheme w/o causing application programs to be
rewritten

Data Models
Mapping of various data items that shows how they are related is
called Data Model. Data Models can be classified into

Object based logical Models : OBL models describe the data at


conceptual and view levels. Some of the well known models are
o Entity-Relationships model
o Object Oriented Model

Record based logical Models : RBL models also describe the data
at conceptual and view levels. Some are

BRBRAITT- June-2011

Information Technology For JTOs PH-II- IT


o Hierarchical Model
o Network Model
o Relational Model

Physical Data Models

BRBRAITT- June-2011

Information Technology For JTOs PH-II- IT

Hierarchical Model
Admn

Rama

SDE

15000

TVM

9000

Sita

JTO

10000

ENK

5900

In Hierarchical Data Model, Data is represented by a simple tree


structure. Here Data is represented by records and relationships among Data
is represented by links.
Network Model
Rama

SDE

TVM

15000

9000

Sita

JTO

ENK

10000

5900
I

It also represents the Data & relations by records and links.

BRBRAITT- June-2011

Information Technology For JTOs PH-II- IT

Relational Model

In the previous 2 models Data can be accessed by using pointer


concept. However the 3rd relational model is relatively simple. Here Data &
relations are represented by a collection of simple tables with relationships . It
is based on Codds rules
Codds rules

Information Rule : All information in a RDBMS including Table names,

Column names are represented by values in tables.


Guarnteed Data Access Rule : Every piece of data can be accessed by
using a combn of Table name, a primary key value that identifies the
row and a Column name identifies a cell.

Null Rule : The RDBMS distinguishes between zero, blank and null
values

On Line Query Rule : The description of a db & its contents can be


queried using DML.

BRBRAITT- June-2011

Information Technology For JTOs PH-II- IT

High level insert, update and delete : The RDBMS supports insertion,
updation and deletion

Physical Data independence : It is the ability to modify the physical


scheme w/o causing application programs to be rewritten.

Logical Data independence : It is the ability to modify the conceptual


scheme w/o causing application programs to be rewritten.

Integrity independence : It is the ability to modify the integrity


constraints w/o causing application programs to be rewritten.

Distribution independence : It is the ability to modify the distribution


methods w/o causing application programs to be rewritten.

Non subversion Rule : The RDBMS should access the information of a


record w/o bypassing Integrity constraints

Relational Database properties


No RDBMS follows all the 12 codds rules. Even the Oracle is powerful
RDBMS, it is not 100% relational.
RDBMS is having a Collection of objects or relations that stores the
data (Table) and a set of operators can act on the relations to produce other
relations. It possess data integrity to keep its data accurate and consistent
Table properties

Relational Database is composed of a collection of 2D tables

Each table is composed of a collection of rows & columns

Each row of data is uniquely identified by a primary key

Each column is uniquely named & possess data integrity

Data in the rows can be manipulated by executing SQL commands

BRBRAITT- June-2011

Information Technology For JTOs PH-II- IT


Features of Oracle 9i

It is an object Relational model

Object oriented RDBMS

The i in the version stands for the internet since

It powers the internet by securely supplying the data

Many commercial internet/intranet applications use oracle data

Provide support to Java (Java functions can be used in oracle


applications

Oracle RDBMS
It is known as Oracle Server. It is a Kernel package. The Kernel is a
set of physical data files and a set of background processes which is known as
instance. When the Oracle Server is executed, it starts an instance. An
instance is a set of background processes and system global area(SGA)
which is responsible for storage, retrieval & modification of data and Control
of access of data.
The architecture of Oracle Server is explained with the help of
following diagram.
Oracle database is a combination of physical database files and
instance which is known as Oracle server. The physical database files are
stored in 1 or more Hard Disks.
The various physical files that make Oracle database are

Data files : which stores database data. Tables/indexes/clusters data

are stored in data files.


Redo log files : which records databases transactions. It is to protect
the system from hardware crash.

Control files : The databases overall architecture is defined in control


files. It contains the location & other information of all other files. Since

BRBRAITT- June-2011

10

Information Technology For JTOs PH-II- IT


it is critical for the database normally multiple copies are stored in
different disks. Control files maintain internal consistency & guide
recovery operation.

Parameter file : It is text file which can be read/written. It stores various


oracle parameters such as Oracle Home, SID, location of Control files,
size & combination of instance.

Instance
An instance is a combination of background processes & Memory
structures as shown in the diagram which will be explained under DBA.

Advantageous of Oracle

It provides 4GL application development

Can be run in any platform

BRBRAITT- June-2011

11

Information Technology For JTOs PH-II- IT

Supports personal/ Client Server computing

Distributed processingParallel Processing

Replicated Processing

Less cost with Client Server

Supports large database

High security

Supports multiple users

Client Server
A Client Server System is more structured than general distributed
computing. In `is system a client sends request to servers to execute tasks.
The tasks may be just to provide information, or to perform a complex
computation (perhaps returning information). Client and servers are
asymmetric & a server may be a client of another server. It is having the
following characteristics.
Client Server Properties

Clients and servers are separate processes

They may run on the same or different machines

Each process can hide internal information

Each process can implement its own set of business rules

They communicate by peer to peer protocols

Advantages of Client Server

Exploits existing h/w s/w configurations

Matches distributed business models

BRBRAITT- June-2011

12

Information Technology For JTOs PH-II- IT

Scalable

The network is the computer

Less cost

Disadvantages of Client Server

Harder to build

Less stable

Susceptible to network load

Lacking in specialists

Difficult to debug

Difficult to test

Client-server model

BRBRAITT- June-2011

13

Information Technology For JTOs PH-II- IT

Distributed Computing
A Distributed Computing System is a set of computers connected in
some way (serial lines, ethernet, ATM, etc). Each computer is able to
communicate with some of the others. Programs running on each computer
are able to share information and request tasks to be executed/
Oracle Server
The relational database management system (RDBMS) sold by Oracle
Corporation. Components of Oracle Server include the kernel and various
utilities for use by DBAs and database users

BRBRAITT- June-2011

14

Information Technology For JTOs PH-II- IT

Communication
For Communication with Oracle server Structured Query
Language(SQL) is used. SQL was developed by ANSI in 1962. SQL is a
English like language. Oracle is the first company to use SQL. With SQL what
to select, update, insert, delete data can be done. It is having the following
categories of statements.

DML Data manipulation. Used for Querying, Entering /Editing

/deleting data
DDL- Data Definition Language used for Defining structures such as
creation of table/index/sequence objects.

DCL- Database Control Language used for DBA operations structures


such as starting & shutting down Database

BRBRAITT- June-2011

15

Information Technology For JTOs PH-II- IT

TCL-Transactions Control Language used for rollbacking(undo) and


saving statements

PL/SQL - superset of SQL(Add programming logic )

A 4GL

Used for creating stored procedures, packages, triggers


database events to occur

Oracle Products
The oracle server comes with a set of utilities known as Oracle
products as below.

SQL * Plus

Oracle Enterprise Manager (OEM)

Developer 6i with Forms, Reports and graphic tools

SQL Loader

SQL * Net

SQL * Plus
It is the command interpreter of Oracle Server. It Recognises SQL
commands, Carries them to Oracle server & Display the response from it. It is
having a set of commands for file manipulation, formatting
OEM
OEM is a comprehensive system management framework, built to
internet standards.
It provides administrators with a robust console, a rich set of tools,
using which DBAs Administer, diagnose, and tune multiple databases. It offers
graphical user interface.
Developer 6i

BRBRAITT- June-2011

16

Information Technology For JTOs PH-II- IT


The Main components of Developer 6i are

Oracle Forms 6i

Oracle Reports 6i

Which Includes multimedia information such as sound, image, charts

Oracle Forms 6i

Fill in the blank template for entering/showing data

Application Developers design Data Entry, Query Forms using this.

End users use this for DML operations

Oracle Reports 6i

O/P of Database can be powerfully presented using reports

Flexible for developing vide variety of reports such as Master/Detail,


Crosstab, labels, form letters

SQL loader
SQL loader allows to load data stored in a variety of formats into an
oracle database such as from text files
SQL *NET
It is a protocol that supports client server computing. Using this any
client can access any server without regard to network protocols.
Oracle Precompilers
This enables to embed SQL statement in programming languages like
Ada, C, CobolIt combines the power of host languages and the flexibility &
ease of SQL.

BRBRAITT- June-2011

17

Information Technology For JTOs PH-II- IT

BRBRAITT- June-2011

18

Information Technology For JTOs PH-II- IT

Chapter-2
SQL COMMANDS
SQL, SEQUEL (Structured English Query Language), is the standard language
used to communicate with a relational database. SQL was developed by IBM
Corporation.
Types of SQL Commands
SQL commands are used to perform various functions. These functions include
building database objects, manipulating objects, populating database tables with
data, updating existing data in tables, deleting data, performing database
queries, controlling database access, and overall database administration.
The main categories are
DDL (Data Definition Language)
DML (Data Manipulation Language)
DQL (Data Query Language)
DCL (Data Control Language)
DTL (Data Transaction Language)
Defining Database Structures
DDL (Data Definition Language) statements are statements to create and
manage database objects in the database. There are three primary DDL
statements:

CREATE - Creating a new database object.


ALTER - Altering the definition of an existing data object.
DROP - Dropping an existing data object.

Manipulating Data
DML (Data Manipulation Language) commands are statements to change data
values in database tables. There are three basic DML commands:

INSERT - Inserts new rows into database tables.


UPDATE - Updates existing rows in database tables
DELETE - Deletes existing rows from database tables

These commands are discussed in detail during "Manipulating Data."

BRBRAITT- June-2011

19

Information Technology For JTOs PH-II- IT


Selecting Data
DQL (Data Query Language) is the basic query command for modern relational
database users. The most frequently used SQL statement in any database
application is
SELECT - Retrieve data from one or more tables, or views, with
different selection criteria, grouping criteria and sorting orders

Data Control Language


DCL (Data control Language) commands in SQL allow to control access to
data within the database. These DCL commands are normally used to create
objects related to user access and also control the distribution of privileges
among users. The basic data control commands are
grants access privileges for database objects to other
users
REVOKE revokes access privileges for database objects previously
granted to other users

GRANT

DTL (Data Transaction Language)


In addition to the previously introduced categories of commands, there are
commands that allow the user to manage database transactions.

COMMIT Saves database transactions


ROLLBACK Undoes database transactions
SAVEPOINT Creates points within groups of transactions in which to
ROLLBACK

BRBRAITT- June-2011

20

Information Technology For JTOs PH-II- IT

(DQL) DATA QUERY LANGUAGE


Introduction
In order to extract data from the database you need to use the Structured Query
Language (SQL) SELECT command. You may need to restrict the rows and
columns that are displayed, as well as specify the order in which the rows are
presented. This lesson explains all of the commands you will use to perform
these actions.
At the end of this lesson, you should be able to
Write a SELECT statement to query the database.
Perform arithmetic calculations using SQL arithmetic operations.
Handle null values.
Specify alternative column headings using aliases.
Concatenate columns.
Sort row output using the ORDER BY clause.
Enter search criteria using the WHERE clause
The Basic Query Block
Four basic clauses

SELECT identifies what columns


FROM identifies which table
WHERE restricts rows to meet a condition
ORDER BY sorts the rows

BRBRAITT- June-2011

21

Information Technology For JTOs PH-II- IT

A SELECT statement retrieves information from the database, implementing all


algebraic operators.
Syntax:SELECT

[DISTINCT] {*, column[alias],..}

FROM Table_name
[WHERE condition(s)]
[ORDERBY {column, expr}[ASC/DESC]]
Where:SELECT

Is a list of at least one column.

DISTINCT

Suppresses duplicates.

Select all columns.

alias

Gives selected columns a different heading.

FROM table

Specifies the table containing the columns.

WHERE

Restricts the query to rows that meet a condition

condition

Is composed of column names, expressions, constants,


and comparison operators.

ORDER BY

Specifies the order in which the retrieved rows are


displayed.

ASC

Orders rows in ascending order.

DESC

Orders the rows in descending order.

BRBRAITT- June-2011

22

Information Technology For JTOs PH-II- IT


Writing SQL Commands
By following these simple rules and guidelines, you will be able to construct valid
statements that are easy both to read and to edit.
SQL commands may be entered on one or many lines.

Clauses are usually placed on separate lines for readability and ease of
editing.
Tabs and indents can be used to make code more readable.

Command words cannot be split across lines or abbreviated.

Keywords and commands typically are entered in uppercase: all other


words, such as table names and columns, are entered in lowercase.

SQL commands are not case sensitive, unless indicted.

An SQL command is entered at the SQL prompt, and subsequent line are
numbered. This is called the SQL buffer.
Only one statement can be current at any time within the buffer, and the statement
can be executed in a number of ways:
Guidelines

Place a semicolon (;) at the end of last clause.


Place a semicolon or slash on the last line in the buffer.

Place a slash at the SQL prompt.

Issue a SQL* plus RUN command at the SQL prompt.

Selecting All Columns, ALL Rows


In its simplest form, a SELECT statement must include the following;
A SELECT clause, which specifies the columns to be displayed.
A FROM clause, which specifies the table containing the columns listed in the
SELECT clause.
Syntax:BRBRAITT- June-2011

23

Information Technology For JTOs PH-II- IT


SELECT

FROM

table_name;

The (*) in the SELECT clause tells the query to return all columns.
Example:SELECT

FROM

emp;

Selecting Specific Columns


If you want explicitly tell the query to display only certain columns, you can specify
the column names in SELECT clause.
Steps to Select Some Columns from a Table:

Identify the column names by using the DESCRIBE command.


List the columns in the SELECT clause.

Separate columns by using a comma

Specify columns in the order you want them to appear.

Column Label Defaults


Label default justification:
Left: date and character data
Right: numeric data

Label default display is uppercase

Example:SELECT
FROM

ename, empno, sal


emp;

Preventing the Selection of Duplicate Rows


Unless you indicate otherwise, SQL displays the result of a query without eliminating
duplicate rows.
The DISTINT keyword
To eliminate duplicate rows in the result, include the DISTINCT keyword in the
SELECT clause immediately after the SELECT command word.

BRBRAITT- June-2011

24

Information Technology For JTOs PH-II- IT


Example:SELECT DISTINCT job FROM emp;
DISTINCT with Multiple Columns
You can specify multiple columns after the DISTINCT qualifier. The DISTINCT
qualifier affects all the selected columns.
Example:SELECT DISTINCT deptno, job

FROM emp;

Querying Data with Conditions


Limiting Selected Rows with the WHERE Clause
You can restrict the rows returned from the query by using the WHERE clause.
A WHERE clause contains a condition that must be met, and directly follows the
FROM clause.
Syntax:SELECT expr FROM

table

[WHERE Condition];

Where: condition

Is composed of column names, expressions,


constants, and comparison operators.

Comparison Operators
Comparison operators are divided in to two categories: logical and SQL. They are
used in the WHERE clause to compare one expression to another using the
following format.
Syntax:WHERE expr operator value
Comparison Operators
Comparison operators test the following conditions:
BRBRAITT- June-2011

25

Information Technology For JTOs PH-II- IT


Operator

Meaning

Equal to

>

Greater than

>=

Greater than or equal


to

<

Less than

<=

Less than or equal to

SQL Operators
There are four SQL operators that operate with all data type:
Operator

Meaning

BETWEEN

Between two values


(inclusive)

IN (list)

Match any of a list of


values

LIKE

Match a character
pattern

IS NULL

Is a null value

The BETWEEN Operator


You can display rows based on a range of value using the BETWEEN operator. The
range you specify contains a lower range and upper range.
The following SQL statement will return persons with Salary between 10000 and
15000.
SELECT * FROM emp
WHERE sal BETWEEN 1000 AND 2500;

BRBRAITT- June-2011

26

Information Technology For JTOs PH-II- IT


The LIKE Operator
You may not always know the exact value to search for. You can select rows that
match a character pattern by using the LIKE operator. The character pattern
matching operation is referred to as a wildcard search. . Two symbols can be used
to construct the searching string.
Symbols
%

Description
Represents any sequence of zero or more
characters.
Represents any single character.

The LIKE condition is used to specify a search for a pattern in a column.


Syntax:SELECT column FROM table
WHERE column LIKE pattern
A "%" sign can be used to define wildcards (missing letters in the pattern) both
before and after the pattern.
The following SQL statement will return persons with names that start with an 'O':
SELECT * FROM emp
WHERE ename LIKE 'O%' ;
The following SQL statement will return persons with first names that end with an 'a':
SELECT * FROM emp
WHERE ename LIKE '%a' ;
The LIKE operator can be used as a shortcut for some BETWEEN comparisons.
SELECT ename FROM emp
WHERE ename LIKE M% ;
IN Operator
IN defines a set in which a given value may or may not be included.
The following SQL statement will return all managers and clerks of emp table

BRBRAITT- June-2011

27

Information Technology For JTOs PH-II- IT


SELECT ename FROM emp
WHERE job IN(MANAGER, CLERK );
IS Null Operator
The IS NULL operator tests for values that are null. A null value means the value is
unavailable, unassigned, known, or inapplicable. Therefore, you cannot test with =
because a null value cannot be equal to any value.
SELECT * FROM emp
WHERE sal IS NULL ;
Querying Data with Multiple Conditions
You may need to specify complex criteria by combining several search condition.
The AND and OR operators may be make compound logical expressions.
The AND operator returns TRUE if both conditions evaluated to TRUE, whereas the
OR operator returns TRUE if either condition is TRUE.
Logical operators
Operator

Meaning

AND

If both component conditions return


TRUE, then the result is TRUE

OR

If either component condition returns


TRUE, then the result is TRUE.

NOT

Returns the opposite condition.

You may find that it is easier to find the rows that do not met a condition, rather than
those that do. Use the comparison and SQL operators with a negative expression.
Negating Logical Operators
<>

Not equal to

Negating SQL Operators

BRBRAITT- June-2011

28

Information Technology For JTOs PH-II- IT

Operator

Description

NOT BETWEEN
AND

Not between two specified values

NOT IN(list)

Not specified list of values

NOT LIKE

Not like comparison string

IS NOT NULL

Is not a null value

Rules of Precedence
You may combine AND and OR operators in the same logical expressions. The
results of all conditions are combined in the order determined by the precedence of
the connecting operators. Where operators of equal precedence are used next to
each other, they are performed from left to right.
Each AND is performed first then each OR is performed. AND has a higher
precedence than OR.
SELECT ename,sal,job

FROM emp

WHERE sal >= 1000


AND job= manager
OR

job= salesman;

Rules of Precedence
Order
Evaluated

Operator
All comparison operators

1
(=, <>, >, >=, <, <=, IN, LIKE, IS NULL,
BETWEEN)
2

AND

OR

BRBRAITT- June-2011

29

Information Technology For JTOs PH-II- IT


Arithmetic Expressions
You may need to modify the way data is displayed, perform calculations, or look at
what-if scenarios. This is possible using arithmetic expressions.
An arithmetic expression may contain column names, constant numeric values, and
the arithmetic operators.
Arithmetic Operators
These are the arithmetic operators available in SQL. You may use arithmetic
operators in any clause of a SQL statement except the FROM clause to create
expressions on NUMBER and DATE data types. Override rules of precedence by
using parentheses.
Operators Description
+
Add
Subtract
*

Multiply

/
()

Divide
Parentheses
to force
operator
precedence

Display the annual salary for all employees.


SELECT ename, sal * 12, comm
FROM emp;
note that the new column (SAL*12) is for display only.
Operator Precedence
If an arithmetic expression contains more than one operator, multiplication and
division are evaluated first. If operators within an expression are of the same priority,
then evaluation is from left to right.

BRBRAITT- June-2011

30

Information Technology For JTOs PH-II- IT


Override the rules of precedence with parentheses to specify the order in which
operators are executed. Parentheses change the order in which a statement is
evaluated.

BRBRAITT- June-2011

31

Information Technology For JTOs PH-II- IT

Column Aliases
A column alias renames a heading.

Especially useful with calculations


Immediately follows column name

Optional AS keyword between column name and alias

Double quotes are required if an alias contains spaces or special


characters.

When displaying the result of a query, SQL*Plus normally uses the selected
columns name as the heading. In many cases, that heading may be difficult to
understand or even meaningless. You can change a columns heading by using a
column alias.
Specify the alias after the column in the SELECT list using a space as a separator.
By default alias headings will be forced to uppercase and cannot contain blank
spaces, unless the alias is enclosed in double quotation marks ( ).
Example:SELECT ename, salary*12 AS annual_salary
FROM emp;

The Concatenation Operator


You can link columns to other columns, arithmetic expressions, or constant values to
create a character expression by using the Concatenation operator (||). Columns on
either side of the operator are combined to make one single output column.
Example:SELECT ename || , || job
FROM emp;

BRBRAITT- June-2011

32

Information Technology For JTOs PH-II- IT

Literal Character String


A literal is any character, expression, or number in the SELECT list that is not a
column name or column alias. It is printed for each row returned. Literal string of
free-format text can be included in the query result and are treated like a column in
the SELECT list.
Character string and dates in the WHERE clause must be enclosed in single
quotation marks ( ). Number constants, however, must not.
Example:SELECT ename ||,|| job
FROM emp
WHERE ename=SCOTT ;

Managing null values

If a row lacks a data value for a particular column, that value is said to be null,
or to contain null.
NULL is a value that is unavailable, unassigned, unknown or inapplicable.

NULL is not the same as zero or space.

Arithmetic expressions containing a null value evaluate to NULL.

Ordering Rows with the ORDER BY Clause


The order of rows returned in a query result is undefined. The ORDER BY clause
may be used to sort the rows. If used, you must place the ORDER BY clause last
you can specify an expression or use position to sort.
syntax

BRBRAITT- June-2011

33

Information Technology For JTOs PH-II- IT


SELECT

expr

FROM

table_name

[ORDER BY {column, expr}[ASC/DESC]]

where:-

ASC

Orders the rows in ascending order.


This is the default order.

DESC

Orders the rows in descending order.

The default sort order is ascending:

Numeric values are displayed with the lowest values first, for example 1999.
Date value are displayed with the earliest value first, for example 01-jan92 before 01-jan-95

Character values are displayed in alphabetical order, for example a first, z


last

In Oracle7, null values are displayed last for ascending sequences and
first and for descending sequences.

Reversing The Default Order


To reverse the order in which rows which rows are displayed, the command word
DESC is specified after the column name in the ORDER BY clause.
Ordering by Position
Another method for sorting query result is to sort by position. This is especially
useful when sorting by a long expression. Rather than typing the expression again,
you can specify its position in the SELECT list.
Example:SELECT ename ,sal*12
FROM emp ORDER BY 2;
BRBRAITT- June-2011

34

Information Technology For JTOs PH-II- IT


Ordering by Multiple Columns
You can sort query result by more than one column.
In the ORDER BY clause, specify the columns, and separate the column names
using commas. If you want to reverse the order of column, specify DESC after its
name or position. You can order by columns that are not in the SELECT list.

SELECT ename, empno, job


FROM emp ORDER BY ename, job DESC;

SQL*Plus COMMANDS
In the previous lesson, you saw how SQL commands are executed within a product
called SQL*Plus. SQL*Plus is a SQL and PL/SQL command execution environment
with additional features.
You can use a number of SQL*Plus commands when writing even the most basic of
SQL statements. This section covers some basic SQL*Plus commands to help you
to

Describe the table structure.


Edit SQL in the buffer.

Save files containing SQL for editing purpose.

Execute saved files.

Load SQL commands from a file into the SQL buffer.

Displaying Table Structure


In SQL*Plus, you can display the structure of a table using the DESCRIBE
command. The result of the command is to see the column names, data types, and
whether a column must contain data.
Syntax:DESC[RIBE] tablename

BRBRAITT- June-2011

35

Information Technology For JTOs PH-II- IT

Where: tablename

Is the name of any existing table, view, or


synonym accessible to the user.

SQL*Plus Editing Commands


When you enter a SQL command, it is stored in a part of memory called the SQL
buffer and remains there until you enter a new command.

Guidelines

If you press [RETURN] before completing a command, SQL*Plus will prompt


you with a line number.
You terminate the SQL buffer by either entering one of the terminator
characters (semicolon or slash), or pressing [RETURN] twice. You will now
see the SQL prompt.

SQL*Pus Editing Commands


Command
A [PPEND] text
C[HANGE]/ old/new/
C [HANGE] / text /
CL[EAR] BUFF [ER]
DEL
I[NPUT]
I[NPUT] text
L[IST]
L[IST] n
L[IST] m n
R[UN]

Description
Add a text to the end of the current line.
Changes old text to new in the current line.
Deletes text from the current line
Deletes all lines from the SQL buffer
Deletes current line
Inserts an indefinite number of lines
Inserts a line consisting of text.
Lists one lines in the SQL buffer
Lists one line (specified by n)
Lists a range of lines (m ton)
Displays and run the current SQL command in the

n
n text
0 text

buffer
Specifies the line to make the current line.
Replaces line n with text.
Inserts a line before line 1.

BRBRAITT- June-2011

36

Information Technology For JTOs PH-II- IT

SQL*Plus File Commands


SQL commands act as the vehicle to the Oracle Server. SQL*Plus commands are
used to control the environment, format query results, and manage files. You can
use the commands identified in the following table.
File Commands
Command

Description

SAVE filename

Save current contents of SQL buffer to a file.

GET filename

Call up contents of previously saved file into the


buffer.

START filename Run a previously saved command file.


@ filename

Run a previously saved command file (same as


START ).

EDIT

Invokes the editor and saves the buffer contents to a


file named a fiedt.buf.

ED[IT] filename

Invokes editor and saves the buffer contents of a


saved file.

EXIT

Leaves SQL*Plus

Logging in to SQL*Plus
How you invoke SQL*Plus depends upon which type of operating system or
windows environment you are running.
Log in Through a Windows Environment
You double-click the SQL*Plus icon in the window manager, then enter the
username, password, and data base, if required.

BRBRAITT- June-2011

37

Information Technology For JTOs PH-II- IT

User name:
Password:
Host String:

Scott
*****

Log in Trough a Command Line Environment


Once you log to your machine, at the operating system prompt, enter the SQL*Plus
command.
Syntax:Sqlplus [user name [/ password [@ database]]]
Where: usrename

Is your database username

password

Is your database password. If you enter your password here,


it is visible.

@ database

Is the database connect string.

Summary
In this lesson, you have learned about retrieving information from a database table
with the SELECT statement and how to implement arithmetic and SQL operators.
You also learned the basic syntax for the SELECT statement.
Syntax:SELECT [DISTINCT] {*, column [alias]}
FROM table
[WHERE condition (s)]
[ORDER BY {column, expr} [ASC/DESC]]
Where:

BRBRAITT- June-2011

38

Information Technology For JTOs PH-II- IT

SELECT

Is a list of at least one column

DISTINCT

Suppresses duplicates.

Select all columns.

alias

Gives selected columns a different


heading

FROM table

Specifies the table containing the


columns.

WHERE

Restricts the query to rows that meet


a condition.

condition

Is composed of column names,


expression, constants, and com

ORDER BY

Specifies

ASC

Orders rows in ascending order.

DESC

Orders the rows in descending order

SQL*PLUS
SQL*Plus
is
an
execution environment
you can use to send
SQL commands to the
database server and to
edit and to save SQL
commands. Commands

may be executed from the SQL prompt or from a script file.

Data Definition Language (DDL)


The Data Definition Language (DDL) part of SQL permits database tables to be
created or deleted. We can also define indexes (keys), specify links between tables,
and impose constraints between database tables.
The most important DDL statements in SQL are

CREATE
ALTER
DROP

- Creating a new database object.


- Altering the definition of an existing data object.
- Dropping an existing data object.

The CREATE TABLE Statement


The CREATE TABLE statement in SQL is used to create a table. Although the very
act of creating a table is quite simple, much time and effort should be put into

BRBRAITT- June-2011

39

Information Technology For JTOs PH-II- IT


planning table structures before the actual execution of the CREATE TABLE
statement.
Some elementary questions need to be answered when creating a table:

What type of data will be entered into the table?

What will be the table's name?

What column(s) will compose the primary key?

What names shall be given to the columns (fields)?

What data type will be assigned to each column?

What will be the allocated length for each column?

Which columns in a table can be left blank?

After these questions are answered, the actual CREATE TABLE statement is simple
The CREATE TABLE Statement has the following general format:
Syntax:CREATE TABLE table-name
(column-descr|constraint, column-descr|constraint...);
Where

table-name is the new name for the table.


column-descr is a column declaration.
constraint is a table constraint.

The column declaration can include optional column constraints. The declaration has
the following general format:
Syntax:column-name data-type [column-constraints]

column-name is the name of the column and must be unique among the
columns of the table.
Data-type declares the type of the column.
column-constraints is an optional list of column constraints with no
separators

BRBRAITT- June-2011

40

Information Technology For JTOs PH-II- IT


In examples, we use the popular data types CHAR (constant-length character),
VARCHAR (variable-length character), NUMBER (numeric values, decimal and
non-decimal), and DATE (date and time values).
Create a table called EMPLOYEE in the following example

Example:CREATE TABLE employee


( ecode integer NOT NULL PRIMARY KEY,
ename
char(20) NOT NULL,
gender
char(1) NOT NULL,
grade
char(2),
gross
number(7) ) ;

Guidelines

Each column has been assigned a specific data type and length.

By using the NULL/NOT NULL constraint, you have specified which


columns require values for every row of data in the table. The
EMP_PHONE is defined as NULL, meaning that NULL values are allowed
in this column because there may be individuals without a telephone
number.

The information concerning each column is separated by a comma, with


parentheses surrounding all columns (a left parenthesis before the first
column and a right parenthesis following the information on the last
column) .

Naming Conventions
When selecting names for objects, specifically tables and columns, the name should
reflect the data that is to be stored. For example, the name for a table pertaining to
employee information could be named EMPLOYEE_TBL. Names for columns
should follow the same logic. When storing an employee's phone number, an
obvious name for that column would be PHONE_NUMBER

BRBRAITT- June-2011

41

Information Technology For JTOs PH-II- IT


Constraints
Constraint specifications add additional restrictions on the contents of the table.
They are automatically enforced by the DBMS.
The column constraints are:
NOT NULL -- specifies that the column can't be set to null. If this constraint is
not specified, the column is nullable, that is, it can be set to null. Normally,
primary key columns are declared as NOT NULL.
PRIMARY KEY -- specifies that this column is the only column in the primary
key. There can be only one primary key declaration in a CREATE TABLE. For
primary keys with multiple columns, use the PRIMARY KEY table constraint.
See Entity Integrity below for a detailed description of primary keys.
UNIQUE -- specifies that this column has a unique value or null for all rows of
the table.
REFERENCES -- specifies that this column is the only column in a foreign
key. For foreign keys with multiple columns, use the FOREIGN KEY table
constraint. See Referential Integrity below for a detailed description of primary
keys.
CHECK -- specifies a user defined constraint on the table. See the table
constraint - CHECK, below.
The table constraints are:
PRIMARY KEY -- specifies the set of columns that comprise the primary key.
There can be only one primary key declaration in a CREATE TABLE
Statement. See Entity Integrity below for a detailed description of primary
keys.
UNIQUE -- specifies that a set of columns have unique values (or nulls) for all
rows in the table. The UNIQUE specifier is followed by a parenthesized list of
column names, separated by commas.
FOREIGN KEY -- specifies the set of columns in a foreign key. See
Referential Integrity below for a detailed description of foreign keys.
CHECK -- specifies a user defined constraint, known as a check condition. The
CHECK specifier is followed by a predicate enclosed in parentheses. For
Intermediate Level SQL92, the CHECK predicate can only reference columns
from the current table row, with no subqueries. Many DBMSs support subqueries
in the check predicate.
Data Type
Data type declarations have the following general format:
Character (String)

BRBRAITT- June-2011

42

Information Technology For JTOs PH-II- IT


CHAR [(length)]
CHARACTER [(length)]
VARCHAR (length)
CHARACTER VARYING (length)
length specifies the number of characters for fixed size strings (CHAR,
CHARACTER) spaces are supplied for shorter strings. If length is
missing for fixed size strings, the default length is 1.
For variable size strings (VARCHAR, CHARACTER VARYING), length
is the maximum size of the string. Strings exceeding length are
truncated on the right.
Numeric
SMALLINT
INT
INTEGER
The integer types have default binary precision -- 15 for SMALLINT
and 31 for INT, INTEGER.
NUMERIC ( precision [, scale] )
DECIMAL ( precision [, scale] )
Fixed point types have a decimal precision (total number of digits) and
scale (which cannot exceed the precision). The default scale is 0.
NUMERIC scales must be represented exactly. DECIMAL values can
be stored internally with a larger scale (implementation defined).
FLOAT [(precision)]
REAL
DOUBLE
The floating point types have a binary precision (maximum significant
binary digits). Precision values are implementation dependent for
REAL and DOUBLE, although the standard states that the default
precision for DOUBLE must be larger than for REAL. FLOAT also uses
an implementation defined default for precision (commonly this is the
same as for REAL), but the binary precision for FLOAT can be explicit.
Date time
DATE
TIME [(scale)] [WITH TIME ZONE]
TIMESTAMP [(scale)] [WITH TIME ZONE]

BRBRAITT- June-2011

43

Information Technology For JTOs PH-II- IT

zone component (adjustment in hours, minutes)


Timestamp -- combination calendar date and clock time with year,
month, day, hour, minute, second and fraction of second, plus a
timezone component (adjustment in hours, minutes)
Interval -- intervals represent time and date intervals. They are signed.
An interval value can contain a subset of the interval fields, for
example - hour to minute, year, day to second. Interval types are
subdivided into:
year-month intervals -- may contain years, months or
combination years/months value.
day-time intervals -- days, hours, minutes, seconds, fractions of
second.

The most frequently used ones are tabulated below :

VARCHAR2(Size)
CHAR(Size)
NUMBER(p,s)
DATE
LONG
RAW(Size)

LONG RAW
BLOB

min is 1 & max is 4000


min 1 byte & max 2000 bytes
p 1 to 38 s 84 to 127
Jan 1, 4712 BC to Dec 31,4712 AD
Character data up to 2 GB
binary data max 2000 bytes
(graphics,sound etc)
binary data up to 2GB
binary large object up to 4 GB
(text,graphics,video clips,sound etc)

Creating a Table from an Existing Table


A copy of an existing table can be created using a combination of the CREATE
TABLE statement and the SELECT statement. The new table has the same column
definitions. All columns or specific columns can be selected. New columns that are
created via functions or a combination of columns automatically assume the size
necessary to hold the data.
The basic syntax for creating a table from another table is as follows:
Syntax:CREATE TABLE new_table_name AS

BRBRAITT- June-2011

44

Information Technology For JTOs PH-II- IT


SELECT [ *|column1, column2 ]
FROM table_name
WHERE CONDITIONS
The following example creates a table having all the employees of deptno 20
Example:CREATE TABLE emp_temp AS
SELECT * FROM emp ;
This will create a new table emp_temp that is a copy of the emp table
The CREATE TABLE table_name AS SELECT is useful for creating test tables,
new tables as copies of existing tables, and for making smaller tables out of large
tables.The ALTER TABLE Command
A table can be modified through the use of the ALTER TABLE command after that
table's creation. You can add column(s), drop column(s), change column definitions,
add and drop constraints etc.

Syntax:ALTER TABLE table_name


ADD column_name datatype

Syntax:ALTER TABLE table_name


DROP COLUMN column_name
Note: Some database systems don't allow the dropping of a column in a database
table (DROP COLUMN column_name).
To add a column named "City" in the " EMPLOYEE " table:
Example

BRBRAITT- June-2011

45

Information Technology For JTOs PH-II- IT


ALTER TABLE employee ADD City varchar(30)
To drop the "city " column in the " EMPLOYEE " table:
Example :ALTER TABLE Employee
DROP COLUMN city ;

DROPPING TABLES
Dropping a table is actually one of the easiest things to do. When the RESTRICT
option is used and the table is referenced by a view or constraint, the DROP
statement returns an error. When the CASCADE option is used, the drop succeeds
and all referencing views and constraints are dropped. The syntax to drop a table
follows
Syntax:DROP TABLE TABLE_NAME [ RESTRICT|CASCADE ]
Eg:DROP TABLE emp_temp;

Summary
You have specifically learned about the table. The table is the simplest form of data
storage in a relational database. Tables contain groups of logical information, such
as employee, department, or salary information. A table is composed of various
columns, with each column having attributes; those attributes mainly consist of data
types and constraints, such as NOT NULL values, primary keys, foreign keys, and
unique values.
You learned the CREATE TABLE command and options, that may be available with
this command. You have also learned how to modify the structure of existing tables
using the ALTER TABLE command.

BRBRAITT- June-2011

46

Information Technology For JTOs PH-II- IT

Data Manipulation Language(DML)


Data Manipulation LanguageDML. is the part of SQL that is used to make changes to
data and tables in a relational database.
At the end of this lesson, you should be able to get

An overview of data manipulation language


Instruction on how to manipulate data in tables

Concepts behind table population of data

How to delete data from tables

How to change or modify data in tables

Overview of Data Manipulation


Data Manipulation Language (DML) is the part of SQL that allows a database user to
actually propagate changes among data in a relational database. With DML, the
user can populate tables with new data, update existing data in tables, and delete
data from tables. Simple database queries can also be performed within a DML
command.
There are three basic DML commands in SQL:

INSERT - Inserting new rows into database tables.


UPDATE - Updating existing rows in database tables .
DELETE - Deleting existing rows from database tables.

Inserting Data into a Table


Use the INSERT statement to insert new data into a table.
The simplest form of the INSERT statement is as follows;-;

Syntax:-

BRBRAITT- June-2011

47

Information Technology For JTOs PH-II- IT


INSERT INTO table_name
VALUES ('value1', 'value2', value3);
Guidelines

You must include every column in the specified table in the VALUES list.

Each value in this list is separated by a comma.

The values inserted into the table must be enclosed by quotation marks
for character and date/time data types. Quotation marks are not required
for numeric data types or NULL values using the NULL keyword.

A value should be present for each column in the table.

Insert a new record into the DEPT table.


Example
INSERT INTO Dept
VALUES (60,Marketing',Delhi);
In this example three values were inserted into the dept table with three columns.
The inserted values are in the same order as the columns listed in the table. The first
value's associated column,deptno, is a numeric data type and does not require
quotation marks, although they can be used. The remaining two values are inserted
using quotation marks because the data types of the corresponding columns are of
character type.
Note
Although single quotation marks are not required around numeric data that is
being inserted, they may be used with any data type. Said another way, single
quotation marks are optional when referring to numeric data values in the
database, but required for all other data values (data types). Although usually a
matter of preference, most SQL users choose not to use quotation marks with
numeric values.

Inserting Data into Limited Columns of a Table


BRBRAITT- June-2011

48

Information Technology For JTOs PH-II- IT


There is a way you can insert data into specified columns.
You must, in this case, specify a column list as well as a VALUES list in your
INSERT statement.

Syntax:INSERT INTO table_name (Column1,Column2)


VALUES ('value1', 'value2' );
For instance, suppose you want to insert only empno, ename, and job columns you
use the command
Example(1)
INSERT INTO emp (empno, ename, job)
VALUES (5063,Maya,Manager);
Output:-1 row created
You use table employee and insert values into only specified columns in the
following example
Table structure
ecode integer NOT NULL PRIMARY KEY,
ename
char(20) NOT NULL,
gender
char(1) NOT NULL,
grade
char(2),
gross
number(7)
Example(2)
INSERT INTO employee (ecode,ename,gender,gross)
VALUES(1001,Ravi,M, 9000);
Output:-1 row created
You have specified a column list enclosed by parentheses after the table name in the
INSERT statement. You have listed all columns into which you want to insert data.

BRBRAITT- June-2011

49

Information Technology For JTOs PH-II- IT


Grade is the only excluded column. You can see, if you look at the table definition,
that grade column does not require data for every record in the table. You know that
Grade does not require data because NOT NULL is not specified in the table
definition. NOT NULL tells us that NULL values are not allowed in the column.
Furthermore, the list of values must appear in the same order as the column list.
Note
In an INSERT statement only those columns can be omitted that have either
default value defined or they allow NULL values
Inserting NULL Values
Inserting a NULL value into a column of a table is a simple matter. You might want to
insert a NULL value into a column if the value of the column in question is unknown.
A NULL value can be inserted into a column of a table using the keyword NULL.
Syntax:INSERT INTO table_name
VALUES ('value1', NULL, value3);
The NULL keyword should be used in the proper sequence of the associated column
that exists in the table. That column will not have data in it for that row if you enter
NULL. In the syntax, a NULL value is being entered in the place of COLUMN2.
Example:INSERT INTO emp
(EMPNO,ename,job,hiredate, comm,deptno)
VALUES (8100,Aravind,clerk, 10-jun-06,6000,'',20);

Output:-1 row created

But instead of inserting the value NULL into the Comm column, we have inserted ''.
NULL value has been inserted by using two single quotation marks together, which
also symbolizes a NULL value (because there is nothing between them).

BRBRAITT- June-2011

50

Information Technology For JTOs PH-II- IT

Insertion using substitution operator &


Data can be inserted interactively also. Here data is inserted through parameter
substitution. Notice that parameters for character values are enclosed in single
quotation marks.
Example(1)
INSERT INTO result
VALUES(&rollno,&name,&marks,&grade);
Now oracle shall first ask you to provide values for these parameters by prompting
these messages.
Enter value for rollno : 1001
Enter value for name : Meera
Enter value for marks : 95
Enter value for grade : A+
And after accepting these values, Oracle displays two messages like
Output:-1 row created
Old n: VALUES(&rollno,&name,&marks,&grade)
New n: Values (1001,Meera,95, A+)
Similarly try the following example
Example(2)
INSERT INTO emp
(&EMPNO,&ename,&job,&hiredate,&sal,&comm.,&deptno);
Enter value for empno: 8100
Enter value for ename: Aravind
Enter value for job: clerk
Enter value for hiredate:10-may-03
Enter value for comm: NULL
Enter value for deptno:20

BRBRAITT- June-2011

51

Information Technology For JTOs PH-II- IT

Note:The column list in the INSERT statement does not have to reflect the same order
of columns as in the definition of the associated table, but the list of values must
be in the order of the associated columns in the column list.
Inserting Data from Another Table
You can insert data into a table based on the results of a query from another table
using a combination of the INSERT statement and the SELECT statement. In the
case of combining the INSERT statement with the SELECT statement, you are able
to insert the data retrieved from a query into a table.
The syntax for inserting data from another table is
Syntax:INSERT INTO table_name [('column1', 'column2')]
SELECT ('column1', 'column2')]
FROM table_name
[WHERE condition(s)];
The following example uses a simple query to view all data in the EMP table.
SELECT * tells the database server that you want information on all columns of the
table. Because there is no WHERE clause, you will see all records in the table as
well.
Example:INSERT INTO Emp_TMP
SELECT * from EMP;

The following Conditions must be satisfied:

Both tables must be already created

BRBRAITT- June-2011

52

Information Technology For JTOs PH-II- IT

Columns of both tables must match

Inserting special values by using SQL Functions


You can use pseudo columns to enter special values in your table.
Specify USERID to enter the current user name. SYSDATE enter the current date
and time.
When inserting a date value, the format DD-MON-YY is usually used. With this
format, recall that the century defaults to the current century. Because the date also
contains time information, the default time is midnight(00:00:00)
Inserting Specific Date and Time Values
If a date is required to be entered in another century and a specific time is also
required, use the TO_DATE function.
Example:If we have a table student with following schema:
Student(Rollno,name,marks,exam_Date)
Record information for the student registration in the student table. Supply the
current user name for the name column and the current date and time in the
Exam_DATE column. Set the START_DATE to be january1, 1996, 8:00 A.M.
Example:INSERT INTO student (Rollno,name,marks,exam_Date,start_date)
Values(26, USER, 60, SYSDATE, TO_DATE (01-JAN-96 08:00, DD-MONYY HH:MI));
Output:-1 row created
Updating Existing Data
Pre-existing data in a table can be modified using the UPDATE command. The
UPDATE command does not add new records to a table, nor does it remove records
UPDATE simply updates existing data.

BRBRAITT- June-2011

53

Information Technology For JTOs PH-II- IT

Updating the Value of a Single Column


The most simple form of the UPDATE statement is its use to update a single column
in a table. Either a single row of data or numerous records can be updated when
updating a single column in a table.
Syntax:UPDATE table_name
SET column_name = 'value'
[WHERE condition];
Example:- to double grosspay of all grade E3 and E4 employees you can use the
following expression
Example:UPDATE employee
SET gross = gross*2
WHERE (grade = E3 OR grade = E4);
Output:-3 rows updated
The following example updates the Deptno column in the EMP table which you have
specified using the WHERE clause.
Transfer employee number 1002 to department 10
Example:UPDATE EMP
SET deptno = 10
WHERE empno=1002;

BRBRAITT- June-2011

54

Information Technology For JTOs PH-II- IT


Output:-1 row updated
The following example is identical to the previous example, except for the absence
of the WHERE clause:
Example:UPDATE EMP
SET Comm = 1;
Output:-14 rows updated
Notice that in this example, an UPDATE statement without a WHERE clause is used
to update the COMM column in the EMP table for all rows of data.
Note
Extreme caution must be used when using the UPDATE statement without a
WHERE clause. The target column is updated for all rows of data in the table if
conditions are not designated using the WHERE clause. In most situations, the
use of the WHERE clause with a DML command is appropriate.
Updating Multiple Columns in One or More Records
Next, you see how to update multiple columns with a single UPDATE statement.
Syntax:UPDATE table_name
SET column 1= 'value' ,

column2 = 'value', column3 = 'value'

[WHERE condition];
Note
The SET keyword is used only once for each UPDATE statement. If more than
one column is to be updated, a comma is used to separate the columns to be
updated.
If a sub query is used in a UPDATE statement, it must return exactly one row for
each row in the update table that matches the WHERE clause. If it returns multiple
rows, Oracle server will give you an error message.

BRBRAITT- June-2011

55

Information Technology For JTOs PH-II- IT


Example:-UPDATE employee
SET grade=NULL, gross=20000
WHERE sex=F
Output:-4 rows updated
Here both grade and gross fields of all lady employees are updated simultaneously.
Deleting Data from Tables
The DELETE command is used to remove entire rows of data from a table. The
DELETE command is not used to remove values from specific columns; a full
record, including all columns, is removed.
Syntax;DELETE FROM table_name
[where condition];
Example:DELETE FROM EMP
WHERE empno= 1002;
Output:-1 row deleted
Notice the use of the WHERE clause. The WHERE clause is an essential part of the
DELETE statement if you are attempting to remove selected rows of data from a
table.
Note
The temporary tables created as copies of the original table can be very useful for
testing the DELETE and UPDATE commands before issuing them against the
original table.
CREATE TABLE emp_temp AS
SELECT * FROM emp ;
CREATE TABLE emp1_temp AS
SELECT * FROM emp ;
Example:-To delete all the employees of sales department
DELETE FROM emp_temp

BRBRAITT- June-2011

56

Information Technology For JTOs PH-II- IT


WHERE deptno IN(SELECT deptno FROM
dept where dname=SALES) ;
Output:-5 rows deleted
Delete All Rows from a Table
If you want to delete all rows from a table, you have two options:

Use the DELETE statement with no WHERE clause. (the table structure,
attributes, and indexes will also be deleted)
DELETE FROM EMP1_temp;

Use the TRUNCATE TABLE statement. (deletes only the data inside the
table)
TRUNCATE TABLE EMP_temp;

Note
i) If the WHERE clause is omitted from the DELETE statement, all rows of
data are deleted from the table. As a general rule, always use a WHERE
clause with the DELETE statement.
ii) Also, remember that the DELETE command may have a permanent
impact on the database. Ideally, it should be possible to recover
erroneously deleted data via a backup, but in some cases, it may be
difficult or even impossible to recover data. If data cannot be recovered, it
must be re-entered into the database.
Summary
You have learned the three basic commands in Data Manipulation Language (DML):
the INSERT, UPDATE, and DELETE statements. As you have seen, data
manipulation is a very powerful part of SQL, allowing the database user to populate
tables with new data, update existing data, and delete data.
A very important lesson when updating or deleting data from tables in a database is
sometimes learned when neglecting the use of the WHERE clause. Remember that
the WHERE clause places conditions on a SQL statementparticularly in the case
of UDPATE and DELETE operations, when specifying specific rows of data that will
be affected during a transaction. All target table data rows are affected if the WHERE
clause is not used, which could be disastrous to the database. Protect your data and
be cautious during data manipulation operations.

BRBRAITT- June-2011

57

Information Technology For JTOs PH-II- IT

Data Control Language


The third SQL component is Data Control Language (DCL).
Included in DCL are important statements such as GRANT and REVOKE. These
statements control which privileges a user has with the database, such as selecting
rows, updating tables, deleting data, altering table structures, and so on.
Some statements, such as CREATE, GRANT, and REVOKE, may require
administrative privilege to issue.
Privileges
Privileges are the right to execute particular SQL statements.
The database administrator is a high level user with the ability to grant users access
to the database and its objects.
The users require system privileges to gain access to the database and object
privileges to manipulate the content of the objects in the database.
Users can also be given the privilege to grant additional privileges to other users or
to roles which are named groups of related privileges.
Users with different roles perform different tasks and should be given different
privileges.
GRANT Statement
The GRANT Statement grants access privileges for database objects to other users.
It has the following general format:

Syntax:
GRANT privilege-list
ON [table_name] object-list
TO user-list
[With GRANT option]

BRBRAITT- June-2011

58

Information Technology For JTOs PH-II- IT


where:
privilege-list is either ALL PRIVILEGES or a comma-separated list of

properties: SELECT, INSERT, UPDATE, DELETE.

object-list is a comma-separated list of table and view names.

user-list is either PUBLIC (all users) or a comma-separated list of user


names.
With GRANT option allows the grantee to grant the object privileges to

other users and roles.


Guidelines

The GRANT statement grants each privilege in privilegelist for each object (table) in object-list to each user in user-list.
In general, the access privileges apply to all columns in
the table or view, but it is possible to specify a column list with the
UPDATE privilege specifier:

UPDATE [ ( column-1 [, column-2] ... ) ]

If the optional column list is specified, UPDATE privileges


are granted for those columns only.

The user-list may specify PUBLIC. This is a general


grant, applying to all users (and future users) in the catalog.
Privileges granted are revoked with the REVOKE

Statement.

The optional specificier WITH GRANT OPTION may


follow user-list in the GRANT statement. WITH GRANT OPTION
specifies that, in addition to access privileges, the privilege to grant
those privileges to other users is granted.

The Owner has all privileges on the object and can grant
specific privileges on that object.

BRBRAITT- June-2011

The object privileges vary from object to object

59

Information Technology For JTOs PH-II- IT


Example
A new database administrator has been hired to manage the emp table, and needs
to be granted the privileges of SELECT, INSERT, UPDATE, and DELETE.

GRANT SELECT, INSERT, UPDATE, DELETE


ON emp TO user02;

The GRANT statement grants the user named user02 the privileges to select, insert,
update, and delete for the emp table.
.
The REVOKE Statement
Exercise
It has been decided that once records are entered into the emp table, they should
not be changed or deleted by the new database user. Revoke the UPDATE and
DELETE privileges from user02.
Example query
REVOKE update, delete ON emp FROM
user02;

Syntax of the REVOKE statement


REVOKE privilege_list ON table_name FROM
user_name;

privilege_listA list of privileges to be revoked from the user.


Possible values include SELECT, INSERT, UPDATE,
BRBRAITT- June-2011

60

Information Technology For JTOs PH-II- IT


DELETE, and ALL PRIVILEGES.
About the query
The REVOKE statement is used to revoke privileges from users of the database.
The query revokes the UPDATE and DELETE privileges from the user named
user02 for the emp table.

BRBRAITT- June-2011

61

Information Technology For JTOs PH-II- IT

Data Transaction Language (Transaction Control Language)


Objectives
In this session, you learn the concepts behind the management of database
transactions such as

The definition of a transaction


The commands used to control transactions

The syntax and examples of transaction commands

When to use transaction commands

The consequences of poor transaction control

A transaction is a unit of work that is performed against a database. Transactions are


units or sequences of work accomplished in a logical order, whether in a manual
fashion by a user or automatically by some sort of a database program. In a
relational database using SQL, transactions are accomplished using the DML
commands , INSERT, UPDATE, and DELETE.
A transaction is the propagation of one or more changes to the database. For
instance, you are performing a transaction if you performed an UPDATE statement
on a table to change an individual's name.
A transaction can either be one DML statement or a group of statements. When
managing transactions, each designated transaction (group of DML statements)
must be successful as one entity or none of them will be successful.
The following list describes the nature of transactions:

All transactions have a beginning and an end.


A transaction can be saved or undone.

If a transaction fails in the middle, no part of the transaction


can be saved to the database.

BRBRAITT- June-2011

62

Information Technology For JTOs PH-II- IT

What Is Transaction Control?


Transaction control is the ability to manage various transactions that may occur
within a relational database management system.
When a transaction is executed and completes successfully, the target table is
not immediately changed, although it may appear so according to the output.
When a transaction successfully completes, there are transaction control
commands that are used to finalize the transaction, either saving the changes
made by the transaction to the database or reversing the changes made by the
transaction.
There are three commands used to control transactions:

COMMIT
ROLLBACK
SAVEPOINT

Each of these is discussed in detail in the following sections.


Note
Transaction control commands are only used with the DML commands
INSERT, UPDATE, and DELETE. For example, you do not issue a COMMIT
statement after creating a table. When the table is created, it is automatically
committed to the database. Likewise, you cannot issue a ROLLBACK to
replenish a table that was just dropped.
When a transaction has completed, the transaction information is stored either in
an allocated area or in a temporary rollback area in the database. All changes
are held in this temporary rollback area until a transaction control command is
issued. When a transaction control command is issued, changes are either made
to the database or discarded; then, the temporary rollback area is emptied.

The COMMIT Command


The COMMIT command is the transaction command used to save changes
invoked by a transaction to the database. The COMMIT command saves all
transactions to the database since the last COMMIT or ROLLBACK command.

BRBRAITT- June-2011

63

Information Technology For JTOs PH-II- IT


The syntax for this command is
COMMIT;
In the following example, you begin by selecting all data from the EMP_temp
table:
SELECT * FROM EMP_TMP;
Next, you delete all records from the table where the job=clerk.
DELETE FROM EMP_TMP
WHERE job=clerk;
A COMMIT statement is issued to save the changes to the database, completing
the transaction.
COMMIT;
Note :

Frequent COMMITs in large loads or unloads of the database are


highly recommended; however, too many COMMITs cause the job
running to take a lot of extra time to complete. Remember that all
changes are sent to the temporary rollback area first. If this temporary
rollback area runs out of space and cannot store information about
changes made to the database, the database will probably halt,
disallowing further transaction activity.

In some implementations, transactions are committed without issuing


the COMMIT commandinstead, merely signing out of the database
causes a commit to occur.

The ROLLBACK Command


The ROLLBACK command is the transaction control command used to undo
transactions that have not already been saved to the database. The ROLLBACK
command can only be used to undo transactions since the last COMMIT or
ROLLBACK command was issued.
Syntax:ROLLBACK;

BRBRAITT- June-2011

64

Information Technology For JTOs PH-II- IT


In the following example, you begin by selecting all records from the EMP_TEMP
table since the previous deletion of records:
SELECT * FROM EMP_TMP;
Next, you update the table, changing the sal to 10000 for
the empno 7499:
UPDATE EMP_TMP
SET sal = 10000
WHERE empno = '7499';
If you perform a quick query on the table, the change appears to have occurred:
SELECT * FROM EMP_TMP;
Now, issue the ROLLBACK statement to undo the last change:
ROLLBACK;
Finally, verify that the change was not committed to the database:
SELECT * FROM EMP_TMP;

The SAVEPOINT Command


A SAVEPOINT is a point in a transaction when you can roll the transaction back
to a certain point without rolling back the entire transaction.
Syntax:SAVEPOINT Savepoint_Name
This command serves only in the creation of a SAVEPOINT among transaction
statements. The ROLLBACK command is used to undo a group of transactions.
The SAVEPOINT is a way of managing transactions by breaking large numbers
of transactions into smaller, more manageable groups.
Note :
The SAVEPOINT name must be unique to the associated group of
transactions.

BRBRAITT- June-2011

65

Information Technology For JTOs PH-II- IT


The ROLLBACK TO SAVEPOINT Command
Syntax:ROLLBACK TO Savepoint_Name;

In this example, you plan to delete the remaining records from the EMP_TEMP
table. You want to create a SAVEPOINT before each delete, so that you can
ROLLBACK to any SAVEPOINT at any time to return the appropriate data to its
original state:
SAVEPOINT SP1;
DELETE FROM EMP_TEMP WHERE Empno= 7521;
SAVEPOINT SP2;
DELETE FROM EMP_TEMP WHERE Empno= 7788;
SAVEPOINT SP3;
DELETE FROM EMP_TEMP WHERE Empno= 7698;
Now that the three deletions have taken place, say you have changed your mind
and decided to ROLLBACK to the SAVEPOINT that you identified as SP2.
Because SP2 was created after the first deletion, the last two deletions are
undone:
ROLLBACK TO SP2;
Notice that only the first deletion took place since you rolled back to SP2:
SELECT * FROM EMP_TMP;
Remember, the ROLLBACK command by itself will roll back to the last COMMIT
or ROLLBACK. You have not yet issued a COMMIT, so all deletions are undone,
as in the following example:
ROLLBACK ;
SELECT * FROM EMP_TMP;

Transaction Control and Database Performance


Poor transaction control can hurt database performance and even bring the
database to a halt. Repeated poor database performance may be due to a lack
BRBRAITT- June-2011

66

Information Technology For JTOs PH-II- IT


of transaction control during large inserts, updates, or deletes. Not only are large
batch processes, such as these demanding on the CPU and memory
themselves, but temporary storage for rollback information continues to grow
until either a COMMIT or ROLLBACK command is issued.
When a COMMIT is issued, rollback transaction information is written to the
target table and the rollback information in temporary storage is cleared. When a
ROLLBACK is issued, no changes are made to the database and the rollback
information in the temporary storage is cleared. If neither a COMMIT nor
ROLLBACK is issued, the temporary storage for rollback information continues to
grow until there is no more space left, thus forcing the database to stop all
processes until space is freed. Although space usage is ultimately controlled by
the DBA, a lack of transaction control can still cause database processing to
stop, sometimes forcing the DBA to take action that may consist of killing running
user processes.

Summary
Here You learned the preliminary concepts of transaction management through
the use of three transaction control commands: COMMIT, ROLLBACK, and
SAVEPOINT. COMMIT is used to save a transaction to the database.
ROLLBACK is used to undo a transaction that was performed. SAVEPOINT is
used to break a transaction or transactions into groups, allowing you to roll back
to specific logical points in transaction processing.
Remember that you should frequently use the COMMIT and ROLLBACK
commands when running large transaction jobs to keep space free in the
database. Also keep in mind that these transaction commands are used only with
the three DML commands (INSERT, UPDATE, and DELETE).

BRBRAITT- June-2011

67

Information Technology For JTOs PH-II- IT

Chapter 3
Oracle built in functions and Group functions
Overview
Data can be manipulated in queries through functions supported by SQL.
A function is a special type of predefined command set that performs some
operation and returns a single value.
SQL has a lot of built-in functions for counting and calculations.
Syntax
SELECT function (column) FROM table

Types of Functions
There are several basic types and categories of functions in SQL. The basic
types of functions are:

Scalar functions
Aggregate Functions(Group functions)

Scalar functions
Scalar functions operate against a single value, and return a single value based
on the input value.
They can be used in the SELECT clause of queries to

Manipulate data items


Accept arguments and return one value

Act on each row returned

Return one result per row

Modify the data type

BRBRAITT- June-2011

68

Information Technology For JTOs PH-II- IT


They are categorized according to the types of Data they operate upon:Character Functions
These functions are applied to strings of text

LOWER()

Convert to lowercase

UPPER()

Convert to uppercase

INITCAP ()

Convert to initial capitalization

CONCAT()

Concatenate values

SUBSTR()

Return substring

LENGTH

Return number of characters

CONCAT function
Combines two string values into one
"||" is used for this operation.
Syntax:-

CONCAT (char1 ,char2)

Example:-

SELECT CONCAT (CONCAT(ename, is a,)job) job


FROM emp
WHERE empno=7900;

Result:-

job
JONES is a CLERK

BRBRAITT- June-2011

69

Information Technology For JTOs PH-II- IT

INITCAP Function
Convert to initial capitalization
Syntax:-

INITCAP (expression)

Example:-

SELECT INITCAP(ename) from emp;


Returns ename in initial caps letters

LEFT and RIGHT Function

Returns a specified number of characters from the left and right of a character
expression respectively
Syntax:-

RIGHT(character_expression ,
integer_expression )
LEFT (character_expression ,
integer_expression)

Example:Here is, for example, the way to determine the names of the
employees that start and end with the same letter:
SELECT ename FROM emp WHERE
LEFT(ename, 1) = RIGHT(ename, 1)

LOWER and UPPER functions


Convert to lowercase and uppercase respectively
Syntax:-

LOWER(character_expression)

BRBRAITT- June-2011

70

Information Technology For JTOs PH-II- IT


UPPER(character_expression )
Example:-

SELECT LOWER(ename) from emp;


Returns ename in lowercase letters
SELECT UPPER(ename) from emp;
Returns ename in uppercase letters

LTRIM and RTRIM functions

Cut accordingly the leading and trailing blanks of the string expression, which is
being converted by default to the VARCHAR type.
Syntax:-

LTRIM (character_expression )
RTRIM (character_expression )

Example:-

Select LTRIM(PS ANIL,PS)

LPAD and RPAD functions


Left-pads(inserts the left side) or right-pads the given characters to given string
to reach at given width.
Syntax:- LPAD(char1,n,char2)
RPAD(char1,n,char2)

SELECT LPAD(ABCD,7,*) from dual;


Pads the string on the left with the * or whatever character is indicated , to make
it (here) 7 characters long

BRBRAITT- June-2011

71

Information Technology For JTOs PH-II- IT


SELECT RPAD(ABCD,7,*) from dual;
Pads the string on the right with the * or whatever character is indicated , to
make it (here) 7 characters long

SUBSTRING function
Extract from an expression its part of a specified length, starting from a specified
initial position.
Syntax:-

SUBSTRING (expression , start , length )

Example:-

For, if we need to get 3 characters in a ship name, starting from


the 2nd character, then it's quite easy to do it with the SUBSTRING
function.
SELECT name, SUBSTRING(name, 2, 3) FROM emp;
SELECT SUBSTR(abcdefgh,1,3) from dual;
Return substring by extracting 3 letters from the beginning at
position 1

LENGTH function
Return number of characters in the string
Syntax:-

LENGTH(expression)

Example:-

SELECT LENGTH(12345678) from dual;

Result:-

NVL function
In order to convert a null value to an actual value, use the NVL function.
Syntax:-

BRBRAITT- June-2011

72

Information Technology For JTOs PH-II- IT


NVL (expr1,expr2)
Where expr 1

Is the source value or expression that may contain


null.

expr 2
Is the target value for converting null.

Data types to use are date,character&number


Data types must match.
NVL(start_date, 01-JAN-95)
NVL(title, Unavailable)
NVL (salary, 1000)

Example:-

NVL(job,SDE)

Will substitute the value SDE for any NULL Value found in the job column
Notes: you can use the NVL function to convert any data type, but the return
value is always the same as the data type of expr 1.
Number Functions

ROUND

Rounds values to specified decimal

TRUNC

Truncates values to specified decimal

MOD

Returns remainder of division

ROUND and TRUNC Functions


ROUND(45.923,2)

45.92

ROUND(45.923,0)

46

ROUND(45.923,-1)

50

TRUNC(45.923,2)

45.92

TRUNC(45.923)

45

BRBRAITT- June-2011

73

Information Technology For JTOs PH-II- IT


TRUNC(45.923,-1)

40

Date Functions

Date functions operate on values of the Date datatypes


Oracle Date Format
Oracle stores dates in an internal numeric format
Century, year, month, day, hours, minutes, seconds
Default date display is DD-MON-YY
SYSDATE is a function returning date and time
DUAL is a dummy table used to view SYSDATE
SELECT SYSDATE

FROM

DUAL;

MONTHS_BETWEEN

Number of months between two dates

ADD_MONTHS

Add calendar months to date

NEXT_DAY

Next day of the date

LAST_DAY

Last day of the month

ROUND

Round to date at midnight

TRUNC

Removes time portion from date

ADD_MONTHS
This function adds number of months to a given date and returns a date after
those many months.
Syntax:ADD_months(date1,n)
It returns the value of argument date date1 plus n months
Example:-

BRBRAITT- June-2011

74

Information Technology For JTOs PH-II- IT


Find out when will SMITH complete one month in the company.
SELECT hiredate, ADD_months(hiredate,1)Next month
From emp
Where ename=SMITH;
Output

hiredate

Next month

17-dec-80

17-jan-81

MONTHS_BETWEEN
This function finds out the number of months passed between given two dates
Syntax:Months_between(date1,date2)
Date2>date1
Example:SELECT Months_between(22-Jan-03,02-Dec_2002) MONTHS
FROM DUAL;
Output:-

months
1.6451613

NEXT_DAY
Returns the date of a specified coming day the first weekday named by argument
CHAR that is later than the date d in the Next week
Syntax:NEXT_DAY(d,CHAR)
Example:-To get the date of next Tuesday after NOV 16,2006
SELECT NEXT_DAY(16-NOV-06,Tuesday) Next day
FROM DUAL

BRBRAITT- June-2011

75

Information Technology For JTOs PH-II- IT


Output:-

Next day
21-Nov-06

LAST_DAY
Returns the Last day of the specified month
Syntax:LAST_DAY(Date)
Example:SELECT LAST_DAY(16-NOV-06) Last day
FROM DUAL
Output:-

Last day
30-Nov-06

BRBRAITT- June-2011

76

Information Technology For JTOs PH-II- IT

TO_CHAR, date conversion


This function converts a date into equivalent character string.
Syntax:
TO_CHAR(n,(fmt))
SELECT TO_CHAR(HIREDATE, Mon, DD, YY) Date Format
FROM EMP
WHERE empo= 7369
Output
Date Format
Dec 17,80
SELECT TO_CHAR(HIREDATE, DY-Mon. DD, YY) Date Format
FROM emp
WHEREempno=7369;
Output
Date format
WED-Dec. 17,80
SELECT TO_CHAR(HIREDATE, Day Mon. DDTH, YY ;hh:mi:ss am)
Date Format
FROM emp WHERE empno=7369;
Output
Date format
Wednesday Dec. 17th, 80; 12:00:00 am

BRBRAITT-JUN-2011

77

Information Technology For JTOs PH-II- IT

Aggregate functions (Group functions)


SUM, AVG, MAX, MIN, and COUNT.
Aggregate functions operate against a collection of values, but return a single
value.
Note: If used among many other expressions in the item list of a SELECT
statement, the SELECT must have a GROUP BY clause.
AVG ( )
This function computes the average of the given column
SYNTAX
Argument type
Return Value
Description
Example
SQL>
Output

AVG(DISTINCT/ ALL) N
Numeric
Numeric
Returns Average value of parameters n
Calculate average salary of all employees listed in table
emp
SELECT AVG(sal)
FROM emp;
2077.21429

SUM()
This function gives the sum of all the rows, satisfying any conditions, of the given
column or expression.
SYNTAX
Argument type
Return Value
Description
Example
SQL>
Output

BRBRAITT-JUN-2011

SUM([DISTINCT | ALL] n)
Numeric
Numeric
Returns sum of values of n .
Display total salary of all employees in table emp
SELECT SUM(sal) Total FROM emp
Total
29081

78

Information Technology For JTOs PH-II- IT


COUNT()
This function counts the number of rows, satisfying any conditions, of the given
column or expression
SYNTAX
Argument type
Return Value
Description
Example
SQL>
Output

COUNT({*|[DISTINCT | ALL] expr})


Numeric
Numeric
Returns the number of rows in the query .
Count number of records in table emp
SELECT COUNT(*) Total FROM emp
18

MAX ( ) gives the maximum value from a given column or expression.


SYNTAX
Argument type
Return Value
Description
Example
SQL>
Output

MAX ([DISTINCT| ALL] expr)


Numeric
Numeric
Returns maximum value of argument expr.
Display maximum salary from table emp
SELECT MAX (sal) Maximum FROM emp
5004

MIN ( ) gives the minimum value from a given column or expression.


SYNTAX
Argument type
Return Value
Description
Example
SQL>
Output

BRBRAITT-JUN-2011

MIN([DISTINCT| ALL] expr)


Numeric
Numeric
Returns minimum value of employee.
Display the Joining date of seniormost employee.
SELECT MIN (hiredate) Minimum hire date
17-DEC-80

79

Information Technology For JTOs PH-II- IT

SQL GROUP BY and HAVING


Aggregate functions (like SUM) often need an added GROUP BY
functionality.
GROUP BY
GROUP BY... was added to SQL because aggregate functions (like SUM) return
the aggregate of all column values every time they are called, and without the
GROUP BY function it was impossible to find the sum for each individual group of
column values.
The GROUP BY clause is used to define the row groups for each of those the
aggregate functions (COUNT, MIN, MAX, AVG, and SUM) may be applied. When
aggregate functions are used without a GROUP BY clause, all the columns with
names mentioned in SELECT clause must be included in the aggregate
functions. Then these functions are applied to the total set of the rows that fit the
query predicate. Otherwise, all the columns in the SELECT list not included into
the aggregate functions must be listed in the GROUP BY clause. As a result, all
the returned query rows distributed into groups are characterized by the same
combinations of these column values. Later on, aggregate functions are applied
to each group. It is essential that NULL-values are considered equal in this case,
i.e. when grouping by the column including NULL-values, all these rows will be
combined in one group.
When a GROUP BY clause is used without any aggregate function in the
SELECT clause, the query will simply return one row from each group. Beside
the DISTINCT keyword, this opportunity may be used in eliminating the row
duplicates from the result set.
syntax
SELECT column1, SUM(column2) FROM table
GROUP BY column1
Example
SELECT job ,SUM(Sal) FROM Emp
GROUP BY job

BRBRAITT-JUN-2011

80

Information Technology For JTOs PH-II- IT

HAVING
HAVING... was added to SQL because the WHERE keyword could not be used
against aggregate functions (like SUM), and without HAVING... it would be
impossible to test for result conditions.
While WHERE clause gives predicate for filtering rows, the HAVING clause is
applied after grouping that gives a similar predicate but filtering groups by the
values of aggregate functions. This clause is nessesary for checking the values
that are obtained by means of an aggregate function not from separate rows of
record source in the FROM clause but from the groups of these rows. Therefore,
this checking is not applicable to the WHERE clause.
Syntax :SELECT column_a, SUM(column_b) FROM table
GROUP BY column_a
HAVING SUM(column_b) condition value
Example 1:-:
SELECT job ,SUM(sal) FROM EMP
GROUP BY job
HAVING SUM(sal)>10000
Example 2:-:
SELECT deptno,job ,SUM(sal) FROM EMP
GROUP BY deptno,job
HAVING job IN (CLERK,SALESMAN);

BRBRAITT-JUN-2011

81

Information Technology For JTOs PH-II- IT

Chapter 4
JOINS , Subqueries
Joins and Keys
Sometimes we have to select data from two or more tables to make our result
complete. We have to perform a join.
Good database design suggests that each table lists data only about a single
entity, and detailed information can be obtained in a relational database, by using
additional tables, and by using a join.
Tables in a database can be related to each other with keys. A primary key is a
column with a unique value for each row. Each primary key value must be unique
within the table. The purpose is to bind data together, across tables, without
repeating all of the data in every table.
A foreign key is a column in a table where that column is a primary key of another
table, which means that any data in a foreign key column must have
corresponding data in the other table where that column is the primary key. In
DBMS-speak, this correspondence is known as referential integrity.
In the "Employees" table below, the "Employee_ID" column is the primary key,
meaning that no two rows can have the same Employee_ID. The Employee_ID
distinguishes two persons even if they have the same name.
When you look at the example tables below, notice that:

The "Employee_ID" column is the primary key of the "Employees" table


The "Prod_ID" column is the primary key of the "Orders" table
The "Employee_ID" column in the "Orders" table is used to refer to the
persons in the "Employees" table without using their names

Employees:

Employee_ID

Name

01

Anil

02

Sindhu

BRBRAITT-JUN-2011

82

Information Technology For JTOs PH-II- IT

03

Jaya

04

Vinod

Orders:

Prod_ID

Product

Employee_ID

234

Printer

01

657

Table

03

865

Chair

03

Referring to Two Tables


We can select data from two tables by referring to two tables, like this:
Example
Who has ordered a product, and what did they order?
SELECT Employees.Name, Orders.Product
FROM Employees, Orders
WHERE Employees.Employee_ID=Orders.Employee_ID
Result

Name

Product

Anil

Printer

Jaya

Table

Jaya

Chair

BRBRAITT-JUN-2011

83

Information Technology For JTOs PH-II- IT


Example
Who ordered a printer?
SELECT Employees.Name
FROM Employees, Orders
WHERE Employees.Employee_ID=Orders.Employee_ID
AND Orders.Product='Printer'
Result

Name
Anil
INNER JOIN
OR we can select data from two tables with the JOIN keyword, like this:
Syntax:SELECT field1, field2, field3
FROM first_table
INNER JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield
Example:-Who has ordered a product, and what did they order?
SELECT Employees.Name, Orders.Product
FROM Employees
INNER JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID

BRBRAITT-JUN-2011

84

Information Technology For JTOs PH-II- IT


The INNER JOIN returns all rows from both tables where there is a match. If
there are rows in Employees that do not have matches in Orders, those rows will
not be listed.
LEFT JOIN
Syntax
SELECT field1, field2, field3
FROM first_table
LEFT JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield

List all employees, and their orders - if any.


SELECT Employees.Name, Orders.Product
FROM Employees
LEFT JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID
The LEFT JOIN returns all the rows from the first table (Employees), even if there
are no matches in the second table (Orders). If there are rows in Employees that
do not have matches in Orders, those rows also will be listed.
RIGHT JOIN
Syntax
SELECT field1, field2, field3
FROM first_table
RIGHT JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield

BRBRAITT-JUN-2011

85

Information Technology For JTOs PH-II- IT


List all orders, and who has ordered - if any.
SELECT Employees.Name, Orders.Product
FROM Employees
RIGHT JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID;
The RIGHT JOIN returns all the rows from the second table (Orders), even if
there are no matches in the first table (Employees). If there had been any rows in
Orders that did not have matches in Employees, those rows also would have
been listed.

Example
Who ordered a printer?
SELECT Employees.Name
FROM Employees
INNER JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID
WHERE Orders.product=Printer

SQL UNION and UNION ALL


UNION
The UNION command is used to select related information from two tables, much
like the JOIN command. However, when using the UNION command all selected
columns need to be of the same data type.
Note: With UNION, only distinct values are selected.

BRBRAITT-JUN-2011

86

Information Technology For JTOs PH-II- IT


SQL Statement 1
UNION
SQL Statement 2
Employees_Norway:

E_ID

E_Name

01

Anil

02

Sindhu

03

Jaya

04

Vinod

Employees_USA:

E_ID

E_Name

01

Sally

02

Kent

03

Jaya

04

Stephen

Using the UNION Command


Example
List all different employee names in Norway and USA:
SELECT E_Name FROM Employees_Norway
BRBRAITT-JUN-2011

87

Information Technology For JTOs PH-II- IT


UNION
SELECT E_Name FROM Employees_USA
Result
E_Name
Anil
Sindhu
Jaya
Vinod
Sally
Kent
Stephen

Note: This command cannot be used to list all employees in Norway and USA. In
the example above we have two employees with equal names, and only one of
them is listed. The UNION command only selects distinct values.
UNION ALL
The UNION ALL command is equal to the UNION command, except that UNION
ALL selects all values.

SQL Statement 1
UNION ALL
SQL Statement 2
Using the UNION ALL Command

BRBRAITT-JUN-2011

88

Information Technology For JTOs PH-II- IT


Example
List all employees in Norway and USA:
SELECT E_Name FROM Employees_Norway
UNION ALL
SELECT E_Name FROM Employees_USA
Result
E_Name
Anil
Sindhu
Jaya
Vinod
Sally
Kent
Jaya
Stephen

Subqueries
Objectives
During this lesson, you are presented with the concept of using subqueries to
return results from a database query more effectively.
What Is a Subquery?
A subquery is a query embedded within the WHERE clause of another query to
further restrict data returned by the query. A subquery is a query within another
query, also known as a nested query. A subquery is used to return data that will
be used in the main query as a condition to further restrict the data to be
BRBRAITT-JUN-2011

89

Information Technology For JTOs PH-II- IT


retrieved. Subqueries are used with the SELECT, INSERT, UPDATE, and
DELETE statements

A subquery can be used in some cases in place of a join operation by


indirectly linking data between the tables based on one or more
conditions.

When a subquery is used in a query, the subquery is resolved first, and


then the main query is resolved according to the condition(s) as resolved
by the subquery.

The results of the subquery are used to process expressions in the


WHERE clause of the main query.

The subquery can be used either in the WHERE clause or the HAVING
clause of the main query.

Logical and relational operators, such as =, >, <, <>, IN, NOT IN, AND,
OR, and so on, can be used within the subquery as well to evaluate a
subquery in the WHERE or HAVING clause.

The same rules that apply to standard queries also apply to Subqueries.
Join operations, functions, conversions, and other options can be used
within a subquery.

Guidelines:

Subqueries must be enclosed within parentheses.

A subquery can have only one column in the SELECT clause, unless
multiple columns are in the main query for the subquery to compare its
selected columns.

An ORDER BY cannot be used in a subquery, although the main query


can use an ORDER BY. The GROUP BY can be used to perform the same
function as the ORDER BY in a subquery.

Subqueries that return more than one row can only be used with multiple
value operators, such as the IN operator.

A subquery cannot be immediately enclosed in a set function.

The BETWEEN operator cannot be used with a subquery; however, the


BETWEEN can be used within the subquery.

Subqueries with the SELECT Statement

BRBRAITT-JUN-2011

90

Information Technology For JTOs PH-II- IT


Subqueries are most frequently used with the SELECT statement, although they
can be used within a data manipulation statement as well. The subquery, when
used with the SELECT statement, retrieves data for the main query to solve the
main query.
syntax:
SELECT select_list
FROM table_name
WHERE expr operator (SELECT select_list
FROM table_name
WHERE conditions);

The next query selects the deptno for a particular employee. This query is used
as the subquery in the following example.
Example:-SELECT deptno FROM emp
WHERE ename=JAMES;
The previous query is used as a subquery in the WHERE clause of the following
query. The following SQL statement returns the name and job of employees who
works in the same department as JAMES.

SELECT empno,ename,sal
FROM emp,
WHERE deptno = (SELECT deptno FROM emp
WHERE ename=JAMES);
The result of the subquery is used as the last condition of the WHERE clause
Subqueries are frequently used to place conditions on a query when the exact
conditions are unknown. When a single row subquery is used we should use a
single row comparison operator such as =, >, <, or <>,

BRBRAITT-JUN-2011

91

Information Technology For JTOs PH-II- IT


You can display data from a main query using a group function in a subquery to
return a single row. The subquery is in parentheses and is placed after the
comparison operator.

Example:Find out who earns least.


SELECT ename, job, FROM emp
WHERE sal=
(SELECT MIN(sal) FROM emp );
The preceding SQL statement returns the name and job of employees who has
min sal.
Using ANY, ALL, EXISTS Operators
SQL provides three very useful operators that are generally used with
subqueries. These are ANY,ALL & EXISTS predicates.
The EXISTS predicate
The EXISTS predicate evaluates to TRUE if the subquery returns any rows,
otherwise it evaluates to FALSE.
Example:SELECT dname, deptno FROM emp
WHERE EXISTS
(SELECT * FROM emp
WHERE dept.deptno=emp.deptno);

SOME, ANY and ALL operators


SOME and ANY are synonyms, i.e. any of them may be used. The subquery
results is a single value column.

BRBRAITT-JUN-2011

92

Information Technology For JTOs PH-II- IT


Syntax;expression> <comparison operator> SOME|ANY /(<subquery>

Compares a value to any of the values in a list or returned by a subquery.If any


value V returned by the subquery evaluates the operation "<expression value>
<comparison operator> V" to TRUE, the ANY clausecis also equal to TRUE.

Example:The following query show the details of those employees that have a salary
equal to any employee of deptno 30
SELECT * FROM emp
WHERE sal=ANY
(SELECT sal FROM emp
WHERE deptno= 30);
Or
SELECT * FROM emp
WHERE sal=SOME
(SELECT sal FROM emp
WHERE deptno= 30);

ALL Operator is similar to that with ANY, except that all values returned by the
subquery must meet the predicate "<expression> <comparison operator> V ".
Syntax:<expression> <comparsion operator> ALL (<subquery>)

BRBRAITT-JUN-2011

93

Information Technology For JTOs PH-II- IT


Example:-Show details of those departments that have salary more than or
equal to average salaries of all the job types.
SELECT * FROM emp
WHERE sal>=ALL
(SELECT AVG(sal) FROM emp
GROUPBY job);

Here are the formal rules for evaluating the predicate with ANY|SOME and ALL
parameters:

If ALL or SOME parameter are given and all the comparison results of
expression value with each value returned by the subquery are equal
to TRUE, truth value is TRUE.

If the result set of the subquery does not have any rows with the ALL
parameter specified, the result is TRUE. However, if the SOME
parameter is specified, the result is equal to FALSE.

If the ALL parameter has been specified and comparison of the


expression value with at least one value obtained from the subquery
gives FALSE, the truth value is equal to FALSE.

If the SOME parameter is specified and comparison of the expression


value with at least one value obtained from the subquery gives TRUE,
the truth value is equal to TRUE.

If the SOME parameter is specified and each comparison of the


expression value with the values obtained from the subquery gives
FALSE, the truth value is also equal to FALSE.

Otherwise, the result evaluates to UNKNOWN.

Nested Subqueries
Nesting is the act of embedding a subquery within another subquery. For
example:
Select * FROM Table_name

BRBRAITT-JUN-2011

94

Information Technology For JTOs PH-II- IT


WHERE ( SUBQUERY(SUBQUERY(SUBQUERY)));
Subqueries can be nested as deeply as your implementation of SQL allows.

BRBRAITT-JUN-2011

95

Information Technology For JTOs PH-II- IT

Chapter 5
Oracle Schema Objects (Views, Sequences, Indexes,
Synonyms)
Introduction
A schema is a collection of logical structures of data, or schema objects. A
schema is owned by a database user and has the same name as that user. Each
user owns a single schema. Schema objects can be created and manipulated
with SQL and include:

Tables
Views
Synonyms
Sequences
Stored Procedures
Tablespaces etc

Tables

A database table is a basic unit of data logical storage in an Oracle


database. Data is stored in rows and columns.
You define a table with a table name, such as employees, and a set of
columns.

You give each column a column name, such as ename, deptno and job a
datatype, such as VARCHAR2, DATE, or NUMBER; and a width.

The width can be predetermined by the datatype, as in DATE. If columns


are of the NUMBER datatype, define precision and scale instead of width.
A row is a collection of column information corresponding to a single
record.

BRBRAITT-JUN-2011

96

Information Technology For JTOs PH-II- IT

Views
Objectives
In this lesson, you will see how views can be used to present data to user in a
variety of ways. In addition, you will see how integrity constraints can be
enforced, if using a view to insert, update, or delete data.
At the end of this lesson, you should be able to

Explain the concept of view.

Use data dictionary views.

Create simple and complex views

Create a view with an option to enforce constraints.

Modify a view.

Remove a view.

Overview
Present logical subset or combination of data by creating views of tables.
What is a View?
A view is a logical table based on a table or another view. A view contains no
data of its own, but is rather like a window through which data from tables can
be viewed or changed. The view is stored as a SELECT statement in the data
dictionary.
Advantages of Views

Restrict access to the database because the view can display a selective
portion of the database.

Allow user to make simple queries to retrieve the result from complicated
queries. For example, views allow user to query information from multiple
tables without knowing how to write a join statement.

Provide data independence for ad hoc users and application programs.


One view can be used to retrieve data from several tables.

BRBRAITT-JUN-2011

97

Information Technology For JTOs PH-II- IT

Provide groups of users access to data according to their particular


criteria.

Create View Command


Creating a view by embedding a sub query with the CREATE VIEW statement.

CREATE [OR REPLACE] [FORCE / NOFORCE] VIEW


view_name
[(alias[, alias].)]
As subquery
[WITH CHECK OPTION [CONSTRAINT constraint]]
[WITH READ ONLY];

Example:CREATE VIEW emp_view AS


SELECT ename, job, deptno
FROM emp;

CREATE VIEW taxpayee AS


SELECT ecode, ename, gross*0.1
FROM emp
WHERE gross>8000;

Guidelines

BRBRAITT-JUN-2011

98

Information Technology For JTOs PH-II- IT

The query that defines a view can contain complex SELECT syntax,
including joins, group, and sub queries.

The query that defines the view cannot contain an ORDER BY clause.

If you do not specify a constraint name in the format SYS Cn.

You can use the OR REPLACE option to change the definition of the
view without dropping and re-creating it, or regranting object privileges
previously granted on it.

You can Control the column names by including column aliases within
the subquery.

You can Create a complex view that contains group function to display
values from two tables.

Types of Views
There are two classifications for views: simple and complex. The basic difference
is related to the DML operations.
Simple View Compared to Complex Views
Performing DML Operation on a View
Characteristic

Simple Views

Complex Views

Number of tables

Only one

One or more

Contain functions

No

Yes

Contain groups of data


No
(DISTINCT Or group functions)

Yes

DML through the view


Yes
No
You can perform DML operation on data through a view provided those
operations follow the rules outlined below:

A join condition

Group functions

A GROUP BY clause

The DISTINCT command

BRBRAITT-JUN-2011

99

Information Technology For JTOs PH-II- IT


You can modify data in a view unless it contains any of the above and any of the
following:

Columns defined by expression, for example, SALARY*12.


The ROWNUM pseudocolumn.

You can add data through a view unless it contains any of the above and there
are NOTNULL columns in the base table are not selected by the view. All
required values must be present in the view. Remember that you are adding
values directly into the underlying table through the view.

Group functions in views


The following example shows how to create a view with summarized data from
one or more underlying tables:
CREATE VIEW emplocation AS
SELECT ename empname, loc location
FROM emp,dept
WHERE emp.deptno=dept.deptno
GROUPBY loc;
A view can be created from multiple tables by using a JOIN in the SELECT
statement. WITH CHECK OPTION is discussed later this hour. The syntax is as
follows
Remember that when selecting data from multiple tables, the tables must be
joined by common columns in the WHERE clause. A view is nothing more than a
SELECT statement itself; therefore, tables are joined in a view definition the
same as they are in a regular SELECT statement. Recall the use of table aliases
to simplify the readability of a multiple-table query.
Removing a View
Use the DROP VIEW command to remove a view. The commands remove the
view definition from the database. Dropping views has no affect on the table on
which the view was based. Views or other applications based on deleted views
become invalid. Only the creator or user with the DROP ANY VIEW privilege can
remove a view.
Syntax
BRBRAITT-JUN-2011

100

Information Technology For JTOs PH-II- IT


DROP VIEW View_name

BRBRAITT-JUN-2011

101

Information Technology For JTOs PH-II- IT

Example:DROP VIEW taxpayee


Summary
A view is based on a table or another view and acts as a window through which
data on tables can be viewed or changed. A view does not contain data. The
definition of the view is stored in the dictionary. You can see the definition of the
view in the USER_VIEWS data dictionary table.
Advantages of views

Restrict database access

Simplify queries

Provide data independence

Allow multiple views of the same data

Remove views without affecting the underlying data

View Options

Can be a simple view based on one table

Can be complex view based on more than one table, or contain groups or
functions

Can be replace if one of the same name exists

Contain a check constraint

Can be read-only.

BRBRAITT-JUN-2011

102

Information Technology For JTOs PH-II- IT

Indexes
Overview
Indexes are created in an existing table to locate rows more quickly and
efficiently. It is possible to create an index on one or more columns of a table,
and each index is given a name. The users cannot see the indexes, they are just
used to speed up queries.
Note: Updating a table containing indexes takes more time than updating a table
without, this is because the indexes also need an update. So, it is a good idea to
create indexes only on columns that are often used for a search.
What is an index?
An index is a data base object that provides direct and fast access to row in a
table.
Indexes are logically and physically independent of the table they index. This
means that they can be create or dropped at any time and have no effect on the
base tables or other indexes.
How are Indexes created?
Two type of indexes can be created. One type is a unique index. The Oracle
Server automatically creates this index when you define a column in a table to
have a PRIMARY KEY or a UNIQUE constraint. The name of the index is the
same given to the constraint.
The other type of index a user can be create is a non-unique index. For example,
you can create a FOREIGN KEY column index for a join in a query to improve
retrieval speed.
Index Types
Type

Description

Unique

Ensures that values in specified columns are unique.

Non-unique

Ensures fastest possible results when querying data.

Single column

Only one column exists in the index.

Concatenated or
composite

Can contain up to 16 columns in the index for either


performance or uniqueness check purposes. The

BRBRAITT-JUN-2011

103

Information Technology For JTOs PH-II- IT


columns need not be adjacent.
Creating an Index
Syntax
CREATE INDEX index_name
ON table_name (column_name)
A Unique Index
Creates a unique index on a table. A unique index means that two rows cannot
have the same index value.
CREATE UNIQUE INDEX index_name
ON table_name (column_name)
A Simple Index
Creates a simple index on a table. When the UNIQUE keyword is omitted,
duplicate values are allowed.
The "column_name" specifies the column you want indexed.
This example creates a simple index, named "PersonIndex", on the Ename field
of the EMP table:
CREATE INDEX PersonIndex
ON EMP(Ename)
If you want to index the values in a column in descending order, you can add the
reserved word DESC after the column name:
CREATE INDEX PersonIndex
ON EMP(Ename DESC)
If you want to index more than one column you can list the column names within
the parentheses, separated by commas:
CREATE INDEX PersonIndex

BRBRAITT-JUN-2011

104

Information Technology For JTOs PH-II- IT


ON EMP(Ename job)
More is Not Always Better
More indexes on a table does not mean it will speed up queries. Each DML
operation that is committed on a table with indexes mean that the indexes must
be update. The more indexes you have associated with a table, the more effort
the server must make to update all the indexes after a DML.
When to Create an Index

The column is used frequently in the WHERE clause or in a join condition.


The column contains a wide range of values.

The column contains a large number of null values.

Two or more columns are frequently used together in a WHERE clause or


join condition.

The table is a large and most quires are expected to retrieve more than
10-15% of the rows.

Remember that if you want to enforce uniqueness, you should define a


unique constraint in the table definition. Then, a unique index is
automatically created.

When to Not Create an Index

The table is small.


The column are not often used as a condition in the query.

Most queries are expected to retrieve less than 10-15% of the rows.

The table is updated frequently

Removing an INDEX
You cannot modify indexes.To change an index ,you must drop it and then
recreate it.
Drop Index
You can delete an existing index in a table with the DROP INDEX statement.
Syntax
BRBRAITT-JUN-2011

105

Information Technology For JTOs PH-II- IT


DROP INDEX index_name
Example:DROP INDEX PersonIndex;

BRBRAITT-JUN-2011

106

Information Technology For JTOs PH-II- IT

SEQUENCES
Objectives
Many applications require the use of unique numbers as primary key values. You
can either build code into the application to handle this requirement or use a
sequence to generate numbers. This lesson covers creating and using sequence
that creates unique numbers.
At the end of this lesson, you should be able to

Explain the use of sequences.

Create a sequence.

Use a sequence.

Modify a sequence definition.

Remove a sequence.

Overview
A sequence generator can be used to automatically generate sequence numbers
for row in table. A sequence is a database object created by a user and can be
shared by multiple users.
A typical usage for sequence is to create a primary key value, which must be
unique for each row. The sequence is generated and incremented (or
decremented) by an internal Oracle routine. This can be a time saving object
because it can reduce the amount of application code needed to write a
sequence generating routine.
Sequence numbers are stored and generated independently of tables. Therefore,
the same sequence can be used for multiple tables.
Creating Sequence
Syntax:CREATING SEQUENCE sequence _ name [INCREMENT BY n]
[START WITH n] [{MAXALUE n /NOMAXVALUE}]
[{MINVALUE n /NOMINVALUE}]
[{CYCLE /NOCYCLE}] [{CACHE n / NOCACHE}];

BRBRAITT-JUN-2011

107

Information Technology For JTOs PH-II- IT


Where
Sequence_ name

is the name of the sequence generator

INCREMENT BY n

Specifies the interval between sequence numbers


where n is an integer. If this clause is omitted, the
sequence will increment by 1.

START WITH n

Specifies the first sequences number to be generated.


If this clause is omitted, the sequence will start with1

MAXVALUE n

Specifies the maximum value the sequence can


generate.

NOMAXVALUE

Specifies a maximum value of 1027 . This is the default


option.
Specifies a minimum sequence value.

MINVALUE n
NOMINVALUE

Specifies a minimum value of 1.

CYCLE/NONCYCLE

Specifies that the sequences continues to generate


values after reaching either its maximum or minimum
value or does not generate additional values.
NOCYCLE is the default option.

CACHE n/ NOCACHE

Specifies how many values the Oracle7 Server will


preallocate and keep in memory. By default, the server
will cache 20 values.

Example:CREATE SEQUENCE count Start with 50


increment by 1 ;
This sequence generates a sequence of counting nubers starting from 50

Using a Sequence
Once you create your sequence, you can use the sequence to generate
sequential numbers for use in your table. Reference the sequence values by
using the NEXTVAL and CURRVAL pseudo columns.

BRBRAITT-JUN-2011

108

Information Technology For JTOs PH-II- IT

NEXTVAL and CURRVAL pseudo columns


The NEXTVAL pseudocolumn is used to extract successive sequence numbers
from a specified sequence. You must qualify NEXTVAL with the sequence name.
When you reference sequence. NEXTVAL, a new sequence number is generated
and the current sequence number is placed in CURRVAL
The CURRVAL psedocolumn is used to refer to a sequence number that the
current use has just generated. NEXTVAL must be used to generate a sequence
number in the current users session before CURRVAL can be referenced. You
must qualify CURRVAL with the sequence name. When sequence. CURRVAL
referenced, the last value returned to that users process is displayed.
Rules for Using NEXTVAL and CURRVAL
You can use NEXTVAL and CURRVAL in
The SELECT list of a SELECT statement that is not part of a subquery.
The SELECT list of a subquery in an INSERT statement.
The VALUE clause of an INSERT statement.
The SET clause of an UPDATE statement.
You cannot use NEXTVAL and CURRVAL in
A SELECT list of view.
A SELECT statement with the DISTINCT keyword.
A SELECT statement with the GROUP BY, HAVING, or ORDER BY clauses.
A subquery in a SELECT, DELECT, or UPDATE statement.
A DEFAULT expression in a CREATE TABLE or ALTER TABLE command.

Example:CREATE SEQUENCE emp_seq Start with 100


increment by 1 ;
INSERT INTO emp values(emp_seq.nextval, Ravi , 1000) ;
SELECT emp_seq.CURRVAL FROM Dual;

BRBRAITT-JUN-2011

109

Information Technology For JTOs PH-II- IT

Caching Sequence Values


Cache sequence in the memory to allow faster access to those sequence values.
The cache is populated at the first reference to the sequence. Each request for
the next sequence value is retrieved from the cached sequence. After the last
sequence is used, the next request for the sequence pulls another cache of
sequences into memory.
Altering a Sequence
If you reach the MAXVALUE limit for your sequence, no additional values from
the sequence will be allocated and you will receive an error indicating the
sequence exceeds the MAXVALUE. To continue to use the sequence,
you can modify it by using the ALTER SEQUENCE command
Syntax
ALTER SEQUENCE sequence_name
[INCREMENT by n]
[{MAXVALUE n / NOMAXVALUE}]
[{MINVALUE n / NOMINVALUE}]
[{CYCLE /NOCYCLE}]
[{CACHE n / NOCACHE}]
Guidelines

You must own or you have the ALTER privilege for the sequence in order
to modify it.
Only future sequence numbers are affected by the ALTER SEQUENCE
command.

Some validation is performed. For example, a new MAXVALUE cannot be


imposed that is less than the current sequence number.

The START WITH option cannot be changed using ALTER SEQUENCE.


The sequence must be dropped and re-created in order to restart the
sequence at a different number.

BRBRAITT-JUN-2011

110

Information Technology For JTOs PH-II- IT

Removing a Sequence
To remove a sequence from the data dictionary, use the DROP SEQUENCE
command. You must be the owner of the sequence or have the DROP ANY
SEQUENCE privilege to remove it.
Syntax
DROP SEQUENCE sequence_name
Summary
The sequence generator can be used to automatically generate sequence
numbers for row in tables. This can be time saving, and reduce the amount of
application code needed.
A sequence is a database object that can be shared with other users. Information
about the sequence can be found in the USER_SEQUENCE table of the data
dictionary.
To use a sequence, reference it with either the NEXTVAL or the CURRVAL
pseudo columns.
Retrieve the next number in the sequence by referring sequence. NEXTVAL.
Return the current available number by referencing sequence. CURRVAL.

Synonyms
Synonyms are usually created so that a user can avoid having to qualify another
user's table or view to access the table or view.
What Is a Synonym?
A synonym is merely another name for a table or a view. Synonyms can be
created as PUBLIC or PRIVATE. A PUBLIC synonym can be used by any user of
the database; a PRIVATE synonym can be used only by the owner and any users
that have been granted privileges
Synonyms are of two types:Private Synonyms are the Synonyms created by a user for personal use.

BRBRAITT-JUN-2011

111

Information Technology For JTOs PH-II- IT


Example:- for assigning shorter name to objects created by the user
himself/herself.
Public Synonyms are those that are created by a user and that can be used by
all other users of the database.
Creating Synonyms
Syntax
CREATE [PUBLIC|PRIVATE] SYNONYM synonym_name FOR
TABLE|VIEW
Eg:-You create a synonym called sal, short for SALGRADE_TBL, in the following
example. This frees you from having to spell out the full table name.
CREATE SYNONYM sal FOR salgrade;
Dropping Synonyms
Dropping synonyms is like dropping most any other database object. The general
syntax to drop a synonym is as follows:
Syntax
DROP [PUBLIC|PRIVATE] SYNONYM synonym_name
Eg:-DROP SYNONYM sal;
Summary
Synonyms are used to simplify the name of another object in the database, either
by creating a synonym with a short name for an object with a long name or by
creating a synonym on an object owned by another user to which you have
access. There are two types of synonyms: PUBLIC and PRIVATE. A PUBLIC
synonym is one that is accessible to all database users, whereas a PRIVATE
synonym is accessible to a single user. A DBA typically creates a PUBLIC
synonym, whereas each individual user normally creates his or her own
PRIVATE synonyms

BRBRAITT-JUN-2011

112

Information Technology For JTOs PH-II- IT

Chapter 6
CONSTRAINTS
A constraint refers to a condition or a check that is applied to a column (field) or
set of columns in a table. The constraints applied to maintain data integrity are
also known as integrity constraints.
You can use constraints to

Enforce rules at the table level whenever a row is inserted, updated, or


deleted from that table. The constraint must be satisfied for the operation
to succeed.

Prevent the deletion of a table if there are dependencies from other tables.

The two basic types of constraints are


1. Column constraint

Which applies only to individual columns

2. Table constraint

Which applies to groups of one or more columns

Syntax for the CREATE TABLE command, expanded to include constraints is


as follows:
CREATE TABLE <table name>
(<column name><datatype> [(size)] <column
constraint>,
<column name><datatype> [(size)] <column
constraint> ..

BRBRAITT-JUN-2011

113

Information Technology For JTOs PH-II- IT


<table constraint> (<column name>,[<column
name> ..]).);
Different Constraints
1. NOT NULL
2. UNIQUE
3. PRIMARY KEY
4. FOREIGN KEY
5. DEFAULT
6. CHECK
1. NOT NULL Constraint
This specifies that the column can never have empty values (i.e. NULL
values).
CREATE TABLE employee

BRBRAITT-JUN-2011

(ecode

number(4)

NOT NULL,

ename

char(20)

NOT NULL,

gender

char(1)

NOT NULL,

grade

char(2),

gross

number(7) ) ;

114

Information Technology For JTOs PH-II- IT


The above command creates a table called employee in which the columns
ecode, ename and sex can never have NULL values. Any attempt to put
NULL values in these columns will be rejected.
2. UNIQUE Constraint
This constraint ensures that no two rows can have the same value in
the specified column(s). For example UNIQUE constraint applied on ecode
of employee table as shown below, ensures that no two rows can have the
same ecode value,
CREATE TABLE employee
(ecode
number(4)
NOT NULL UNIQUE,
ename
char(20)
NOT NULL,
gender
char(1)
NOT NULL,
grade
char(2),
gross
number(7) ) ;
NULL values are allowed if the unique key is based on a single column.
Unique constraints can be defined at the column or table-constraint level. A
composite unique key is created by using the table-level definition.
3. PRIMARY KEY Constraint
A PRIMARY KEY constraint creates a primary key for the table. Only
one primary key can be created for each table. The PRIMARY KEY
constraint is a column or set of columns that uniquely identifies each row in
a table. This constraint enforces uniqueness of the column or column
combination and ensures that no column that is part of the primary key can
contain a null value.
PRIMARY KEY constraints can be defined at the column or table-constraint level.
A composite PRIMARY KEY is created by using the table-level definition.
A UNIQUE index is automatically created for a PRIMARY KEY column.
Example:CREATE TABLE employee
( ecode integer
ename
gender
grade
gross

NOT NULL PRIMARY KEY,


char(20)
NOT NULL,
char(1)
NOT NULL,
char(2),
number(7) ) ;

BRBRAITT-JUN-2011

115

Information Technology For JTOs PH-II- IT

4. FOREIGN KEY Constraint


The FOREIGN KEY, or referential integrity constraint, designates a column
or combination of columns as a foreign key and establishes a relationship
between a primary key or a unique key in the same table or between tables.
A foreign key value must match an existing value in the parent table or be NULL.
FOREIGN KEY constraints can be defined at the column or table-constraint level.
A composite FOREIGN KEY is created by using the table-level definition.
The foreign key is defined in the child table, and the table containing the
referenced column is the parent table. The foreign key is defined using a
combination of the following keywords:

FOREIGN KEY is used to define the column in the child table at the tableconstraint level.
REFERENCES identifies the table and column in the parent table.
ON DELETE CASCADE indicates that when the row in the parent table is
deleted, the dependent rows in the child table will also be deleted.

Without th ON DELETE CASCADE option, the row in the parent table cannot be
deleted if it is referenced in the child table.
Master table
CREATE TABLE dept_data
(deptno
number(2)
PRIMARY KEY,
dname
varchar2(10));
Child table
CREATE TABLE emp_data
(empno
varchar2(5)
PRIMARY KEY,
location
varchar2(3),
deptno
number(2)
REFERENCES dept_data(deptno));
5. DEFAULT Constraint
A default value can be specified for a column using the DEFAULT clause.
When a user does not enter a value for the column (having default value),
automatically the defined default value is inserted in the field.
Consider the following SQL statement.

BRBRAITT-JUN-2011

116

Information Technology For JTOs PH-II- IT


CREATE TABLE employee
(ecode
integer
ename
char(20)
gender
char(1)
grade
char(2)
gross
number(7) ) ;

NOT NULL PRIMARY KEY,


NOT NULL,
NOT NULL,
DEFAULT=E1,

According to the above command, if no value is provided for grade, the


default value of E1 will be entered. The datatype of the default value has to be
compatible with the datatype of the column to which it is assigned. Insertion of
NULL (as default value) is possible only if the column definition permits. (NOT
NULL columns cannot have NULL as default). A column can have only one
default value.
6. CHECK Constraint
The CHECK Constraint defines a condition that each row must satisfy. The
condition can use the same constructs as query conditions, with the following
exceptions:

References to the CURRVAL, NEXTVAL, LEVEL, or ROWNUM


pseudocolumns.
Calls to SYSDATE, UID, USER, or USERENV functions
Queries that refer to other values in other rows.

CHECK constraints can be defined at the column- or table-constraint level. The


constraint syntax can apply to any column in the table, not only on the column on
which it is defined.
CREATE TABLE employee
( ecode
ename
gender
grade
gross

integer
char(20)
char(1)
char(2)
number(7)

BRBRAITT-JUN-2011

NOT NULL PRIMARY KEY,


NOT NULL,
NOT NULL,
DEFAULT=E1,
CHECK (gross>2000) ) ;

117

Information Technology For JTOs PH-II- IT

SQL Syntax Summary


Statement

Syntax

AND / OR

SELECT column_name(s)
FROM table_name
WHERE condition
AND|OR condition

ALTER TABLE (add column)

ALTER TABLE table_name


ADD column_name datatype

ALTER TABLE (drop column)

ALTER TABLE table_name


DROP COLUMN column_name

AS (alias for column)

SELECT column_name AS column_alias


FROM table_name

AS (alias for table)

SELECT column_name
FROM table_name AS table_alias

BETWEEN

SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2

CREATE DATABASE

CREATE DATABASE database_name

CREATE INDEX

CREATE INDEX index_name


ON table_name (column_name)

CREATE TABLE

CREATE TABLE table_name


(column_name1 data_type,
column_name2 data_type,.......)

CREATE UNIQUE INDEX

CREATE UNIQUE INDEX index_name


ON table_name (column_name)

CREATE VIEW

CREATE VIEW view_name AS


SELECT column_name(s)
FROM table_name
WHERE condition

BRBRAITT-JUN-2011

118

Information Technology For JTOs PH-II- IT


DELETE FROM table_name
(Note: Deletes the entire table!!)
DELETE FROM

or
DELETE FROM table_name
WHERE condition

DROP DATABASE

DROP DATABASE database_name

DROP INDEX

DROP INDEX table_name.index_name

DROP TABLE

DROP TABLE table_name

GROUP BY

SELECT column_name1,SUM(column_name2)
FROM table_name
GROUP BY column_name1

HAVING

SELECT column_name1,SUM(column_name2)
FROM table_name
GROUP BY column_name1
HAVING SUM(column_name2) condition value

IN

SELECT column_name(s)
FROM table_name
WHERE column_name
IN (value1,value2,..)

INSERT INTO

INSERT INTO table_name


VALUES (value1, value2,....)
or
INSERT INTO table_name
(column_name1, column_name2,...)
VALUES (value1, value2,....)

LIKE

SELECT column_name(s)
FROM table_name
WHERE column_name
LIKE pattern

ORDER BY

SELECT column_name(s)
FROM table_name
ORDER BY column_name [ASC|DESC]

BRBRAITT-JUN-2011

119

Information Technology For JTOs PH-II- IT

SELECT

SELECT column_name(s)
FROM table_name

SELECT *

SELECT *
FROM table_name

SELECT DISTINCT

SELECT DISTINCT column_name(s)


FROM table_name
SELECT * INTO new_table_name
FROM original_table_name

SELECT INTO
(used to create backup copies of
tables)

or

TRUNCATE TABLE (deletes only


the data inside the table)

TRUNCATE TABLE table_name

SELECT column_name(s)
INTO new_table_name
FROM original_table_name

UPDATE

UPDATE table_name
SET column_name=new_value
[, column_name=new_value]
WHERE column_name=some_value

WHERE

SELECT column_name(s)
FROM table_name
WHERE condition

SQL Summary
This module has taught you the standard computer language for accessing and
manipulating database systems.
You have learned how to execute queries, retrieve data, insert new records,
delete records and update records in a database with SQL.

BRBRAITT-JUN-2011

120

Information Technology For JTOs PH-II- IT

CHAPTER 7
PL/SQL ENGINE, BLOCKS, DATATYPES
PL/SQL first appeared in Oracle Version 6 in 1988. It was primarily
used within Oracles user interface product SQL Forms to allows for the inclusion
of complex logic within the forms. It replaced an old step method for logical
control and provided a reasonably simple programming language that resembled
ADA and C. Looking back at those days, we remember converting old Pro * C
programs into PL/SQL so that we could more easily maintain them. Actually, the
C programmer took another job, and we had lots of people who wanted to use
their new programming language knowledge. So we converted all the code in a
relatively short time frame, and here we are far ahead with some of that original
PL/SQL code still in use. We have come a long way since then. Today we use
PL/SQL to read data, to populate the database, create stored objects, and even
to display web pages. PL/SQL has certainly grown into a mature product. Oracle
has shown a strong dedication to the language, as illustrated by its use of
PL/SQL in many of its products, such as Oracle Applications. Oracle is also
using the web portion of PL/SQL quite extensively.
Have you visited
www.oracle.com lately ? If so, you have seen PL/SQL for the web in action. So
lets move on and look more closely at the PL/SQL programming language.
It is Just as important to learn PL/SQL as it is to learn SQL. So,
whether you are looking at becoming a DBA or an Oracle developer , knowledge
of PL/SQL is a skill that you must have in your database toolkit. In this session
we will discuss the following:

Overview of PL/SQL structure


Components of PL/SQL
Compilation and execution
Block structure
Variables and datatypes
Execution control
Looping
SQL in PL/SQL
Cursors
Exceptions
Stored procedures and functions and Packages
Triggers

BRBRAITT-JUN-2011

121

Information Technology For JTOs PH-II- IT

Terminology
The following Terminology will arm you with the technical jargon to get through
this chapter.

A program is a set of commands that perform a specific task.


Variables are programmer defined names to store information while
running a program.
The declare section is where you define the variables in a program.
The executable section is where you define the steps that will run in the
program you create.
An exception is a system-or user-defined error- handling mechanism
within a program.
A data type defines the class of a piece of information or data. For
example, you can think of information n as numbers or characters. In
programming, the same is true- a character data type would contain any
set of characters, and a numeric data type would contain decimals
between 0 and 9 and may be either a positive or negative value.
A PL/SQL block is the set of commands that constitute a PL/SQL program.
An anonymous PL/SQL block that may contain a declare section, will
always contain an executable section, and may contain an exception
section. A named PL/SQL block is one that is defined and named for
storage in the database.
An executable is the name of a programs written using one of an
assortment of computer programming languages. When you type the
name of an executable, the program runs. For example, when you use
SQL *Plus you enter the command sqlplus.
Arithmetic operators are symbols used to define mathematical operations
performed on data. The most common operators are + (additional),(Subtraction), / (division)), * (multiplication.)
Relational operators define comparisons or choices made on data. For
example, if you wish to see whether two dates are equal, you would use
the relational operator. Some common relational operators are =(equal), >
(greater than), < (less than), != (not equal).
A loop is a construct in a computer program in which a segment of code is
executed repeatedly.
An exit condition is the part of the loop where a test is performed on data.
If the test returns a result of true, then you might exit the loop.
An array is a data set that may be held in a memory structure that can
hold many rows of information. You can usually move from row to row in
an array. It is a variable, but it is one that may contain more than one
value at any one time.
A cursor is an Oracle memory structure that holds an SQL statement and
may also hold the result during the running of a program.

BRBRAITT-JUN-2011

122

Information Technology For JTOs PH-II- IT

A stored object is a PL/SQL program that is saved in the database and


may be shared and used by many developers and end users. Procedures,
packages, functions, and triggers are all examples of stored objects.

PL/SQL: THE ORACLE PROGRAMMING LANGUAGE


The Oracle 9i Database is more than just a database. It is also an
engine for many languages. It serves as a java engine with the built-in java
Virtual Machine (JVM), as well as a PL/SQL engine. This means that the
code may be stored in the database and then run. So there is no need for
another product. The PL/SQL engine is bundled with the database. Imagine
a product from Oracle that works really well and is free. How can they make
any money ? Lets look at how PL/SQL fits in to the Oracle database. The
following Figure shows you how PL/SQL works from within and from outside
the database.

BRBRAITT-JUN-2011

123

Information Technology For JTOs PH-II- IT

ORACLE DATABASE

INTEGRATED SQL
INTEGRATED
ENGINE SQL
ENGINE
PL/SQL
Stored
Program

External
Program
calls

PL/SQL
PL/SQL
Engine
Engine
SQL
ENGINE
SQL
ENGINE

DATABASE

FIGURE: PL/SQL architecture

In Figure, you see at the center the oracle 9i Server, the primary engine for
the data base. It serves as the coordinator for all calls to the database.
When a call is made from a program to the server to run a PL/SQL program,
the database (Oracle) loads the compiled program into memory, and then the
PL/SQL engine and SQL engine execute the program. The PL/SQL engine
will handle the programs memory structures and logical program flow. The
SQL engine then issues data requests to the database. It is a closed system
and one that allows for very efficient programming.
PL/SQL is used in numerous Oracle products, including :

The Oracle server

BRBRAITT-JUN-2011

124

Information Technology For JTOs PH-II- IT

Oracle forms
Oracle Reports
Oracle Warehouse Builder
Oracle Applications
Oracle Portal

All these programs use PL/SQL to some extent. There may be as


many as 5 million lines of Pl/SQL code contained in Oracle Applications, for
example. PL/SQL program can be called from these Oracle development
environments:

SQL *Plus
Oracle Enterprise Manager
Oracle precompilers (such as Pro *C, Pro *COBOL, etc.)
Oracle Call Interface (OCI)
Server Manager
Oracle 9i Application Server
Java Virtual Machine (JVM)

As you can see, PL/SQL is well established within most of


the Oracle9i line of products. You may now have some background in the
Pl/SQL architecture. Lets discover the basics of the language.

PL/SQL CHARACTER SET


As with all programming languages, there are characters that you
use to write your programs. Each language has its own rules and
restrictions when it comes to the valid characters. In the following
sections, we will learn the following:

Valid characters when programming in PL/SOL


Arithmetic operators
Relational operators

Supported Characters
When programming in PL/SQL, you may only use characters as defined here:

Upper-or lowercase characters


All digits between 0 and 9
Symbols: ( ) + -*/<>=!~;:.-@%,#^&_|{ }?[ ]

BRBRAITT-JUN-2011

125

Information Technology For JTOs PH-II- IT


Some of these characters are for program commands; others serve as
relation or arithmatic operators. Together they form a program.

Arithmetic Operators and Relational Operators


Table I shows the common arithematic operators and Table 2 shows the
commom relational operators used in PL/SQL. They are listed in the order
that they are executed (known as precedence, or priority). When the
functions appear in the same line, this means they are executed with the
same level of precedence, so the position of the expression will decide which
goes first.

Common Mathematical Operators


Operator

Meaning

**
*, /

Exponent
Multiplication,
division
+, - , ||
Addition, subtraction,
concatenation.

Common Relational Operators


Operator
=
<> or !=
>
<
>=
<=

Meaning
Equal
Not equal
Greater than
Less than
Greater than or equal
Less than or equal

PL/SQL STRUCTURE
The structure used in all of PL/SQL is the foundation for all of the
language. When you master it, you will be able to move forward, but if you do
not take the time to get this first step right, your journey will be difficult. Actually,
it is easy, Lets look at the structure that all of your Pl/SQL programs will have.
BRBRAITT-JUN-2011

126

Information Technology For JTOs PH-II- IT

You will have areas for program parameters (used to pass values from
outside a program to the program), internal variables, the main program code
and logic, and then some ways to handle things when they go wrong.

PL/SQL BLOCK STRUCTURE


A basic PL/SQL block of code can contain up to three parts. The order in
which the sections of the blocks are written is shown below:Section

Description

Declarative

Contains all variables, Optional


constants, cursors, and
user-defined
exceptions
that will be referenced
within
the
Executable
section.

Executable

Contains SQL statements Mandatory


to manipulate data in the
database and PL/SQL
statements to manipulate
data in the block.

Exception
Handling

Specifies the actions to Optional


perform when errors and
abnormal conditions arise
within
the
Executable
section.

Note:

Inclusion

In PL/SQ, an error or warning is called an exception.

BRBRAITT-JUN-2011

127

Information Technology For JTOs PH-II- IT


Section keywords DECLARE, BEGIN, and EXCEPTION are not followed
by semicolons. However, END and all other PL/SQL statements do require a
semicolon to terminate the statement. You can string statements together on the
same line. However, this method is not recommended for clarity or editing.

PL/SQL block structure

DECLARE -Optional
-Variables,constants,
cursors,user-defined exceptions
BEGIN -Mandatory
-SQL Statements
-PL/SQL control statements
EXCEPTION -Optional
-Actions to perform when errors occur.
END; - Mandatory

PL/SQL Block Structure

Every unit of PL/SQL comprises one or more blocks. These blocks can be
entirely separate or nested one within another. Therefore, one block can
represent a small part of another block, which in turn can be part of the whole
unit of code.

BRBRAITT-JUN-2011

128

Information Technology For JTOs PH-II- IT

PL/SQL Program constructs


The following list outlines a variety of different PL/SQL program constructs
using the basic PL/SQL block. They are available based on the environments
where they are executed
Program Construct

Description

Anonymous Block

Unnamed PL/SQL block All PL/SQL environments.


that is embedded within
an application or is
issued interactively.

Stored Procedure
Function

Availability

or Named PL/SQL block Oracle


Server
with
that
can
accept Procedural Extension.
parameters and can be
invoked repeatedly.

Application Procedure or Named PL/SQL block Components


Function
that
can
accept Developer/2000,
parameters and can be example forms.
invoked repeatedly.

of
for

Package

Named PL/SQL module Oracle


Server with
that groups
together procedural Extension.
related
procedures,
functions, and identifiers.

Database Trigger

PL/SQL block that is Oracle


Server with
associated
with
a Procedural Extension.
database table and is
fired automatically.

Application Trigger

PL/SQL block that is Components


associated
with
an Developer/2000,
application even and it example Forms.
fired automatically.

of
for

Note: A function is similar to a procedure, except that a function must return a


value.
The two types of constructs covered in this course are anonymous
blocks and subprograms.

BRBRAITT-JUN-2011

129

Information Technology For JTOs PH-II- IT

Anonymous Blocks
Anonymous blocks are un-named 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 execution at runtime. You can embed an anonymous block
within a precompiler program and within SQL* Plus or server Manager. Triggers
in Developer/2000 components consist of such blocks.

Subprograms
Subprograms are named Pl/SQL blocks. You can declare them either as
procedures or as functions. Procedure perform actions and functions return
values.
Developer/2000 components allow you to declare procedures and
functions as part of the application (a form or report), and call them from other
procedures, functions, and triggers.

BLOCK TYPES
Anonymous
[DECLARE]
BEGIN
--statements;

Procedure
PROCEDURE name

Function

IS

FUNCTION name
IS
BEGIN

BEGIN

--statements

--statements

RETURN value;

[EXCEPTION]

[EXCEPTION]

[EXCEPTION]
END;
END;

END;

PL/SQL VARIABLES AND DATATYPE

BRBRAITT-JUN-2011

130

Information Technology For JTOs PH-II- IT


You will almost always need to use variables in a PL/SQL program. It is here that
you will define how your data is to be held , while you work it through your
program.

Handling Variables in PL/SQL


Declare and initialize variables within the declarative section
Assign new values to variables within the executable section
Pass values into PL/SQL blocks through parameters
View results through output variables.

Delcaring PL/SQL Variables and Constants.


You need to declare all identifiers within the declaration section before
referencing them within the PL/SQL block.
Syntax
Identifier [ Constant ] datatype [ Not Null ]
[ := | DEFAULT expr ] ;
WHERE:
IDENTIFIER
CONSTANT
DATATYPE

- is the name of the identifier


- Constrains the identifier so that its
value cannot change; constant
must be initialized.
- Is a scalar or composite datatype

NOT NULL

- Constrains the variable so that it


must contain a value; NOT NULL
variables must be initialized

EXPR

- Is any PL/SQL expression that can


be a literal, another variable, or an
expression involving operators and
functions.

Guidelines

Name the identifier according to the same rules used for SQL objects
You can use naming conventions, for example v_name to represent a
variable, and c_name to represent a constant.
You have the option of assigning an initial Value to variables, unless they
are NOT NULL.

BRBRAITT-JUN-2011

131

Information Technology For JTOs PH-II- IT

Initialize the variable to an expression with the assignment operator (:=) or


equivalently, with the DEFAULT reserved word: otherwise, variables are
initialized to NULL by default.
Declare at most one identifier per line.

PL/SQL supports three datatypes - scalar, composite and reference that


you can use for declaring variables, constants and pointers.

Scalar Data types


A scalar data type holds a single value and has no internal components.
Scalar data types can be classified into four categories:

Number
Character
date and time
Boolean

Character and number data types have subtypes that associate a base
type to a constraint. For example, INTEGER and POSITIVE are subtypes of the
NUMBER base type.

Datatype
BINARY-INTEGER
NUMBER(Precision-scale)
CHAR (Maximumlength)
LONG
VARCHAR2(maximum-length)
DATE
BOOLEAN

BRBRAITT-JUN-2011

Description
Base type for integers between
2147483647 and 2147483647.
Base type for fixed and floating point
numbers.
Base type for fixed length character data
up to 32767 bytes. If you do not specify
a maximum length, the default length is
set to 1.
Base type for variable length character
data upto 32760 bytes.
Base type for variable length character
data up to 32767 bytes.
Base type for dates and times.
Base type that stores one of three
possible values used for logical
calculations: TRUE,FALSE, or NULL.

132

Information Technology For JTOs PH-II- IT

Scalar Variable Declarations: Examples


V_gender
V_count
V_total_sal
V_order_date
C_tax_rate
V_valid

CHAR(1);
BINARY_INTEGER := 0;
NUMBER(9,2) := 0;
DATE := SYSDATE + 7;
CONSTANT NUMBER(3,2) := 8.25;
BOOLEAN NOT NULL := TRUE;

Declaring Scalar Variables

Examples
1. Declare a variable to store the gender code (M or F)
V_gender
CHAR (1);
2. Declare a variable to count the iterations of a loop and intialize the variable to
0
V_count

- BINARY-INTEGER :=0;

3. Declare a variable to accumulate the total salary for a department and initialize
the variable to 0
V_total_sal

NUMBER (9,2) :=0 ;

4. Declare a variable to store the ship date of an order, and initialize the variable
to one week from today.
V_order_date DATE := SYSDATE + 7;
5. Declare a constant for the tax rate, which never changes throughout the
PL/SQL block.
C_tax_rate CONSTANT NUMBER (3,2) := 8.25;
6. Declare a flag to indicate whether a piece of data is valid or invalid, and
initialize the variable to TRUE.
V_valid

BOOLEAN NOT NULL : =TRUE;

BRBRAITT-JUN-2011

133

Information Technology For JTOs PH-II- IT

The %Type Attribute

The % TYPE Attribute

Declare a variable according to

- Another previously declared variable


- A database column definition.
Prefix %Type with
-The database table and column
-The previously declared variable name.
-PL/SQL determines the datatype and size of the variable.
When you declare PL/SQLvariables to hold column values, you must
ensure that the variable is of the correct datatype and precision. If it is not, then
a PL/SQL error will occur during the execution.
Rather than hard-coding the datatype and precision of a variable, you can
declare a variable according to another previously-declared variable or data base
column. You do this using the % TYPE attribute. To use the attribute in place of
the datatype required in the variable declaration, prefix it with the database table
and column names. If referring to a previously declared variable, prefix the
variable name to the attribute.
PL/SQL determines the datatype and size of the variable when the block
is compiled. So the variable is always compatiable with the database column or
identifier used to populate the variable.

Advantages of Using the %TYPE Attribute


The datatype of the underlying database column may be unknown.
The datatype of the underlying database column may change at runtime.
Examples
1. Declare variables to store the first and last names for an employee.
DECLARE
V_last_name
V_first_name

s_emp.lastname%TYPE;
s_emp.first_name%TYPE;

2. Declare variables to store the balance for a checking account, as well as


the minimum balance, which starts out as 10.
BRBRAITT-JUN-2011

134

Information Technology For JTOs PH-II- IT

DECLARE
V_balance
NUMBER (7,2);
V_minimum_balance v_balance%TYPE := 10;

A NOT NULL column constraint does not apply to variables declared


using %TYPE. Therefore, if you declare a variable using the % TYPE
attribute, using a database column defined as NOT NULL, you can
assign the NULL value to the variable.

DECLARING COMPOSITE DATATYPES


Declaring Records with the %ROWTYPE Attribute
The % ROWTYPE Attribute
Declare a variable according to a collection of columns in a
database table or view.
Prefix %ROWTYPE with the database table.
Fields within the RECORD take their names and datatypes
from the columns of the table or view.

Declaring a record based upon a collection of columns in a database table


or view by using the % ROWTYPE attribute. The fields within the record
take their names and datatypes from the columns of the table or view.

You declare records in the DECLARE section of a block, along with the
other types of variables you have seen.

Advantages of Using the %ROWTYPE Attribute

The number and datatypes of the underlying database columns may be


unknown.
The number and datatypes of the underlying database columns may
change at runtime.
The structure is the same as the cursor or the database table. Especially
useful when retrieving a row with the SELECT statement, or when
retrieving multiple rows with an explicit cursor.

Example

BRBRAITT-JUN-2011

135

Information Technology For JTOs PH-II- IT


Declare a variable to store the same information about a department as it is
stored in the S_DEPT table.

DECLARE
Dept_record
Emp_record

s_dept%ROWTYPE;
s_emp%ROWTYPE;

This declaration creates a record with the same field names and field
datatypes as a row in a table. DEPT_RECORD is a record. The fields
are:
DEPT_RECORD.ID,
DEPT_RECORD.NAME
and
DEPT_RECORD.REGION_ID

Referencing Non-PL/SQL Variables

Referencing Non-PL/SQL Variables


Reference non- PL/SQLvariables as host variables.
Prefix the reference with a colon ( : )

You can reference variables declared in the host or calling environment in


PL/SQL statements, unless the statement is within a procedure, function,
or package.
This includes host language variables declared
in
precompiler programs.
Screen fields in a Developer/2000 Forms
application, and SQL*Plus bind variables.
To reference host variables, you must prefix the references with a colon
( : ) to distinguish them from declared PL/SQL variables.

Example
Store the annual salary in a SQL *Plus global variable.
:g_annual_salary := v_salary *12;

BRBRAITT-JUN-2011

136

Information Technology For JTOs PH-II- IT

CHAPTER 8
CONTROL STRUCTURES, EXCEPTIONS, TRIGGERS
AND CURSOR
CONTROL STRUCTURES
At the heart of any programming language are its control structures.
Since Programs are written to handle a number of different situations, the
manner in which different conditions are detected and dealt with is the biggest
part of program control. Various types of control structures are used for this
purpose, including
If logic structures
Case expressions
Looping structures
Program control is governed by the status of variables and the data that is
read from and written to the database. As an example, picture yourself going into
the drivers license office to renew your drivers license. When you enter the
officer, you are presented with a number of directional signs. One sign reads
Driver Testing ; for this, you go to the second floor. Another sign tells you that
License Renewals is one the third floor. You are here for a renewal, so you
head up to the third floor. Once you arrive in the renewal office, you are once
again faced with some new choices. Now you have to decide whether you are
going to pay by cash or credit card. Cash payments are being accepted to the
right, and credit cards are to the left. You see that you have enough cash, and
you head to the payment wicket on the right. Let us look at Table below and see
how our program control influenced your choices.

step
1
2
3
4
5
6
7
8
9
10
11
12
13

process or decision to make

next steps

here for a driverss license yes=2 no=4


here is for driving test
yes=5 no=3
here for a license renewal
yes=6 no=4
ask for help
right place=1 wrong=13
go to second floor
7
go to third floor
9
line up for test
8
pass test
6
payment method
cash=10 credit=11
cash payment wicket
12
credit card payment
receive new license
13
go home leave building

BRBRAITT-JUN-2011

137

Information Technology For JTOs PH-II- IT


-------------------------------------------------------------------------------------------------TABLE- Program Control Decision Matrix

IF Logic Structures
When you are writing computer programs, situations present themselves
in which you must test a condition. When you ask a question in your program,
you are usually presented with one of two answers; it may be true or it may be
false. Computer programs are black and white; in computer logic, there can only
be true or false answers to your questions, no maybe. PL/SQL provides you with
three distinctive if logic structures that allows you to test for true and false
conditions. In everyday life we are presented with decisions that we need to
make; the following sections will show you how to do it using PL/SQL.

IF - THEN
You use the if-then construct to test the simplest type of condition. If the
condition evaluates to true, then one or more lines of program code will be
executed. If the condition evaluates as false, then no action is taken. The
following code snippet illustrates how this is performed with a PL/SQL program.
IF I_date > 11-APR-03 then
I_salary := I_salary * 1.15;
- - Increase salary by 15%
END IF:
NOTE:

Each IF statement is followed by its own then. There is also no


semicolon ( ; ) terminator on a line that begins with an IF.

To add comments to your code, start a comment line with /* and end with
*/ or you may use the double hyphen ( - -) as we have done in the above
example.
In this case, if the value of the variable I_date is greater than 11th of
April 2003, then the salary will be increased by 15 percent . This
statement may also be restated using the following statement.
IF not (I_date <= 11 APR-03) then
I_salary := I_salary *1.15;
-- Increase salary by 15%
END IF;
Also, you nest IF _ THEN statement to increase the power
of your statements. Let us add a condition to limit who gets the raise:

BRBRAITT-JUN-2011

138

Information Technology For JTOs PH-II- IT


IF I_date > 11-Apr-03 then
IF I_last _name = PAKMAN then
I_salary := 1-salary *1.15 ;
-- Increase salary by 15%
END IF;
END IF:
Now, not only must the date be greater than the 11th of April ,2003, but
also your last name must be equal to Pakman in order to get the raise. This a
method that we use to make sure human resource programs give programmers a
raise every year.
What you should also notice in this code is that there are now two end if
statements. This is a required construct, since you must always pair an if
statement with an end if; so if you are going to have nested if statements, you
must ensure that each is paired with a matching end if;
NOTE
Each IF statement block must have at least one line of program code.
If you wish to do nothing within your program code, simply use the
NULL; command.

IF - THEN ELSE
The if-then-else construct is similar to the simple if-then construct. The
difference is that when the condition executes as false , the program statements
that follow the else statement are executed. The following code illulstrated this
logic within PL/SQL.
IF I_date > 11-APR-03 then
I_salary := I_salary *1.15 ;
-- Increase salary by 15%
ELSE
I_salary := I_salary *1.05 ;
--Increase salary by 5%
END IF;
In the preceding code listing, you see the condition that if the date is
greater than the 11th of april, 2003, you will get a 15 percent salary increase.
However, when the date is less than or equal to this date, you will only receive a
5 percent increase.
As with the simple if-then construct, you may nest the if-then-else
construct. Let us look at how this might appear in our PL/SQL program:
IF I_date > 11-Apr-03 then

BRBRAITT-JUN-2011

139

Information Technology For JTOs PH-II- IT


IF I_last_name = PAKMAN then
I_salary := I_salary *1.15;
-- Increase salary by 15%
ELSE
I_salary := I_salary *1.10;
-- Increase salary by 10%
END IF;
ELSE
I_salary := I_salary *1.05;
-- Increase salary by 5%
END IF;

This leads us to another note on using the if statement within


PL/SQL

NOTE:- Only one else statement is allowed within every if statement


construct, and there is no semicolon(;) on the line starting with else.

IF THEN - ELSIF
The final if construct that we will show you is if-then-elsif. In this case,
you provide yourself with the option to test another condition when the first
condition is evaluated as false. When you want to test for more than one
condition without using nested if statements, this is the type of statement that you
might use.
IF I_last__name = PAKMAN then
I_salary := I_salary *1.15;
-- Increase salary by 15%
ELSIF I_last_name = ASTROFF then
I_salary := I_salary *1.10;
-- Increase salary by 10%
ELSE
I_salary := I_salary *1.05;
-- Increase salary by 5%
END IF;
In the preceding statement, if your last name is Pakman, you
get a 15 percent raise; if it is Astroff, you get 10 percent; and the rest of us
get only a 5 per cent raise. There is no limit to the number of elsif
conditions that you may use within this construct. The following shows
you an example of using multiple elsif statement within the construct.
IF I_city = OTTAWA then
L_team_name := SENATORS;
ELSIF I_city = LOS ANGELS then

BRBRAITT-JUN-2011

140

Information Technology For JTOs PH-II- IT


L_team_name := KINGS;
ELSIF I_city = NEW YORK then
L_team _name := RANGERS;
ELSIF I_city = TORONTO then
L_team_name := MAPLE LEAFS;
END IF;
NOTE: There is no matching END IF statement for each elsif. Only a single
END IF is required within this construct.
When writing your PL/SQL program, use indentation to simplify the
reading of the program, as in the code segments shown here. As a rule , you
should line up each if-then-else statement, and indent the program code that lies
between each of these words.

CASE EXPRESSIONS
The next logical step from the if statement is the case statement. The
case statement, which was introduced with Oracle 9i, is an evolution in logical
control. It differs from the if-then-else constructs in that you now can use a simple
structure to logically select from a list of values. More important, it may be used
to set the value of a variable. Let us look at how this may be done. First, let us
look at the format:
CASE variable
WHEN expressional then value 1
WHEN expression 2 then value 2
WHEN expression 3 then value 3
WHEN expression 4 then value 4
ELSE value 5
END;

There is no limit to the number of expressions that may be defined in a


case expression. Here is an example of the use of the case
expression:

SQL>run
1 DECLARE
2 val varchar2(100) ;
3 city varchar2 (20) := TORONTO;
4 BEGIN
5 val := CASE city
6 WHEN TORONTO then RAPTORS
7 WHEN LOS ANGELS then LAKERS
8 WHEN BOSTON then CELTICS

BRBRAITT-JUN-2011

141

Information Technology For JTOs PH-II- IT


9
10
11
12
13
14
15

WHEN CHICAGO then BULLS


ELSE NO TEAM
END;
dbms_ouput.put_line (val);--output to the screen
* end;
RAPTORS

PL/SQL procedure successfully completed.


NOTE:

In order to get oracle to provide ouput from a PL/SQL program, you


must set the environment variable within SQL* Plus. To do this, type
as follows:
SET serveroutput on

Although you can use the if-then-else to achieve the same purpose, the
case statement is easier to read and more efficient. Remember that once Oracle
9i reaches a value in the case statement that meets the condition, the
processing of the case statement will stop.
LOOPS
Loops are control structures that allow you to repeat a set of
commands until you decide that it is time to stop the looping.
Generally, the format that all loops take is the flowing:
LOOP
Executable statements;
END LOOP;
Each time the loop is executed, the statements within the loop are
executed, and then the program return to the top of the loop structure to do it all
over again. However, if you ever want this processing to stop, you will need to
learn about the EXIT statement.
The exist statement allows you to stop executing within a loop without a
condition. It will then pass control back to the program and will continue on after
the loop statements.

BRBRAITT-JUN-2011

142

Information Technology For JTOs PH-II- IT

The following is how to get out of a tight loop:


LOOP
IF I_batting_average <= 300 then EXIT;
ELSE
L_decision := STAY IN MAJORS;
END IF;
END LOOP;
There are many other kinds of loops that provide more control over
looping. Each has its uses in PL/SQL programming, and each should be learned
so that you have maximum flexibility in your programming needs.

The while Loop


The while loop will continue to execute as long as the condition that you
have defined continues to be true. If the condition becomes false, then you exit
the loop. Let us look at an example.
WHILE I_sales_total < 100000 LOOP
SELECT sales_amount INTO
I_sale_amount
FROM daily_sales;
I_sales_total := I_sales_total + I_sale_amount;
END LOOP;

Although you may use the exist command to do the same thing. It
is better form to use the while expression.

The for Loop


The for loop is one of the most common loops that you will encounter in
your PL/SQL travels. This loop allows you to control the number of times that a
loop executes.In the case of the while loop, you are never quite sure how many
times a loop is executed, since it will continue to loop until a codition is met. The
for loop allows you to define the number of times that you will be looping when
you program the loop itself. You will define the value to start your loop with and
the value that will terminate your loop. Let us look at some syntax;
FOR I_counter IN 1 .. 10
LOOP
Statements;
END LOOP;

BRBRAITT-JUN-2011

143

Information Technology For JTOs PH-II- IT

So, what is important for you to note in the preceding statement? First,
you need to know that the variable I_counter will hold the value between 1 and
10. How do we know it will be between 1 and 10 ? Well, after the IN, we place
the counters range. In this case, the counter starts at I, the low bound, and
continues to 10. You should also note the two dots. (..) between the two integer
values (1 and 10). This tells Oracle 9i that you would like it to count between
these two numbers.
One more note:

regardless of any previous values that the variable I_counter has


been set to in an earlier command in your program, when you use
the values in the loop, you will discover that they are now set to
values between 1 and 10.
You can also count backward using the REVERSE clause. The
next code listing shows you how the reverse clause may be used.

DECLARE
I_counter number;
BEGIN
FOR I_counter IN REVERSE 1..5
LOOP
Dbms_output.put_line (I_counter);
END LOOP;
End;
/
5
4
3
2
1
PL/SQL procedure successfully completed.
Now you can see how easy it is to use simple loops, but loops have much
more power. Using loops like the while loop or the for loop allows you to use
variables instead of hard coded values. This gives you the greatest possible
flexibility because you can have the database or external data provide you with
the limits within your loop. Let us look at how this might work. In the following
example, we select the number of employees in our employee table, and then
show how the counter counts from 1 to the number of employees in our small
company.

BRBRAITT-JUN-2011

144

Information Technology For JTOs PH-II- IT


SQL>run
1 DECLARE
2 I_emp_count number;
3 i number ; -- We will use this as our counter
4

BEGIN

5
select the number of employees in the
I_emp_count variable

--

6 Select count (*) into I_emp_count from employees;


7
8

FOR i IN 1 .. I_emp_count LOOP

9 dbms_output.put_line (Employee || i);


10

END LOOP;

11 *END;

Employee 1
Employee 2
Employee 3
Employee 4
Employee 5
Employee 6

PL/SQL procedure successfully completed.

BRBRAITT-JUN-2011

145

Information Technology For JTOs PH-II- IT


- As you might have guessed, we have six employees in our company. (It
may be small, but it is very good.) The important point is that you may use
variables in your loops. The other line that you may have noticed is the select
statement contained in this PL/SQL block. You might be thinking, what are they
talking about and where did this come from ? Well, we have not told you about
select statements in your Pl/SQL programs, but this seems like a perfect time to
talk about SQL in your PL/SQL programs.

SQL in Your PL/SQL Programs

We have looked at a lot of structure up until now. You should know that a
PL/SQL program will always have a BEGIN and END. It may have variables ,
loops, or logic control, but your next question must be wheres the best ? What
gives PL/SQL its beef is SQL. Since you have all these CONTROL structures,
you need to use them in conjunction with information.You may want the
information so that you can create a report, update data, create new data,and
delete old data, or perform just about any other function that you can think of. It
is very important for you to see how you can integrate data into PL/SQL code.
Without data, PL/SQL is just PL.

EXCEPTIONS
INTRODUCTION
When you execute PL/SQL program, you may encounter errors, that stop
the program. Any well-written program must have the ability to handle such
errors intelligently and recover from them , if possible. PL/SQL implements error
handling via exceptions and Exception Handlers which can be associated with
oracle errors or with user defined errors. In this chapter, we wll discuss the
types of exceptions, how exceptions are raised and handled, association of
exceptions with ORACLE error and the rule of the exception propogation. It also
provides the guidelines on using exceptions.
We already know how PL/SQL is based on the ADA language. One of the
features of ADA that is incorporated into PL/SQL is the exception mechanism,
that makes your programs robust and able to deal with both unexpected and
expected errors during execution.
What kinds of error can occur in a PL/SQL Program ?

BRBRAITT-JUN-2011

146

Information Technology For JTOs PH-II- IT


Errors can be classified as compile-time and run-time errors. Compiletime errors are reported by PL/SQL compiler interactivelty & you have to correct
them. Without correcting them PL/SQL wll not run at all.
So exceptions are designed for runtime error handling only, rather than
compile time error handling.
WHAT IS EXCEPTION?
An exception is an identifier in PL/SQL which is raised when an error
occurs, during the execution of a block. This terminates its main body of actions
and transfers control to a separate program called exception handler , which
specifies the final action to be performed. This separates the error handling from
the rest of the program which makes the logic of the program, easier to
understand. This also ensures that all errors will be trapped.
In a language (such as C) that does not use the exception model for error
handling , you must explicitly insert error handling code in order to ensure that
your program can handle errors , in all cases.
For example
Int x,y,z;
Function(x); /* function call, passing x as an argument */
If < an error occurred >
Handle_error ();
Y = 1/z;
Handle_error(.);
Z = x+y;
Handle_error ();

Note that a check for errors must occur after each statement in the
program. If you forget to insert the check, the program will not properly
handle an error situation. In addition, the error handling can clutter up
the program, making it difficult to understand the programs logic.

The preceding example can be simplified in PL/SQL as follows:


DECLARE
X
NUMBER;
Y
NUMBER;
Z
NUMBER;
BEGIN
Function(x);
Y = 1/z;
Z = X+Y;

BRBRAITT-JUN-2011

147

Information Technology For JTOs PH-II- IT


EXCEPTION
When OTHERS then
/* handler to execute all errors */
handle_error(.);
END;

Note that the error handling code is separated from the programs
logic. This solves problems occurring in the previous case.

Programs logic is easier to understand, since it is clearly visible.


No matter which statement fails, the programs will detect and handle
the error.

TRAPPING EXCEPTIONS:
Generally exceptions are declared in the declarative section of the block,
raised in the executable section and handled in the exception section.
PL/SQL provides a set of system defined exceptions and allows you to
add user defined exceptions.
There are 3 types of exceptions. They are as follows.
1.

PREDEFINED ORACLE SERVER ERROR:


This is one of approximately 20 most common SQL errors that occur often
in PL/SQL program, which are defined in the package STANDARD . This
package is available to any PL/SQL block. So this exception need not be
declared. They are also raised automatically when the associated ORACLE
error occurs. Only they need to be handled in the exception handling section.
2.

NON PREDEFINED ORACLE-SERVER ERROR


Any other standard ORACLE server error falls in this category . Declare
this exception within the declarative section, and allow the ORACLE server to
raise them implicitly.
3.

USER DEFINED ERROR


A condition that the developer determines is abnormal, can be defined by
the program as a user_defined exception. It could be an error with the data
also. Declare it with the declarative section, raise and handle it explicitly.

The system_defined exceptions are as follows:

BRBRAITT-JUN-2011

148

Information Technology For JTOs PH-II- IT

CURSOR_ALREADY_OPEN:
Raised if an open statement tries to
open a cursor that is already open. You must close a cursor before you
can reopen it. SQL CODE is set to -6511 (error is ORA-06511)
INVALID_CURSOR: Raised if you attempted to open an undeclared
cursor, or close, one that was not opened or fetch from one that was not
open, and so on. SQLCODE is set to -1001 (error is ORA-01001).
INVALID_NUMBER: Raised on a conversion error from a character string
to a number, when the character string does not contain a legitimate
number in a SQL statement. SQL CODE is set to 1722. (error is ORA01722)
LOGIN_DENIED:
Raised if user tries to logon to ORACLE with
an invalid username/ password. SQLCODE is set to -1017 (error is 0RA01017.)
DUP_VAL_ON_INDEX:
Raised if an insert or update would
have caused a duplicate value in unique database column. SQLCODE is
set to 1 (error is ORA-00001).
NO_DATA_FOUND :
Raised if a select statement returns nothing.
SQLCODE is set to- +100 (error is ORA-01403)
TOO_MANY_ROWS:
Raised when select statement that is supposed
to return just one row , returns more than one (this is also raised by a
subquery that is only supposed to return one row). SQL CODE is set to
1422 (error is ORA-01422)
NOT_LOGGED_ON:
Raised if you attempt any sort of database call
without being logged on to ORACLE. SQLCODE is set to-1012 (error is
ORA-01012.)
PROGRAM_ERROR:
Raised if PL/SQL itself has an internal problem
executing the code such as exiting a function that has no return statement.
SQLCODE is set to - 6501 (ERROR IS ORA -06501)
STORAGE _ERROR;
Raised if PL/SQL needs more memory than is
available that is run out of memory or memory is corruputed. SQLCODE
is set to 6500 (error is ORA-06500)
TIMEOUT_ON_RESOURCE:
Raised when a time out occurs while
ORACLE is waiting for a resource. This usually means an instance has
had an abnormal termination. SQLCODE is set to -51 (error is ORA00051)
TRANSACTION_BACKED_OUT: Raised when the remote part of a
transaction is rolled back due to deadlock or data might be inconsistent at
some node. SQLCODE is set to - 61 (error is ORA-00061)
VALUE_ERROR:
Raised when the value of a column of PL/SQL is
damaged by arithematic, conversion, truncation or constraint error occurs
in a procedural statement. If the error occurs in a SQL statement,
INVALID_NUMBER is raised instead. SQLCODE is set to 6502 (error is
ORA-01456)
ZERO_DIVIDE:
Raised when a statement tries to divide a number by
zero. SQLCODE is set to - 1476 (error is ORA-01476)

BRBRAITT-JUN-2011

149

Information Technology For JTOs PH-II- IT

DECLARING,RAISING & HANDLING EXCEPTIONS:


1.
DECLARING EXCEPTIONS:
User defined & ORACLE
predefined exceptions are declared in the declarative section as follows:

non

SYNTAX:
Exception_name EXCEPTION;

Where exception_name is the name of the exception and EXCEPTION


is the keyword for declaring exception.

2.
RAISING EXCEPTION:
When the error associated with an exception
occurs, the exception must be raised. User defined exceptions are raised
explicitly within the executable section using RAISE statement. Predefined
exceptions are raised automatically when their associated ORACLE error occurs.
For e.g. if the error ORA-01403 occurs when no rows are retrieved from the
database, the PL/SQL raises the exception NO_DATA_FOUND.

SYNTAX:
RAISE exception_name;
Where exception_name is the name of the previously defined
exception.
3.
HANDLING EXCEPTIONS:
Reference the declared exception within
the corresponding exception handling routine using WHEN CLAUSE.
WHEN exception_name THEN
Statements;
Where exception_name is the name of the exception declared in the
declarative section and raised in the exevutable section.

EXAMPLE FOR USER DEFINED EXCEPTION:


DECLARE
e_invalid_staffno EXCEPTION;
BEGIN
BRBRAITT-JUN-2011

150

Information Technology For JTOs PH-II- IT

IF &&p_staffno IS NULL OR
(TO_NUMBER (&p_staffno)
NOT BETWEEN 1000 ND 9999
THEN
RAISE e_invalid_staffno;
ELSE
INSERT INTO emp_data (staffno,emp_name, deptno)
VALUES (&p_staffno, &p_name, &p_deptno);
INSERT INTO emp_sal (staffno)
VALUES (&p_staffno);
END IF;
EXCEPTION
WHEN e_invalid _staffno THEN
INSERT INTO MESSAGE
VALUES (INVALID STAFF NUMBER, Staff number: || &p_staffno ||
must be between 1001 and 9999 );
END;
/
EXPLANATION: In the above example e_invalid_staffno is defined as an
exception in the declarative section by the user. In the executable section the
verification of staff number i.e. whether it is within the range 1001 -9999 is
verified by the IF. ..END IF clause. If it is not, the exception e_invalid_staffno is
raised and control is transferred to the corresponding exception handling section
and a message is inserted into the table message.

Examples for pre defined exceptions:

Example for INVALID NUMBER

INSERT INTO emp_data


VALUES (ABCD,Kaimal, SDE, 10-Jan-50,TVM,10);
DECLARE
V_sl
V_Staffno
V_name
V_desgn
V_hq

NUMBER (2);
CHAR (4);
varchar2(25);
varchar2(5);
CHAR(3);

BRBRAITT-JUN-2011

151

Information Technology For JTOs PH-II- IT

BEGIN
SELECT
TO_NUMBER(staff no) -1000 as
Emp_name,desgn, hq
INTO v_sl,v_staffno, v_desgn, v_hq
FROM emp_data
WHERE staffno = ABCD;
INSERTINTO message
VALUES (to_char (v_sl) || - || v_staffno,
v_name || || desgn || - ||v_hq);

SL_NO,

staffno,

EXCEPTION
WHEN INVALID_NUMBER THEN
INSERT INTO Message
VALUES (invalid number, There is a wrong character value in the staff
number);
END;
/
Now execute the program and see the resultas follows:
SQL>SELECT *FROM MESSAGE;
OUTPUT:
INVALID NUMBER There is a wrong character value in the staff number.
Explnation:

The staffno ABCD is converted to a number by the TO_NUMBER


function in the SQL statement. But since abcd cannot be converted
into a number, the exception INVALID_NUMBER is raised and action
is taken accordingly.

Example for DUP_VAL_ON_INDEX:


DECLARE
BEGIN
INSERT INTO emp_data (staffno, emp_name, deptno)
VALUES (&p_staffno, &P_name, &p_deptno);
Insert into EMP_SAL(staffno)
Values (&p_staffno);

BRBRAITT-JUN-2011

152

Information Technology For JTOs PH-II- IT


EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
INSERT INTO MESSAGE
VALUES(DUP_VAL_ON_INDEX,
STAFFNO || &p_sattno || already exists);
END;
EXPLANATION:
When you try to insert a new row with the existing staff no,
DUP_VAL_ON_INDEX is raised and action is taken accordingly.
Example for NO_DATA_FOUND AND TOO_MANY_ROWS:
DECLARE
V_basic
V_name
V_desgn

emp_sal.basic%TYPE;
emp_data.emp_name%TYPE;
emp_data.desgn%TYPE;

BEGIN
SELECT emp_name,desgn INTO
V_name,v_desgn
FROM emp_data
WHERE staffno = &&_staffno;
Select basic INTO v_basic
FROM emp-sal
WHERE staffno = &p_staffno;
INSERT INTO PAYBILL(Staffno,emp_name,desgn,basic)
VALUES (&p_staffno,v_name,v_desgn,v_basic);
EXCEPTION
When NO_DATA_FOUND THEN
INSERT INTO MESSAGE
VALUES (NO_DATA_FOUND,
There is no record of information for this staff no: || &p_staffno);
WHEN TOO MANY_ROWS THEN
INSERT INTO MESSAGE
VALUES (TOO_MANY_ROWS,
There are more than 1 records for this staff number : || &p_staffno);
END;
//

BRBRAITT-JUN-2011

153

Information Technology For JTOs PH-II- IT

EXPLATION:
When there is no record under the given staffno in
EMP_DATA table, no row is returned by the SQL statement and so
NO_DATA_FOUND exception is raised and action is taken accordingly . When
there are more than 1 record for the given staffno in EMP_SAL table, more than
one row is retrieved by the 2ndSQL statement and so TOO_MANY_ROWS
exception is raised and action is taken accordingly.

EXAMPLE FOR VALUE_ERROR:


Both of the following examples raise VALUE_ERROR.
Example I :
DECLARE
Tempvar

varchar2(3);

BEGIN
Tempvar := ABCD;
EXCEPTION
WHEN VALUE _ERROR THEN
INSERT INTO message
VALUES (VALUE_ERROR,
There is an error in the assignment of value to the variable);
END;
/
Example 2:
DECLARE
Tempvar

varchar2(3);

BEGIN
SELECT staffno
INTO tempvar
FROM emp_data
WHERE staffno = 1001 ;
EXCEPTION

BRBRAITT-JUN-2011

154

Information Technology For JTOs PH-II- IT

WHEN VALUE_ERROR THEN


INSERT INTO message
VALUES (VALUE_ERROR,
There is an error in the assignment of value to the variable);
END;
/
EXPLANATION: The error can occur either as a result of an assignment
statement or selectinto statement.
EXAMPLE FOR ZERO_DIVIDE:
DECLARE
V_maxbasic NUMBER(6);
V_MINBASIC
NUMBER(6);
V_ratio
NUMBER(5,2)
BEGIN
SELECT MAX(basic), MIN(basic)
Into v_maxbasic, v_minbasic
FROM emp_sal;
V_ratio := v_maxbasic / v_minbasic;
INSERT INTO message
VALUES (NULL ,
The ratio between maximum and minimum basicpay is ||
to_char(v_ratio));
EXCEPTION
WHEN ZERO_DIVIDE THEN
INSERT INTO message
VALUES (ZERO_DIVIDE ERROR,
There is zero value in the basicpay);
END;
/
Now execute the program and see the result as follows
SQL>SELECT * FROM message;

BRBRAITT-JUN-2011

155

Information Technology For JTOs PH-II- IT

OUTPUT
The ratio between maximum and minimum basic pay is x.xx (some value).
Next modify one of the basic as 0 as follows:
SQL> UPDATE emp_sal
SET basic = 0
WHERE staffno = 1001;
Again run the program and observe the result.
OUTPUT:
ZERO_DIVIDE ERROR: There is zero value in the basic pay, so when an
attempt made to divide a number by zero, the ZERO_DIVIDE exception is raised
automatically and since there was a handler in the exception section, the control
branched there and recorded the error by inserting one row in the message table.

THE EXCEPTION_INIT PRAGMA:


The standard system exceptions, such as ZERO_DIVIDE which are
referenced by name, are no more than the association of a name with the
internal ORACLE error number. There are 100s of these error numbers, and
only the most common dozen have been given names. Any that are not named
will still raise exception flag and transfer control to the EXCEPTION block, but
they will all be caught by OTHERS rather than by name.
You can change this by assigning your own names to other ORACLE error
number. This provides named exceptions in addition to the predefined ones.
EXCEPTION_INIT allow you to do this. Exception is the one word name you
assign to the integer error number. Integer should be negative if the error code
is negative (TRUE for fatal errors) and exception must follow normal object
naming rules.
Note that the syntax of this command requires the word PRAGMA
before EXCEPTION_INIT.
A PRAGMA is not an executable code. It is a compiler directive-an
instruction to the compiler, which can be thought of as a parenthetical remark to
the compiler. PRAGMAS (also called pesudoinstructions are processed at
compile time and not at run time. The predefined PRAGMA EXCEPTION_INIT
tells the PL/SQL compiler to associate an exception name with an ORACLE
error number. That allows you to refer to any internal exception by name and to
write a specific handler for it.

BRBRAITT-JUN-2011

156

Information Technology For JTOs PH-II- IT


SYNTAX;
1.
Declare the name for the exception within the declarative section as
follows:
Exception_name EXCEPTION;
Where exception_name is the name of the exception.
2.
Associate the declared exception with standard ORACLE error number
using PRAGMA EXCEPTION_UNIT Statement in the declarative part of PL/SQL
block, sub-program or package.
PRAGMA EXCEPTION_INIT (exception_name,error-number):
Where exception_name is the name of the previously declared exception.
The PRAGMA must appear somewhere after the exception declaration in the
same declarativepart.
3.
Refer declared exception within the corresponding exception handling
routine.
Example:
The ORACLE error that is UNIQUE or NOT NULL CONSTRAINT
violated can be associated with an exception name empty_name as follows:
DECLARE
/* ORACLE NON PREDEFINED EXCEPTION */
empty_name EXCEPTION;
PRAGMA EXCEPTION_INIT (empty_name, -1400);
BEGIN
INSERT INTO emp_data (staffno,
(&p_staffno, &p_name, &p_deptno);
INSERT INTO emp_sal (staffno)
VALUES (&p_staffno);

emp_name,

deptno)

VALUES

EXCEPTION
WHEN empty_name THEN
INSERT INTO message
Values (Blank Name,
Employees name cannot be blank);

BRBRAITT-JUN-2011

157

Information Technology For JTOs PH-II- IT


END;
/
SELECT * FROM Message;
Similarly, The referential integrity constraint violated which is having code
-2292 & The table or view does not exist, having code 942 can be associated
with an exception name using PRAGMA EXCEPTION_INIT.

CUSTOMISING ERROR CONDITIONS:


You may establish different error conditions within procedural objects. For
each of the error conditions you define, you may select an error message that will
appear
when
the
error
occurs
by
using
built
in
fuction
RAISE_APPLICATION_ERROR to create your own message, which can be
more descriptive than named exceptions. This procedure is defined in the
STANDARD package and may be called from within any procedural object.
The syntax of the RAISE_APPLICATION_ERROR I:
RAISE_APPLICATION_ERROR
[Keep_errors] ;

(error_number,

error_message,

It takes three I/P parameters: the error number (which must be between
-20001 and 20999) and the error message which is the text to be displayed and
keep_errors : a Boolean value which is optional. If keep_errors is true, the new
error is added to the list of already raised (if one exists). If it is false , which is the
default, the new error will replace the current list of errors. You get to assign both
the message number and the text that will be displayed to the user
EXAMPLE:
PROCEDURE paycalc(p_staffno IN emp_data.staffno%TYPE)
IS
Zero_pay EXCEPTION;
BEGIN

EXCEPTION
WHEN TOO_ MANY_ ROWS THEN
RAISE_APPLICATION_ERROR (-20001,
There are more than I records for this staff number : || p_staffno);
WHEN zero_pay THEN
BRBRAITT-JUN-2011

158

Information Technology For JTOs PH-II- IT


RAISE_APPLICATION_ERROR(-20002,
Basic pay zero seems incorrect, It needs updation);
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR(-2003,
There is no record of information for this staff no: || p_staffno);
WHEN OTHERS THEN
RAISE_APPLICATION_ERROR(-2004,
Some other error has occurred);
END paycalc;
In the above program RAISE_APPLICATION_ERROR procedure is called
from each exception handling section to give customized error messages by
setting the error numbers and messages via this procedure. Thus the use of the
RAISE_APPLICATION_ERROR procedure give you great flexibility in managing
the error conditions that may be encountered within your trigger / procedure.
This is a very powerful addition to the standard exceptions that are available in
PL/SQL .

EXCEPTION PROPOGATION:
Exception can occur in the declarative,executable or the exception
section of a PL/SQL block. We have seen what happens when exceptions are
raised in the executable portion of the block, when there is a handler for the
exception. But what, if there is no handler, or the exception is raised from
different section of the block? The process that governs this is known as
exception propogation.
1.

Exception raised in the executable section:

When an exception is raised in the executable section of a block,


PL/SQL uses the following algorithm to determine which exception handler to
invoke.

If the current block has a handler for the exception, execute it and
complete the block successfully. Control then passes to the enclosing
block.
If there is no handler for the current exception, propogate the
exception by raising it in the enclosing block. Step I will then be
executed for the enclosing block.

Before we can examine this algorithm in detail, we need to define an


enclosing block. A block can be embedded inside another block. In this case,
the outer block encloses the inner block.

BRBRAITT-JUN-2011

159

Information Technology For JTOs PH-II- IT


EXAMPLE:
DECLARE
--Begin outer block

BEGIN
--Begin inner block. This is embedded in the outer block.
BEGIN

END;
.
BEGIN
--Begin inner block 2. This is also embedded in the
-- outer block.
--Note that this block does not
-- have a declarative part

END;
.
..
--End out block
END;
In the preceding listing, inner blocks 1 and 2 are both enclosed by the
outer block. Any unhandled exceptions in block 1 and block 2 will be propogated
to the outer block.
A procedure call will also create an enclosing block, and is
illustrated in the following example:
BEGIN
--Begin outer block.
--call a procedure. The procedure will be enclosed by the
--outer block.
F()
END;
If procedure function raises an unhandled exception, it will be
propogated to the outer block, since it encloses the procedure.

TRIGGERS
BRBRAITT-JUN-2011

160

Information Technology For JTOs PH-II- IT

INTRODUCTION
Like procedures, functions and packages. Triggers are named PL/SQL
blocks with declarative, executable and exception handling sections. Like
packages, Triggers must be stored in the database and cannot be local to a block
. However a procedure is executed explicitly from another block which can pass
arguments. But a trigger is executed implicitly, whenever the triggering event
happens and a trigger does not accept arguments. The act of executing a
trigger is known as firing the trigger. The triggering event is a DML (INSERT,
UPDATE, DELETE) operation on a database table.

APPLICATION OF TRIGGERS
Triggers can be used for many things, including

Maintaining complex integrity constraints not possible through declarative


constraints enabled at table creation.
Auditing information in a table by recording the changes made and who
made them.
Automatically signaling other programs that action needs to takes place,
when changes are made to a table.

CREATING TRIGGERS
SYNTAX
The general syntax for creating a trigger is:
CREATE [OR REPLACE] TRIGGER trigger _name
[BEFORE | AFTER ] triggering event ON table_reference [For EACH
ROW ]
[ WHEN trigger_condition ]
trigger_body;
where
trigger_name -the name of the trigger
triggering-event The event or time when the trigger fires.
Table_reference

BRBRAITT-JUN-2011

The table for which the trigger is defined

161

Information Technology For JTOs PH-II- IT


Trigger_body

Main code for the trigger

Trigger_condition The body of the trigger is executed only when the


condition evaluates to TRUE.
EXAMPLE
As an example, suppose we want to track statistics about different
category of subscribers, exchange wise. We want to
store these results in exg_stats table. The following script will create the table
exg_stats.

CREATE TABLE exg_stats


(exg_code CHAR (5),
cat_code NUMBER(2);
no_of_subs NUMBER (5));
In order to keep the table exg_stats up-to-date, We can create a trigger on
the table master_data that will update table exg_stats every time the table master
_data is modified. The update_ES TRIGGER shown next does this. After any
DML operation on the tableMaster_data the trigger update_ES will execute. The
body of the trigger queries the table master_data and updates the table
exg_stats with the current statistics.
CREATE OR REPLACE TRIGGER update_ES
/* Keeps the major_stats table up-to-date with the changes made to the table
master_data*/
AFTER INSERT OR DELETE OR UPDATE ON master_data
DECLARE
CURSOR c_stats IS
SELECT exg_code,cat_code, count (*), no_of_subs
FROM master_data
GROUP BY exg_code,cat_code;

BRBRAITT-JUN-2011

162

Information Technology For JTOs PH-II- IT


BEGIN
/*Loop through each record of the table exg_stats. Attempt to update the
statistics. If the row does not exit, create it */
FOR v_statsRecord IN C_stats LOOP
UPDATE exg_stats
SET no_of_subs = v_statsRecord.no_subs
WHERE exg_code = v_statsRecord.exg_code
AND Cat_code = v_statsRecord.cat_code;

/*Check to see if the row exists*/


IF SQL%NOTFOUND THEN
INSERT INTO exg_stats (exg_code,cat_code,no_of_subs)
VALUES
Record.cat_code,v_statsRecord.no_subs);

(v_statsRecord.exg_code,v_stats

END IF;
END LOOP;
END update_ES;
TRIGGER COMPONENTS
1.Trigger name
2.Triggering event
3.The body
4.When clause -optional.

BRBRAITT-JUN-2011

163

Information Technology For JTOs PH-II- IT

Trigger Name
Namespace: A namespace is the set of legal identifiers available for use
as the names of an object. Within one database shema ,all objects in the same
namespace must have unique name. Procedures, Packages and Tables all share
the same namespace. Hence it is illegal to give the same name to a procedure
and a table.
The namespace for triggers is different from that of the above objects (i.e.,
procedure, package and table). This means that a trigger can have same name
as a table or a procedure.
Trigger names are database identifiers and as such follows the same rules
as other identifiers.
Although it is possible to use the same name for a trigger and a table. It is
better to give each trigger a unique name that identifies its function as well as the
table at which it is defined.

Triggering event
The triggering event determines the type of the triggers.
Triggers can be defined for INSERT, UPDATE or DELETE operation.
Triggers can be fired BEFORE or AFTER the operation.
They can also be fired ROW or STATEMENT level
TABLE I
Category

Values
INSERT

Statement
DELETE

Comments
Defines which kind of DML statement
causes the trigger to fire.

UPDATE
BEFORE
Timing
AFTER
ROW
Level

Defines whether the trigger fires before or


after the statement is executed.
Fires once for each row affected by the
triggering Statement.

STATEMENT
Fires only once either before or after the
BRBRAITT-JUN-2011

164

Information Technology For JTOs PH-II- IT

statement.
TABLE 2
Timing

Statement

Level

BEFORE

INSERT
UPDATE
DELETE

ROW

AFTER

STATEMENT

The values for the timing, statement and level determine the type of the trigger.
From the table 2 it can be observed that there are total of possible 12 types.
2 timings x 3 statement x 2 levels = 12 types
For example all the following are valid trigger types.

BEFORE UPDATE ROW level


AFTER INSERT STATEMENT level
BEFORE DELETE ROW level
AFTER UPDATE STATEMENT level.

A table can have upto 12 triggers defined on it-one of each type. A table
can have more than one trigger of each type.
This means that a table can have any number of triggers.
The order in which the triggers are fired is explained later in this chapter.
A trigger can also be fired for more than one type of triggering statement.
For example, the update_ES Trigger is fired on INSERT, UPDATE and DELETE
statements.

The body of the Trigger


The body of a trigger is a PL/SQL Block. Any statement that is legal in a PL/SQL
block is legal in a trigger body subject to the following restrictions.

A Trigger may not issue any transactional control statements (COMMIT,


ROLLBACK,SAVEPOINT). When the triggering statement is committed or
rolledback the work in the trigger is committed or rolled back as well.
Any procedures or functions that are called by the trigger body cannot
issue any transaction control statements.
The trigger body cannot declare any LONG or LONG RAW variables.

BRBRAITT-JUN-2011

165

Information Technology For JTOs PH-II- IT

:new and :old (explained latter) cannot refer to a LONG or LONG RAW
column in the table for which the trigger is defined.

ORDER OF TRIGGER FIRING


Triggers are fired as the DMLstatement is executed. The algorithm or the
order at which different types of triggers are fired and the DML statement is
executed are given below.
1.Execute the BEFORE statement level trigger, if present.
2.For each row affected by the statement.
i.
Execute the BEFORE row-level trigger, if present.
ii.
Execute the statement itself.
iii.
Execute the AFTER row-level Trigger, if present.
3.Execute the AFTER statement-level Trigger, if present
To illustrate, suppose we create all four kinds of update triggers on the
Staff table. Before after statement and Row level as follows.
Example
/* ******* To create otf_table******** */
CREATE TABLE otf_table
(ord_no NUMBER (5),
tgr_type CHAR(25));
/* ******* To create the sequence tgr_seq ******* */
CREATE SEQUENCE tgr-seq
START WITH 1
INCREMENT BY 1;
/* ***** before statement trigger ****** */
CREATE OR REPLACE TRIGGER staff_Bstatement
BEFORE UPDATE ON staff
BEGIN
Insert into otf_table (ord_no,tgr_type)
VALUES (tgr_seq.NEXTVAL,
before Statement trigger );
END staff_Bstatement;
/* ***** After Statement Trigger****** */
CREATE OR REPLACE TRIGGER Staff_Astatement
AFTER UPDATE ON staff

BRBRAITT-JUN-2011

166

Information Technology For JTOs PH-II- IT


BEGIN
INSERT INTO otf_table (ord_no,tgr_type)
VALUES (tgr_seq.NEXTVAL, After Statement Trigger );
Staff_Astatement;

END

/* ***** Before Row Trigger ******* */


CREATE OR REPLACE TRIGGER STAFF_Brow
BEFORE UPDATE ON staff
FOR EACH ROW
BEGIN
INSERT INTO otf_ table (ord_no,tgr_type)
VALUES (tgr_seq.NEXTVAL , Before Row Trigger);
END staff _Brow;
/* ***** After Row Trigger ***** */
CREATE OR REPLACE TRIGGER staff_Arow
AFTER UPDATE ON staff
FOR EACH ROW
BEGIN
INSERT INTO otf_table (ord_no,tgr_type)
VALUES (tgr_seq.NEXTVAL, After Row Trigger);
END staff_Arow;
/* To test the otf_trigger*/
UPDATE staff
SET Salary = 10000
WHERE desgn = AO;
As each trigger is fired, it will see the changes made by earlier triggers
as well as any data base changes made by earlier triggers as well as any
database changes made by the statement so far.

USING :OLD AND :NEW IN ROW LEVEL TRIGGERS


A row level trigger fire once per row processed by the triggering
statement. Inside the trigger, the row that is currently being processed can be
accessed, by using two pseudo records. :old and :new. Although syntactically
they are treated as records, in reality they are not records. Hence they can be
known as pseudo-records. The type of :old and :new is:
Triggering_table%ROWTYPE;
Where triggering_table is the table for which the trigger is defined.
The colon in front of new and old is required since they are
implemented as bind variables. The colon delimits them from regular PL/SQL

BRBRAITT-JUN-2011

167

Information Technology For JTOs PH-II- IT


variables. A reference such as :new.field will be valid, only if field, is a field in
the triggering table.

BRBRAITT-JUN-2011

168

Information Technology For JTOs PH-II- IT

Triggering
Statement
INSERT
UPDATE
DELETE

:Old

:new

Undefined-All fields
Are NULL

Values that will be inserted


when the statement is
complete.
Original values for the row New values that will be
before the update.
updated when the statement
is complete.
Original values before the Undefined All fields are
row is deleted
Null.
TABLE-3

The Table-3 shows the value of :new and :old with reference to each
statement. In reality, :new and :old are not records. As a result, operations that
would normally be valid on records are not valid for :new and :old . For example,
i.
They cannot be assigned as entire record. Only the individual fields within
them may be assigned.
ii.
:old and :new cannot be passed to procedures or functions that take
arguments of triggering_table%ROW TYPE.
The Generate_EmpId trigger shown next uses :new. It is a BEFORE
INSERT OR UPDATE Trigger and its purpose is to fill in the ID field of staff with a
value generated from the emd_id__seq sequence.
Example:
The trigger Generate_EmpId actually modifies the value of :new.emp_id.
When the statement is actually executed, whatever values in :new will be used.
With Generate_EmpId, we can issue an INSERTstatement such as:
INSERT INTO STAFF (emp_name, desgn)
VALUES JOSE, AO);
Without generating an error. Even though we have not specified a value
for the primary key column emp_id (which is required), the trigger will supply it.
Infact, even if we do specify a value for emp_id, it will be ignored, since the
trigger changes it.
If we issue
INSERT INTO staff (emp_id,emp_name,desgn)

BRBRAITT-JUN-2011

169

Information Technology For JTOs PH-II- IT


VALUES (51,JOSE, AO);
We get the same behaviour. In either case, emp_id_seq.NEXTVAL will be used
for emp_id column.
This shows that, you cannot change :new in an AFTER ROW LEVEL trigger,
since the statement had already been processed.
Note:

In general, :new is modified only in a before row level trigger and :Old is
never modified, only read from.
The :new and :old records are only valid inside a ROW LEVEL triggers.
You will get a compile error, if you try to reference inside a STATEMENT
LEVEL trigger.

THE WHEN CLAUSE


The WHEN clause is valid for row level triggers only. If present, the trigger
body will be executed only for those rows that meet the condition specified by the
WHEN clause. The WHEN clause looks like:
WHEN condition
Where condition is a Boolean expression. It will be evaluated for each
row. The :new and :old records can be referenced inside conditions as well, but
the colon is not used there. The colon is only valid in the trigger body. For
example, the body of the check_salary trigger is only executed if the salary of an
employee is more than 10000.
CREATE OR REPLACE TRIGGER Check _salary
BEFORE INSERT OR UPDATE OF salary ON employee
FOR EACH ROW
WHEN ( :new.salary > 10000)
BEGIN
/* Trigger body goes here. */
END;
Check _Salary could also be written as follows:
CREATE OR REPLACE TRIGGER check_salary
BEFORE INSERT OR UPDATE OF salary ON students
FOR EACH ROW
BEGIN
IF :new.salary > 10000 THEN
/* Trigger body goes here */
END IF;
END;
BRBRAITT-JUN-2011

170

Information Technology For JTOs PH-II- IT

USING TRIGGER PREDICATES:


INSERTING, UPDATING AND DELETING
The update_trigger earlier in this chapter is an INSERT, UPDATE and a
DELETE TRIGGE. Inside a trigger of this type (that will fire for different kinds of
DML statements), there are three Boolean functions that you can use to
determine what the operation is. These predicates are INSERTING, UPDATING
and DELETING. Their behaviour is described in the following table.
Predicate
INSERTING
UPDATING
DELETING

Behavior
TRUE, if the triggering statement is an
INSERT;FALSE otherwise.
TRUE if the triggering statement is an
UPDATE;FALSE otherwise.
TRUE if the triggering statement is a
DELETE;FALSE otherwise.

The Log_Staff_changes trigger uses these predicates to record all


changes made to the staff table. In addition to the change, it records the user,
who makes the change. The records are kept in the staff_audit table, which look
like:
/* To create table staff_audit */
CREATE TABLE staff_audit
(old_emp_id NUMBER(2),
old_emp_name CHAR(20),
old_desgn NUMBER(5),
old_co_id CHAR(2),
old_salary NUMBER(6),
new_emp_id NUMBER(2),
new_emp_name CHAR(20),
new_desgn NUMBER(5),
new_co_id CHAR(2),
new_salary NUMBER(6),
change_type CHAR(1),
changed_by VARCHAR2(8),
Timestamp DATE);
/* To create Log _Staff _changes trigger */
CREATE OR REPLACE TRIGGER log_staff_changes
BEFORE INSERT OR DELETE OR UPDATE ON Staff
BRBRAITT-JUN-2011

171

Information Technology For JTOs PH-II- IT


FOR EACH ROW
Declare
V_change TYPE CHAR(1);
BEGIN
/*Use I for an INSERT, D FOR delete, and U for UPDATE */
IF INSERTING THEN
v _change_type := I;
ELSIF
UPDATING then
V_change_type := U;
ELSE
V_change_type := D;
END IF;
/* Record all the changes made to staff table in staff_audit table. Use SYSDATE
to generate the timestamp, and USER to return the user_ id of the current user. */
INSERT INTO staff_audit
VALUES
(change_type,changed_by,timestamp,old_emp_id,
old_emp_name,Old_desgn,old_co_id,
old_salary,
new_emp_id,
new_emp_name,new_desgn, new_co_id, new_salary);
END Log_Staff_Changes;
Triggers are commonly used for auditing, as log_ Staff_ changes. Oracle
provides auditing as part of the database, but triggers allow for more flexible
auditing. Log_ Staff_changes could be modified, for example, to record changes
made by certain people only . It could also check to see, if users have
permission
to
make
changes
and
raise
an
error
(with
RAISE_APPLICATION_ERROR ) , if they dont have.

BRBRAITT-JUN-2011

172

Information Technology For JTOs PH-II- IT

Cursor
What is a Cursor ?
A cursor is a private SQL area
Every SQL statement executed by the oracle server has
an individual cursor associated with it.
Two Types of cursor:
-Implicit cursors: Declared for all DML and
PL/SQL SELECT statements.
-Explicit cursors: Declared and named by the
programmer.
The Oracle Serve uses work areas called Private SQL areas to execute
SQL statements and store processing information. PL/SQL cursors let you name
a private SQL area and access its stored information. The cursor directs all
phases of processing.
Cursor Description
Type
Implicit Declared by PL/SQL implicitly for all DML
and PL/SQL SELECT statements.
Explicit Declared and named by the programmer
and
manipulated
through
specific
statements within the blocks executable
actions.

Recall that the SELECT statement in PL/SQL must only return a single
row. PL/SQL actually attempts to fetch two rows from an implicit cursor:
one to satisfy the query and a second to see if further rows were
returned. One method to eliminate this extra fetch is to use an explicit
cursor.

Explicit Cursor Functions

Can process beyond the first row returned by the query, row by row.
Keep track of which row is currently being processed.
Allow the programmer to manually control them in the PL/SQL block.

BRBRAITT-JUN-2011

173

Information Technology For JTOs PH-II- IT

Controlling Explicit Cursors


Now that you have a conceptual understanding of cursors, review the
steps to use them. The syntax for each step follows :
Controlling Explicit Cursors Using Four Commands
1. Declare the cursor.
Declare the cursor by naming it and defining the structure of
the query to be performed within it.
2. Open the cursor.
The OPEN statement executes the query and binds any
variable that are referenced. Rows identified by the query are
called the ACTIVE SET and are now available for fetching.
3. Fetch data from the cursor.
The FETCH statement loads the current row from the cursor into
variables. Each fetch causes the cursor to move its pointer to the next row in the
active set. Therefore, each fetch will access a different row returned by the query.
4.Close the cursor.
The CLOSE statement releases the active set of rows. It is now possible
to reopen the cursor to establish a fresh active set.
Controlling Explicit Cursors
no
DECLARE
EMPTY??
(1)

1.
2.
3.
4.
5.

FETC
H

OPEN

(2)

(3)

empty
(4)

CLOSE

yes
(5)

create a named SQLarea


Identify the active set
Load the current row into variables
Test for existing rows: return to FETCH if no rows found
Release the active set

BRBRAITT-JUN-2011

174

Information Technology For JTOs PH-II- IT

Declaring the Cursor


Use the CURSOR statement to declare an explicit cursor. You can define
parameter to allow substitution of values into the query when the cursor is
opened. You can also reference variables within the query, but you must declare
them before the cursor statement.
Syntax:
DECLARE
CURSOR cursor_name IS
Select_statement;

Where:
Cursor_name

is a PL/SQL identifier.

Select_statement

is a SELECT
clause.

statement without an INTO

Note: Do not include the INTO clause within the cursor declaration because it
appears later within the FETCH statement.

Opening the Cursor


Open the cursor to execute the query and identify the active set, after
specifying values for all input variables. The cursor will now point to the first row
in the active set.
Syntax
OPEN cursor_name;
Where Cursor_name

is the name of the previously-declared

cursor.

Note: If the query returns no rows when the cursor is opened, PL/SQL does not
raise an exception. However, you can test the cursor_ status after a fetch.
Opening the Cursor : Syntax

Open the cursor to execute the query and identify the active set.
OPEN cursor_name;

BRBRAITT-JUN-2011

175

Information Technology For JTOs PH-II- IT

If the query returns no rows, no exception is raised.


Test the outcome after a fetch by using cursor attributes.

Fetching Data from the Cursor


Use the FETCH statement to retrieve the current row values into output
variables. After the fetch, you can manipulate the variables by further
statements.
Syntax
FETCH cursor_name INTO variablel, variable2 .. . . . ;

Where:
cursor-name
Variable

is the name of the previously declared cursor.


is an output variable to store the results.

Guidelines:

Include the same number of variables within the INTO clause of the
FETCH statement as output columns in the SELECT statement and
be sure that the data types are compatible.
Match each variable to correspond to the columns positionally.
Alternatively, define a record for the cursor and reference the record in
the FETCH INTO clause.
Test to see if the cursor contain rows. If a fetch acquires no values,
that is there are now rows left to process in the active set and no error
is recorded.
Fetching Data from the Cursor: Syntax:
Retrieving the current row values into output variables.
FETCH
cursor_name
INTO
variable1, variable2;
Include the same number of variables.
Match each variable to correspond to the columns
positionally.
Test to see if the cursor contains rows.

BRBRAITT-JUN-2011

176

Information Technology For JTOs PH-II- IT


Fetching Data from the Cursor: Example
Retrieve the line items of an order, one-by-one
FETCH item_cursor
INTO v_product_id, v_item_total;

Closing the Cursor


Close the cursor after completing the processing of the SELECT
statement. This step allows the cursor to be reopened. Therefore, you can
establish an active set several times.
Syntax{
CLOSE cursor_name;
Where:
cursor-name

is the name of the previously declared

cursor.

Note: Do not attempt to fetch data from a cursor once it has been closed
or the INVALID_CURSOR exception will be raised.
Closing the Cursor: Syntax

Close the cursor after completing the


processing of the rows.
CLOSE cursor_name;
Reopen the cursor, again, if required
Do not attempt to fetch data from a cursor
,once it has been closed.

Explicit Cursor Attributes


As with implicit cursors, there are four attributes for obtaining status
information about a cursor. When used, the attribute name is preceded by the
cursor identifier.
Cursor Attribute

BRBRAITT-JUN-2011

Description

177

Information Technology For JTOs PH-II- IT


%ISOPEN

Boolean attribute that evaluates to TRUE if the cursor


is open.

%Notfound

Boolean attribute that evaluates to TRUE if the most


recent fetch does not return a row.

%FOUND

Boolean attribute that evaluates to TRUE until the most


recent fetch does not return a row, complement of
%NOTFOUND.

%ROWCOUNT

Numeric attribute that evaluates to the total number of


rows returned so far.

Note: Do not reference cursor attributes directly within a SQL statement

Controlling Multiple Fetches from Explicit Cursors


Typically, when you want to process several rows from an explicit cursor,
you define a loop to perform a fetch on each literation. Eventually, all rows in the
active set will be processed, and an unsuccessful fetch sets the %NOTFOUND
attribute to TRUE . Use the explicit cursor attributes to test success of each fetch
before any further references are made to the cursor. If you omit an exist criteria,
an infinite loop will result.
Controlling Multiple Fetches
Process several rows from an explicit cursor using a loop.
Fetch a row with each iteration.
Write a test for an unsuccessful fetch by using the %NOTFOUND
attribute.
Test success of each fetch using explicit cursor attributes.

You can only fetch rows when the cursor is open. Determine whether the
cursor is open using the %ISOPEN cursor attribute, if necessary.

Fetch rows in a loop. Determine when to exit the loop by using cursor
attributes.

To retrieve an exact number of rows, fetch the rows in a numeric FOR


loop, or fetch the rows in a simple loop and determine when to exist the
loop by using the %ROWCOUNT cursor attribute.
Example:

BRBRAITT-JUN-2011

178

Information Technology For JTOs PH-II- IT

Retrieve the first five line items for an order one by one.
cumulative total for each product to the screen.

Print the

PROCEDURE ord_process
V_ord_id IN s_item.ord_id%TYPE;
IS
V_product_id s_item.product_id%TYPE;
V_item_total NUMBER (11,2);
V_order_total NUMBER (11,2) :=0;
CURSOR item_cursor IS
SELECT product_id, price * quantity
FROM
s_item
WHERE ord_id = v_ord_id;
BEGIN
OPEN item_cursor;
LOOP
FETCH item_cursor INTO v_product_id ,
V_item_total;
EXIT WHEN item_cursor%ROWCOUNT > 5
OR item_cursor%NOTFOUND;
V_order_total := v_order_total + v_item_total;
TEXT_IO.PUT_LINE ( Product ID ||
TO_CHAR (v_product_id) ||
has a total of ||
TO CHAR(v_order_total , $999,999,999.99));
END LOOP;
CLOSE item_cursor;
COMMIT;
END ord_process;

Note: If using %ROWCOUNT, add a test for no rows in the cursor by using
the %NOTFOUND attribute because the row count is not incremented if
the fetch does not retrieve any rows.

BRBRAITT-JUN-2011

179

Information Technology For JTOs PH-II- IT


The %ISOPEN Attribute: Example
Fetch rows only when the cursor is open.
Test if the cursor is open using %ISOPEN cursor attribute before
performing a fetch.
IF item_cursor %ISOPEN THEN
FETCH item-cursor INTO v_quantity, v_price,
ELSE
OPEN item-cursor;
END IF;

The %NOTFOUND and


%ROWCOUNT Attributes; Example
Retrieve an exact number of rows using the %ROWCOUNT cursor
attribute.
Determine when to exist the loop using the %NOTFOUND cursor
attribute.

LOOP
FETCH item_cursor
INTO v_product_id, v_item_total;
EXIT WHEN item_cursor%ROWCOUNT > 5
OR item_cursor%NOTFOUND;
V_order_total := v_order_total + v_item_total;
.
END LOOP;

BRBRAITT-JUN-2011

180

Information Technology For JTOs PH-II- IT

Cursors and Records


We have already seen that you can define records to use the structure of
columns in a table. You can also define a record based on the selected list of
columns in an explicit cursor. This is convenient for processing the rows of the
active set since you can simply fetch into the record. Therefore, the values of the
row are loaded directly into the corresponding fields of the record.
In the example, you can select the ROWID pseudo_column, and it will
have a corresponding field within the EMP_RECORD PL/SQL record.
Cursors and Records: Example
Process the rows of the active set conveniently
by fetching values into the PL/SQL RECORD.
Cursor EMP_CURSOR is
SELECT id, salary, start_date, rowid
FROM s_emp
WHERE dept_id = 41 ;
Emp_record emp_cursor%ROWTYPE;
BEGIN
OPEN emp_cursor;
...
FETCH emp_cursor INTO emp_record;

Cursor FOR Loops


A cursor FOR loop processes rows in an explicit cursor. It is a shortcut in
because the cursor is opened, rows are fetched once for each iteration in the
loop, and the cursor is closed automatically when all rows have been processed.
The loop itself is terminated automatically at the end of the iteration where the
last row was fetched.
Syntax
FOR record_name IN cursor_name LOOP
Statement1;
Statement2;
..
END LOOP;

BRBRAITT-JUN-2011

181

Information Technology For JTOs PH-II- IT


Where;
record-name

is the name of the implicitly-declared record.

Cursor-name

is a PL/SQL identifier for the previously-declared cursor.

Guidelines

Do not declare the record that controls the loop. Its scope is only in the
loop.
Test the cursor attributes during the loop, if required.
Supply the parameters for a cursor, if required, in parentheses following
the cursor name in the FOR statement.
Do not use a cursor FOR loop when the cursor operations have to be
handled manually.

Shortcut to process explicit cursors.


Implicit open, fetch, and close occur.

FOR record_name IN cursor_name


LOOP
Statement1;
Statement2;
...
END LOOP;

Do not declare the record; it is implicitly declared.

BRBRAITT-JUN-2011

182

Information Technology For JTOs PH-II- IT


Cursor FOR Loops: Example
Retrieve line items for an order one by one ,until there are no
more line items left.
FOR item_record IN item_cursor LOOP
- -Implicit open and implicit fetch - occur
v_order_total : =v_order_total +
(
item_record.price
*
item_record.quantity);
i := i + 1;
product_id_table
(
l
)
:=
item_record.product_id;
order_total_table ( i ) :=v-order-total;
END LOOP;
- -implicit close occurs.
Summary
Cursor Types

Implicit cursors are used for all DML statements and single row queries.
Explicit cursors are used for queries of zero, one, or more rows.

Explicit Cursor Commands

Declare the cursor.


Open the cursor.
Fetch data from the cursor.
Close the cursor.

Cursor Attributes
Evaluates the status of the cursor by using cursor attributes.
Cursors with Parameters
Use parameter to open an explicit cursor several times in a block, returning a
different active set on each occasion.
Cursor FOR Loops
Use cursor FOR loops as a shortcut to open the cursor, fetch rows once for each
loops iteration, and automatically close the cursor after all rows are processed.
BRBRAITT-JUN-2011

183

Information Technology For JTOs PH-II- IT

CHAPTER 9
STORED PROCEDURES, FUNCTIONS & PACKAGES
SUBPROGRAM
Program units are named PL/SQL blocks.
categories.

They fall into three main

Procedures to perform actions


Functions to compute a value
Packages to bundle logically related procedures and functions

Stored or Application Subprogram ?


These program units can be created in a variety of environments,
including server-side stored subprograms or as application subprograms.
Concept
Location
Executed
Availability

Stored Subprogram
Application Subprogram
Is in the database
Is within the application.
From any database tool From
only
the
or application
application in which it
was created.
By way of database Independently of, and in
security.
addition
to,
stored
subprograms.

Subprograms are composed of a number of sections.

A header to name and type the block


An optional declarative section to set up local identifiers
An executable part to perform the actions
An optional exception handling section to handle exceptions.

What Are PL/SQL Program Units ?


Named PL/SQL blocks
Three main categories:
- Procedures to perform actions
- Functions to compute a value
- packages to bundle logically related procedures and functions.
Stored in the database or developed as an application
subprogram.

BRBRAITT-JUN-2011

184

Information Technology For JTOs PH-II- IT

Subprogram Components
HEADER -Mandatory
-subprogram
name,type,and
arguments
DECLARATIVE -Optional
- -Local identifiers
EXECUTABLE -Mandatory
- -SQL Statements
- -PL/SQL control statements
EXCEPTION HANDLING-Optional
- -Actions to perform when errors
occur
END; - Mandatory

Creating a Subprogram

Select environment

Compile code
Create Subprogram
Invoke

BRBRAITT-JUN-2011

185

Information Technology For JTOs PH-II- IT

The following steps will assist you to create a subprogram.


1.

Select your environment.

If using Procedure Builder, then select either the Program Units node or
the Database Objects node and Stored Procedures Units subobject node.
2.

Write your syntax.

If using Procedure Builder, enter the syntax in the Program Unit Editor. If
using SQL*Plus, write your code in a text editor as a script file.
3.

Compile your code.

The source code is compiled into p-code. If using Procedure Builder, click
the Compile button. If using SQL*Plus, start your file at the SQL prompt.
4.

Invoke the successfully compiled procedure or function.

Guidelines

SQL*Plus is another development environment for writing and for


initial testing of a procedure, although you will need to test the
procedure by invoking it from an application.
The SQL commands issued to create a stored subprogram are
CREATE PROCEDURE or CREATE FUNCTION.
The SQL commands issued to remove a stored subprogram are
DROP PROCEDURE or DROP FUNCTION.
Use CREATE OR REPLACE PROCEDURE or CREATE OR
REPLACE FUNCTION ,so you do not have to issue a DROP
statement.

STORED PROCEDURES
Create a PL/SQL procedure to store a series of actions for later
execution. The procedure can contain zero or more parameters, which
are arguments that you list when calling the procedure.

BRBRAITT-JUN-2011

186

Information Technology For JTOs PH-II- IT


Creating a Procedure Syntax:
PROCEDURE name
[ (parameter1, para2, ) ]
IS
Pl/sql-block;

Where:
Name
Parameter
PL/SQL_BLOCK

is the procedure name, which adheres to the standard


Oracle naming rules.
is the parameter syntax shown below.
- is the procedural body that defines the action
by the procedure.

performed

The parameter syntax is as follows:


Syntax
Parameter_name [ IN | OUT | IN OUT ] datatype
[ { := | DEFAULT } expr ]
Where:
Parameter_name - is the name of the parameter.
Datatype
- is the data type of the parameter, without constraints.
Expr
- is the value to initialize the parameter.
Guidelines

Start the PL/SQL block with the keyword IS .


Enter any local declaration between IS and BEGIN
Do not specify a constraint on the data type.

When creating the procedure from procedure Builder, the CREATE OR


REPLACE portion of the syntax is implied. Therefore, when creating
the procedure from SQL*Plus , begin the statement with CREATE OR
REPLACE.

BRBRAITT-JUN-2011

187

Information Technology For JTOs PH-II- IT

Creating a Procedure: Guidelines

Use the CREATE OR REPLACE clause when building


your procedure in SQL*Plus
Enter any parameters.
Start the PL/SQL BLOCK WITH IS
Enter a local variable declaration or the keyword BEGIN
after IS.

Procedural Parameters
Transfer values to and from the calling environment through parameters.
There are two types that you use.

When declaring a procedure, the formal

parameter is used to define the values used in the executable portion of the
PL/SQL block. The actual parameter, or argument, is referenced when invoking a
subprogram.
Parameter Modes for Formal Parameters
Parameter
Mode
IN

OUT

IN OUT

Description
Default argument.
Passes a value from the calling environment into the
subprogram.
Formal parameter acts as a constant -you cannot overwrite
the value.
Actual parameter can be an expression, a constant, a literal,
or an initialized variable.
Must be specified.
Returns a value from the procedure to the calling
environment.
Formal parameter acts as an uninitialized variable.
Formal parameter cannot be assigned to another variable or
to itself.
Actual parameter must be a variable ; it cannot be a
constant or expression.
Must be specified.
Passes a value from the calling environment into the
procedure, and returns a possibly different value from the

BRBRAITT-JUN-2011

188

Information Technology For JTOs PH-II- IT


procedure to the calling environment.
Formal parameter acts as an initialized variable.
Formal parameter can be used as a normal variable, it can
be assigned to a value.
Actual parameter must be a variable.
Creating a Procedure :Example
PROCEDURE change_salary
(v_emp_id IN NUMBER,
v_new_salary IN NUMBER)
IS
BEGIN
UPDATE s_emp
SET Salary = v_newsalary
WHERE id = v_emp_id;
COMMIT;
END change_salary;

Parameter Modes for Formal Parameters


IN
OUT
IN OUT
Default
Must be specified
Must be specified.
Value is passed into sub Returned
to
calling Passed into subprogram:
Program.
environment
Returned
to
calling
environment.
Formal parameter act as An initialized variable.
An initialized variable.
a constant.
Actual parameter can be Must be a variable.
Must be a variable.
a
literal,
expression,constant or
Initialized variable.

Example:
Update the salary of the specified employee to the specified amount through a
procedure.

BRBRAITT-JUN-2011

189

Information Technology For JTOs PH-II- IT

PROCEDURE change_salary
(v_emp_id IN NUMBER,
v_new_salary IN NUMBER)
- - formal parameters
IS
BEGIN - begin PL/SQL block
UPDATE s_emp
SET
salary = v_new_salary
WHERE id = v_emp_id;
COMMIT;
END change_salary;
This procedure, when invoked, will take the parameters for the employee
number and the new salary, and update the salary for that specified employee.

Eliminate Unnecessary IN Arguments

Where possible, derive values in the procedure, or use default values.


Generate the primary key using a database sequence.
Record the username from the USER function.
Record the current date from the SYDATE FUNCTION.
Take advantage of business rules to compute input values automatically
using a formula.

FUNCTION
Create a PL/SQL function to return a value to the calling environment.
You must declare the RETURN data type in the header section of the function
definition, and define the value to be returned in the PL/SQL block. You can also
declare a list of parameters to be passed into the function.
Create function Syntax:
FUNCTION name
[ (Parameter1, para2, ...) ]
RETURN datatype
IS
Pl/sql_block;
Where:
Name
Parameter
Data type

is the function name, which adheres to the standard Oracle


naming rules.
is the parameter syntax similar to procedure
is the data type of the value to be returned.

BRBRAITT-JUN-2011

190

Information Technology For JTOs PH-II- IT


Pl/sql_block

is the procedural body that defines the action


Performed by the procedure.

The RETURN statement


Remember to include a RETURN statement in the PL/SQL block. The
function must set the value of the return parameter and be of the same data type
specified in the RETURN clause of the function definition. Multiple RETURN
statements are allowed, but only one will be executed by any one call. Typically,
the multiple RETURN statements are within an IF statement.
When creating the function from Procedure Builder, the CREATE
OR REPLACE portion of the syntax is implied. Therefore, when
creating the function from SQL*Plus, Begin the statement with
CREATE OR REPLACE.
Creating a Function

Create a PL/SQL function to return a value to the calling


environment.
Add a RETURN clause with the data type in the declaration of
the function.
Include at least one return statement in the PL/SQL block.

Creating a Function: Syntax


FUNCTION name
[ (parameter1, par2, ..) ]
RETURN data type
IS
Pl/sql-block;

Example: Return the tax based on the value parameter in a function


FUNCTION tax
(v_value IN NUMBER)
RETURN NUMBER
IS
BEGIN
RETURN (v_value * .07);
END tax;

BRBRAITT-JUN-2011

191

Information Technology For JTOs PH-II- IT

Avoid using the OUT and IN OUT modes with FUNCTIONS.


Functions are designed to return a single value.

PACKAGES
INTRODUCTION
Packages are PL/SQL objects that group
other object such as
procedures, functions, types, variables, SQL Cursors and Exceptions as a single
unit with less restriction with respect to dependencies. This is another ADA
feature incorporated in PL/SQL . Packages also provide global variables for
PL/SQL. So packages allow multiple procedures to use the same Variables and
cursors. Procedures within packages may be available to the public in which
case they are accessible to the users of the package or they may be private, in
which case they are only accessible via commands from within the package such
as call from other procedures.
Each package has two parts: The specification and the body. Each of
them stored separately in the data dictionary. The package specification is also
known as the package header. It contains information about the objects you can
access when you use the package. However it does not contain the code for any
procedure.
CREATING PACKAGE
When creating package, the package Specification and the package body
are created separately. Thus there are two commands to use (1) CREATE
PACKAGE for package Specification, and (2)CREATE PACKAGE BODY for the
package body. Both of these commands require that you have the CREATE
PROCEDURE System Privilege. If the package is to be created in a schema
other than your own, then you must have the CREATE ANY PROCEDURE
System privilege.
The Syntax for creating package specification is:
CREATE [ or REPLACE ] package [user.] package_name
{ IS/AS }
procedure_specification |
function_specification |
variable_declaration |
exception_declaration |
cursor_declaration
type_definition
END [package_name];

Where package-name is the name of the package

BRBRAITT-JUN-2011

192

Information Technology For JTOs PH-II- IT


A Package specification consists of the elements of the program such as
functions, procedures, variables, constants, cursors and exceptions which are
the same as they would be in the declarative section of an anonymous block.
The same rules apply for a package header as for a declarative section, except
for procedure & function declarations.
The rules are as follows:

Package elements can appear in any order. However as in a


declarative section, an object must be declared before it is being
referenced; if a cursor contains a variable as part of the where
clause, it must be declared before cursor declaration.
All types of elements do not have to be present. A package
contains only procedure & function specification, for example,
without declaring any exceptions or types.
Any declarations for procedures or functions must be forward
declaration. This is different from the declarative section of a block,
where both forward declaration and actual code for procedures or
functions may be found. The code which implements the packages
procedures or functions is found in the package body.

Example:
CREATE PACKAGE salary_package
As
PROCEDURE addemp (p_staffno IN emp_data.staffno%TYPE,
P_emp_name IN emp_data. Emp_name%TYPE,
P_desgn IN emp_data.desgn%TYPE, p_dob IN
Emp_data.dob%TYPE,
p_hq
IN
emp_data.Hq%TYPE,
p_deptno IN Emp_data.deptno%TYPE);
PROCEDURE salupd (p_staffno IN emp_sal.staffno%TYPE,
P_basic
IN
Emp_sal.basic%TYPE,p_gpf_sub
IN
emp_sal.gpf_sub%TYPE,p_gpf_rec
IN emp_sal.gpf_rec%TYPE,p_qtrs IN
emp_sal.qtrs%TYPE);
PROCEDURE Paybillgen;
PROCEDURE Paycalc (p_staffno IN emp_data.staffno%TYPE);
FUNCTION DA (p_basic IN emp_sal.basic%type)
RETURN number;
FUNCTION hra (p_basic IN emp_sal.basic%TYPE,
p_qtrs IN emp_sal.qtrs%TYPE)
RETURN number;
END salar_package;

BRBRAITT-JUN-2011

193

Information Technology For JTOs PH-II- IT

THE PACKAGE BODY


The package body fully defines the code for all the objects listed in the
specification and can contain additional objects not listed in package
specification. The second one objects is said to be private and are not available
to the users of the package. Private objects may only be called by other objects
within the same package body. The syntax for creating package body is:
CREATE [or REPLACE] PACKAGE BODY [User.]package_body
[IS/ AS]
PL/SQL package body;

Where package-body is the name of the package body which should be


the same as the name of the package specification. Continuing the
SALARY_PACKAGE example, its package body can be created via the
CREATE PACKAGE BODY command as follows;

Example:
CREATE PACKAGE BODY salary_package
AS
Crtdate DATE;
Crtmonth varchar2(9);
PROCEDURE addemp (p_staffno IN
emp_data.staffno%TYPE, p_emp_name IN
emp_data.emp_name%TYPE,
p_desgn
emp_data.desgn%TYPE,
p_dob IN emp_data.dob%TYPE, p_hq
emp_data.hq%TYPE,
p_deptno IN emp_data.deptno%TYPE)

IN
IN

IS
V_deptno emp_data.deptno%TYPE;
Empty_staffno EXCEPTION;
BEGIN
IF p_staffno IS NULL
RAISE empty_staffno;
ELSE
SELECT deptno into v_deptno
FROM dept
WHERE deptno = p_deptno;
INSERT INTO emp_data
VALUES(p_staffno, p_emp_name, p_desgn, p_dob,
p_hq, p_deptno);
INSERT INTO new_emp

BRBRAITT-JUN-2011

194

Information Technology For JTOs PH-II- IT


VALUES (p_staffno,p_emp_name,crtdate,crtmonth);
END IF;
EXCEPTION
WHEN NO_DATA_FOUND then
RAISE_APPLICATION_ERROR( -20001,
Department No: || p_deptno || does not exist );
WHEN DUP_VAL_ON_INDEX then
RAISE_APPLICATION_ERROR( -20002,
Staff Number : || p_staffno || should not be empty );
END addemp;
PROCEDURE salupd (p_staffno IN emp_sal.staffno%TYPE,
P_basic IN emp_sal.basic%TYPE,
P_gpf_sub IN emp_sal.gpf_sub%TYPE,
P_gpf_rec IN emp_sal.gpf_rec%TYPE,
P_qtrs emp_sal.qtrs%TYPE)
IS
Begin
Update emp_sal
SET basic = p_basic,
Gpf-sub
= p_gpf_sub,
Gpf-rec
= p_gpf_rec,
Qtrs
= p_qtrs
WHERE staffno = p_staffno;
COMMIT;
END salupd;
PROCEDURE paycalc (p_staffno IN emp_data.staffno%TYPE)
IS
Zero_pay EXCEPTION;
V_da number (6);
v-hra NUMBER (6);
v_cca number (6);
v_totpay
NUMBER (6);
v_netpay
number (6);
v_basic
emp_sal.basic%TYPE;
v_gpf_sub emp_sal.gpf_sub%TYPE;
v_gpf_rec emp_sal.gpf_rec%TYPE;
v_qtrs
emp_sal.qtrs%TYPE;
v_name
emp_data.emp_name%TYPE;
v_desgn
emp_data.desgn%TYPE;
BEGIN

BRBRAITT-JUN-2011

195

Information Technology For JTOs PH-II- IT


IF v_basic = 0 THEN
RAISE zero_pay;
END IF;
SELECT emp_nam, e_desgn INTO v_name,v_desgn
FROM emp-data
WHERE staffno = p_staffno;
SELECT basic,gpf_sub,gpf_rec,qtrs
INTO v_basic, v_gpf_sub,v_gpf_rec,v_qtrs
FROM emp_sal
WHERE staffno = p_staffno;
SELECT cca INTO v_cca
FROM allowrate;
V_da := da(v_basic);
V_hra := hra(v_basic,v_qtrs);
V_totpay := v_basic + v_da + v_hra + v_cca;
V_netpay := v_totpay v_gpf_sub v_gpf_rec;
INSERT INTO paybill
VALUES (p_staffno,v_name,v_desgn,v_basic,
v_da,v_hra,v_cca,v_totpay,v_netpay);
EXCEPTION
WHEN TOO_MANY_ROWS THEN
RAISE_APPLICATION_ERROR( -20001,
There are more than I records for this staffnumber: || p_staffno );
WHEN zero_pay THEN
RAISE_APPLICATION_ERROR( -20002,
Basic pay zero seems incorrect; It needs updatation);
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR( -20003,
There is no record of information for this staff no: || p_staffno);
WHEN OTHERS THEN
RAISE_APPLICATION_ERROR(-20004,
SOME OTHER ERROR HAS OCCURRED );
End paycalc;
PROCEDURE paybillgen
IS
CURSOR payinfncur IS
SELECT staffno
FROM emp_data;
BEGIN
FOR pay_cur in payinfncur

BRBRAITT-JUN-2011

196

Information Technology For JTOs PH-II- IT


LOOP
Paycalc(Pay_cur);
END LOOP;
END paybillgen;
FUNCTION da (p_basic IN emp_sal.basic%TYPE)
RETURN NUMBER
IS
V_da NUMBER (5);
V_darate NUMBER (5);
BEGIN
SELECT darate into v_darate
FROM allowrate;
V_da := p_basic*v_darate/100;
RETURN(v_da);
FUNCTION hra (p_basic IN emp_sal.basic%TYPE,
P_qtrs IN emp_sal.qtrs%TYPE)
RETURN NUMBER
IS
V_hra NUMBER(5);
V_hrarate
NUMBER (2);
BEGIN
SELECT hrarate into v_hrarate
FROM allowrate;
IF UPPER(p_qtrts) = Y THEN
V_hra := 0;
ELSE
V_hra := p_basic*v_hrarate/100;
END IF;
RETURN(v_hra);
End hra;
END salaray_package;
The create package body command shown in the above example
combines the code for the forward declarations of the da & hra functions with the
code for the forward declarations of the addemp, salupd, paycalc & paybillgen
procedures in the package header. The END clauses all have the names of their
associated objects appended to them. Modifying the end clauses in this manner
helps to clarify the ending points of the object code. Objects that are not having
forward declarations, such as EXCEPTIONS ,can be referenced in the package
body without being referenced.

BRBRAITT-JUN-2011

197

Information Technology For JTOs PH-II- IT


Additional functions, procedures, exceptions, variables, cursors and
constants may be defined within the package body, but they will not be available
to the public unless they have been declared within the package Specification
(via the CREATE PACKAGE command).
The package body is optional. If the package header does not contain any
procedure or function (only variable declarations, cursors, types and so on ), then
the body does not have to be present. This technique is used for declaring
global variables, since all objects in a package header are visible outside the
package.
Any forward declaration in the package header must be fleshed out in the
package body. The specification for the procedure or function must be the same
in both. This includes the name of the subprogram, its parameters and the mode
of the parameters.

PACKAGES SCOPE AND EXECUTION


Any object declared in a package header is in scope and is visible outside
the package by qualifying the object with the package name. Therefore, to
execute a procedure within a package, you must first list the package name, then
the procedure name.
Example;
EXECUTE salary_package.paycalc(1001);
However inside the package body, the object in the header can be
referenced without the package name.

PACKAGE INITIALIZATION
A package body may also include code that is run every time the package
is invoked, regardless of the part of the package that is executed. In the
following e.g., SALARY_PACKAGE package body is modified to include a SQL
statement that records the current date and the current month , at the start of the
package execution. Two new variables crtdate & crtmonth also have been
declared in the package body in order to record these values. Since the 2 new
variables are declared within the package body, they are not available to the
public. Within the package body, they are separated from the procedures and
functions. The package initialization code is shown as follows:
CREATE OR REPLACE PACKAGE BODY salary_package
AS
Crtdate
DATE;
Crtmonth
varchar2(9);

BRBRAITT-JUN-2011

198

Information Technology For JTOs PH-II- IT


.
BEGIN
SELECT sysdate, to_char(sydate, Month)
INTO crtdate, crtmonth
FROM dual;
END salary_package;

Note: The code that is to be run every time the package is executed is
stored in its own PL/SQL block at the bottom of the package body. It
does not have its own end clause; it uses the package bodys end
clause.

Every time the salary-package package is executed the crt date and crt
month variables will be populated by the query shown in the previous
listing. These 2 variables can then be used by the function &
procedures within the package ie; Addemp procedure uses this
variables for populating in the new_emp table.

DROPPING PACKAGES
Packages and its body can be dropped separately as follows:

To drop a package, use the drop package command as shown in the


following listings:
DROP PACKAGE Salary_package;

To drop a package body, use the drop package command with the body
clause, as shown in the following listings:
DROP PACKAGE BODY salary_package;

PACKAGES AND DEPENDENCIES


The Dependency picture for salary-package is shown below:

BRBRAITT-JUN-2011

199

Information Technology For JTOs PH-II- IT


SALARY_PACKAGE DEPENDENCIES

SALARY_PACKAGE
HEADER

SALARY_PACKAGE
BODY

The BODY of the


salary_package depends
on the header, but the
Header does not depend
On the body

The BODY of
salary_package
depends on the
emp_data, emp_sal
& Dept tables
EMP_DATA, EMP_SAL,
& DEPT

The package body depends on emp_data, emp_sl & dept tables and
package header. The package header does not depend on anything. This is the
advantage of packages. We can change the package body without having to
change the header. Therefore other objects which depend on the header wont
have to be recompiled at all , since they never get invalidated. If the header is
changed, this automatically invalidates the body, since the body depends on the
header.
We can examine the behaviour as follows:
In the previous salary_package package, we can refer it with the body and
the table emp_data.
We can query the information about the above objects as follows.
SELECT object_name, object_type,status
FROM user_objects
WHERE object_name IN (salary_package, emp_data);

OUTPUT:
OBJECT_NAME
SALARY_PACKAGE
SALARY_PACKAGE
EMP_DATA

OBJECT_TYPE
PACKAGE
PACKAGE BODY
TABLE

STATUS
VALID
VALID
VALID

- Now change the package body only, by changing the following


statements. Note that the header is unchanged.
V_da := p_basic *v_darate / 100 + 100;
- When you compile by giving / , package body will be created.
BRBRAITT-JUN-2011

200

Information Technology For JTOs PH-II- IT


- Now user_objects shows that package header is still valid.
SELECT object_name, object_type, status
FROM user_objects
WHERE object_name IN (salary_package, emp-data);
OUTPUT:
OBJECT_NAME
SALARY_PACKAGE
SALARY_PACKAGE
EMP_DATA

OBJECT_TYPE
PACKAGE
PACKAGE BODY
TABLE

STATUS
VALID
VALID
VALID

Even if we drop the table EMP_DATA, it only invalidates the package


body.
DROP TABLE emp_data;

Now you check the dependencies as follows.


SELECT object_name,object_type, status
FROM user_objects
WHERE object_name IN (salary_package, emp_data);

OUTPUT:
OBJECT_NAME
SALARY_PACKAGE
SALARY_PACKAGE

OBJECT_TYPE
PACKAGE
PACKAGE BODY

STATUS
VALID
INVALID

Only the package body becomes invalid.

BRBRAITT-JUN-2011

201

Information Technology For JTOs PH-II- IT

CHAPTER 10
ORACLE ARCHITECTURE AND USER MANAGEMENT
ARCHITECTURE OF THE ORACLE SERVER
The server product is simply an executable that performs important
activities when it is run. Access to the Oracle9i Database is supported by the
Oracle executable and a series of support routines and files that fall into the
categories described in the following list.

INIT.ora.
This file contains entries that determine the runtime
environment of the Oracle 9i database as it operates. The values for the
entries in this file control items such as the amount of memory allocated
to the instance and the breakdown of the structures within that memory.

Shared memory
Often referred to as RAM on the PC, this is an
amount of a computers memory that is acquired when an Oracle 9 i
database is started. This chunk of memory is acquired when the Oracle 9i
server is started and is affectionately called the SGA, or system global
area.

Database files
These fall into three categories-data files, control
files, and redo log files. The files that end in .dbf are data files, the ones in
.ctrl are control files, and .log files are online redo logs.

Support processes
These are workers that are spawned when an
Oracle 9i instance is started, and they help to facilitate access to a set of
Oracle database files

Network access
This is enabled by Oracle 9is Oracle Net product,
Its precursors were SQL*Net, delivered with versions upto and including
Oracle7, and Net8 with all releases of Oracle8.

Trace files
These are continually written to as Oracle9i operates and
are deposited in locations specified in an instances INIT.ora. They
contain primiarily two kinds of descriptive information -certain types of
Oracle errors and timestamp information related to some significant
instance activities.

Runtime libraries
These are the equivalent of PC dynamic link libraries,
containing routines and service components that allow the Oracle9i server
to operate and perform a suite of sophisticated functionally on its user
communitys behalf.

BRBRAITT-JUN-2011

202

Information Technology For JTOs PH-II- IT

Let us have a brief look at what goes on as the Oracle9i server operates.

Background Support Processes


Several background processes support the operation of an Oracle 9i
instance and accept connection requests from users.

Database Writer (dbw0)


The database writer is responsible for writing contents of database buffers
to disk. Oracle marks buffers in memory as dirty when the data they contain is
changed. There is one database writer process by default, but you can instruct
Oracle 9i. to spawn up to an additional nine. When a user process needs to
access data that is not in the buffer cache, dbwr ensures that these sessions can
have access to free buffers to go about their work.
This is the only process that writes data to the database -think of it as the
keeper of all the write activities, taking minutes as the database operates.

Process Monitor (pmon)


The process monitor is responsible for carrying out cleanup if and when
any user sessions are ended abnormally and they do not do it themselves. An
all-too-common activity is, when users abruptly end sessions against the
database by pressing CTRL-ALT-DELETE and rebooting their desktop
computers. Resources that may have been tied up by aborted sessions are
cleaned up and released by pmon. Let us call pmon the Secret Agent, slinking
around the database,assuming identifies of aborted user sessions, and
performing cleanup on their behalf.

System Monitor (smon)


The system monitor has a number of responsibilities, the primary one only
happening when the Oracle 9i instance is started. At startup, smons job is to
ensure that all the database files are consistent and perform recovery, if
required. There is also an assortment of other cleanup activities that may need
to be done, which are smons responsibility. Other background processes can
wake up smon if work needs doing . The smon process, by itself checks, every
so often, to see whether there are any tasks waiting for its attention. The work
performed by smon is integral to the smooth operation of any Oracle9i instance.
Let us call this process the Comptroller, ensuring that everything is being done
according to the book on an ongoing basis.

Log Writer (lgwr)

BRBRAITT-JUN-2011

203

Information Technology For JTOs PH-II- IT


The log writer is responsible for redo log buffer management. The redo
logs are Oracle9is transaction logs. Almost all activity against the database is
tracked in the online redo logs. As transactions are initiated, and eventually
committed (saved) or rolled back (abandoned), a record of this activity is written
to these log files. The log writer can write records of multiple transactions to the
redo log files, thereby maximizing its throughput and performance. Writing this
transaction information in batches rather than serially, one at a time, is less time
consuming and uses less resources. The log writer is recording all the
transactions against the virtual oracle 9i Database .

Checkpoint (ckpt)
When a check point activity begins, this process updates all the database
data files, with the details of the checkpoint. The database writer is the only
process that writes data to these database files, whereas the ckpt process
ensures the data files are in synch with one another after a checkpoint
completes. This process we call the Dispatcher -ensuring all is in synch.

Recoverer (reco)
The recoverer processs primary responsibility is to resolve failed
transactions in a distributed Oracle9i environment. This process automatically
connects to remote nodes, involved in a distributed transaction and resolves the
failed transactions, removing rows where appropriate from all nodes involved in
the failure. This recoverer process may attempt to connect to remote nodes more
than once for transaction resolution, with the delay time between consecutive
connections increasing each time.

Archiver (arc0)
The archiver process automatically saves copies of redo logs in a DBAspecified storage location, when media recovery is enabled. We discuss the
circular usage of the online redo logs and the special form of media recovery
called archivelog mode in the upcoming section Redo Logs.. This is an
optional process spawned by log_archive_start = true in the INIT.ora.
A network of background processes supports the operation of an Oracle9i
database. We feel it is relevant to the understanding of the Oracle software, and
the management of the 9i database in particular, to cover details on how the
support processes do just that -support. Let us move on to the INIT.ora, the first
piece in the Oracle9i server O/S file layer.

INIT.ora
The INIT.ora file is read when an Oracle9i instance is started .
Let us look at the type of parameters found in the INIT.ora file and a few
examples of each.
BRBRAITT-JUN-2011

204

Information Technology For JTOs PH-II- IT

Location Entries
The first category of parameters describes the location of one or more files
required by or written to as the instance operates. In some cases, it contains the
fully pathed location, directory, and file name, as in control_files. In other
cases, it simply contains a directory name, as in db_create_file_dest. When the
instance is started, Oracle9i verifies that the directories and files mentioned in
INIT.ora exist and can be written to and read from. If there are any problems,
Oracle9i displays one or more error messages along the lines of those shown in
the next listing.
SQL> startup
ORA-00444: background process LGWR failed while starting
SQL>
SQL> startup
ORACLE instance started.
Total System Global Area 537691548 bytes
Fixed Size
279964 bytes
Variable Size
469762048 bytes
Database Buffers
67108864 bytes
Redo Buffers
540672 bytes
ORA-00205: error in identifying controlfile, check altert log for more info

Limiting Entries
Parameters that list a number for controlling implementation of a feature of
the Oracle9i server usually fall into one of two categories:

Resource limiters - How many resource items should be made available


to the instance upon startup. The entries open_cursors, open_links, and
timed_statistics fall into this realm.
Memory allocations - How much memory should be set aside for the
piece of functionality described by these entries. The most commonly
changed parameters in this class are db_cache_size, shared_pool_size,
and sort_area_size. Some of these entries accept k for kilobytes, m
for megabytes, and g for gigabytes; others simply accept an integer
number of bytes.

There are some operating system -and Oracle9i -enforced minimums and
maximums that can be specified for these entries, and if they exist on your
hardware platform, you will be told when the instance is started. An occurrence
of this is shown in the next listing.
/d0/oraclehome/product/oracle9.0.1/dbs> sqlplus /nolog
SQL*Plus: Release 9.0.1.0.0. Production on Sun Jun 17 13:44:09 2009
BRBRAITT-JUN-2011

205

Information Technology For JTOs PH-II- IT


( c ) Copyright 2001 Oracle Corporation . All rights reserved.
SQL> connect / as sysdba
Connected to an idle instance.
SQL> startup
ORA-00093: shared_pool_reserved_size must be between 5000 and 8388608

Feature Entries
Feature entries also fall into two categories:
Those that can only specify keywords like true, false, partial, or full. A
few parameters that fall into this category are max_dump_file_size,
oracle_trace_enabled, and row locking. Any values other than those in
the approved list for each parameter will be rejected, as shown next.

SQL>ORA-01078:failure in processing system parameters


LRM-00105: always is not a legal Boolean for oracle_trace_enable
Those that determines the level to which a feature is enabled. A good
example of this type of entry is compatible. As the version number of the
Oracle9i software increases , more and more newfangled functionality is
added. To leverage the new features, this parameter must be set to reflect
the new version number.
Before moving on to the control file, let us
spend a minutes on making changes to the parameter values in INIT.ora.

Making Changes to Parameters


Not all parameters in INIT.ora can be changed. Often, changes to the
INIT.ora are put in place to attempt to deal with performance issues. Sometimes
tuning books or the Oracle9i documentation suggests increasing the likes of
shared_pool_size or db_cache_size to assist the speed and throughput of the
database.
In earlier releases of the Oracle server, the only way to change parameter
values was to edit the INIT.ora file, shut down, and start up the database. Since
Oracle7, and more so with Oracle8 and Oracle9i, more and more changes can
be made with the database running. The v$parameter data dictionary view
shown in the next listing is where you can deduce what parameters can be
changed without bouncing (shutdown followed by startup) the database.
SQL> desc v$parameter
Name
Null?
Type
------------------------------------------------------------NUM
NUMBER
NAME
VARCHAR2(64)
TYPE
NUMBER
BRBRAITT-JUN-2011

206

Information Technology For JTOs PH-II- IT


VALUE
ISDEFAULT
ISSES_MODIFIABLE
ISSYS_MODIFIABLE
ISMODIFIED
ISADJUSTED
DESCRIPTION
UPDATE_COMMENT

VARCHAR2(512)
VARCHAR2(9)
VARCHAR2(5)
VARCHAR2(9)
VARCHAR2(10)
VARCHAR2(5)
VARCHAR2(64)
VARCHAR2(255)

You may now have a preliminary knowledge of INIT.ora , what this file is all
about-

The Control File


Oracle9i builds a control file when a database is created; you require only
one control file per instance, but best practices dictate at least two of these
files, at all times. This file is a road map to the Oracle9i database and
contains instance-specific information such as

The name of the database.


Fully pathed names of all database files and redo log files.
The time and date that the database was created.
The current log sequence number -Oracle9i uses its online redo logs in a
circular fashion, allocating this sequence number at the start of a new log
file.
Relevant checkpoint information.

Control file information is available in the v$controlfile data dictionary view.


This view is shown below.
SQL> desc v$controlfile

Name

Null?

STATUS
NAME

Type
VARCHAR2 (7)
VARCHAR2(513)

The startup and shutdown of the Oracle9i database uses the instance
control files for consistency and completeness checking. When we speak of
consistency, we refer to the cross-file dependencies all over the Oracle9i
database that are checked and rechecked on startup and shutdown. In this
context, completeness means a check for the presence of and accessibility to all
the files mentioned in the control files. Let us look now at the redo or transaction
logs.

BRBRAITT-JUN-2011

207

Information Technology For JTOs PH-II- IT

Redo Logs
The redo log files are the heart of the proprietory Oracle9iserver. Some
other vendors may have a similar facility for tracking the activity against their
database. Oracle will write to any number of redo log files that the DBA chooses
to specify. Redo logs were introduced in Oracle V6 (circa 1988), and with
Oracle7 in February 1993, redo log files were enhanced to become multimembered redo log groups. When DBA now talk about the online redo logs,
they really mean online redo log groups.
When redo log groups are created, we give them an integer number,
which becomes the group number to which they are referred by the DBA. We
then speak of redo log group 1or redo log group 2, and so on. As users interact
with the Oracle9i database, a record of their activities is written to the online redo
logs at commit or rollback time. Redo logs are a finite size, and when they fill up,
Oracle switches to another set of log files.
NOTE
Each member of the same redo log group is a mirror image of the other
members in the same group.
Oracle9i needs at least two single-membered redo log groups to operate,
though we recommend at least three two-membered redo log groups. These
must be made manually using a GUI such as OEM or SQL*Plus. When a redo
log group fills up, Oracle switches to the next available group. Before a group is
marked available, Oracle marches through each redo log group reconciling any
outstanding activities, and then marks the group able to be used the next time a
switch occurs. The question you may have already asked yourself is What if a
group has not yet been marked as reusable and its turn comes up?. Oracle9i
suspends activity against the database until the group is marked reusable, and
then operations carry on
Figure 1
illustrates this concept

Group 1

Group 2

Group 3

BRBRAITT-JUN-2011

208

Information Technology For JTOs PH-II- IT

Group 1

Group 2

Group 3

.
Figure -The circular re-use of the online redo log groups
Note

Online redo log file information can be viewed in the v$logfile data
dictionary view shown in the next listing.

SQL>desc v$logfile
Name
Nul?
Type
---------------------------------------------GROUP#
NUMBER
STATUS
VARCHAR2(7)
TYPE
VARCHAR2(7)
MEMBER
VARCHAR2(513)

We have now looked at the major players- background support


processes, redo logs, and control files, these files track activities and pertinent
information about the Oracle9i instance. Figure 2 illustrates who interacts with
what .

BRBRAITT-JUN-2011

209

Information Technology For JTOs PH-II- IT


FIGURE - SGA , SUPPORT PRECESS AND FILE INTERACTION

reco
pmo
n

smon

Dbw0

SHARED
MEMORY
( SGA)

LGWR

R
ckpt

Data
files

Arc0

Control
files

Offline
Offline
storage
Offline
storage
Online
storage
redolog

Offline
storage

The Database Data Files


Your data is stored in the data files. These O/S files are created using one
of the tools supplied with Oracle9i, be it SQL*Plus or OEM. Data files
themselves are not allocated to the database directly; they are hooked into the
instance using an Oracle9i tablespace. As tablespaces are created, one or
more data files are included, as shown in the next listing- as part of a create
tablespace command.
Create tablespace gl
datafile /do/oradata/ntirety/beg9/gl01.dbf size 2000m,
/d1/oradata/ntirety/beg9/gl02.dbf size 2000m,
/d2/oradata/ntirety/beg9/gl03.dbf size 2000m
blocksize 2048
default storage . . . ;
NOTE

When the block size keyword is used to create a table space, there must
be a corresponding parameter (in this case, db_2k_cache_size) in
INIT.ora for that sized block. If you include the block size keyword
without its corresponding size parameter, you will get error ORA_29339.

BRBRAITT-JUN-2011

210

Information Technology For JTOs PH-II- IT


Once this command is written, an entry is written to DBA-DATA-FILES,
part of Oracle9i data dictionary, and the table space is acquired by the instance.
Table I illustrates the hierarchical relationship between the database, a table
space, and the database data files.
When a table space is added to an Oracle9i instance, a record of its size,
name, and location is written to the control files and the data dictionary. The
tablespace map in the data dictionary tracks the Oracle data blocks that have
been allocated to a tablespace. Once the file exists, space is available to users
with appropriate credentials. The Oracle9i create database statement produces
the SYSTEM tablespace where the data dictionary resides.
As soon as the database exists, the DBA runs a handful of administration
scripts that set up the remainder of the data dictionary. One use for table spaces
over and above SYSTEM is for Oracle9is rollback segments. A discussion of
architecture would be deficient without paying some attention to these
components of each and every Oracle database.

Entity
Database
Tablespace
Data file

Is a superset of
Tablespace / data file
Datafile

Belongs to
Database
Tablespace

TABLE - Relationship Between Database, Table space and Data file

Rollback Segments / Undo Tablespace


Whatever format you choose for the management of your databases
undo, that information plays a crucial role in the implementation of Oracles read
consistent mode.
With multiple user
sessions working with the data
concurrently, this model ensures that a session has access to column values
within a database table for the life cycle of the transaction. When necessary,
Oracle9i automatically saves a before image of data, in case the transaction
that initiated the change is not committed. Suppose a banking application is
receiving a deposit for $1,200 into a savings account with a current balance of
$940. The first try at the update, the operator enters 12,000 instead of 1200
Table2. illustrates how read consistency is implemented, assuming the session
that is performing the updates shown has a session identifier, or SID, of 99.

BRBRAITT-JUN-2011

211

Information Technology For JTOs PH-II- IT


Account Balance at End of Activity
State

Activity

Undo

1
2

Pretransaction #1
Update savings set balance
= balance + 12000 where
account = 55524;
Rollback;
Update savings set balance
= Balance + 1200
where account = 55524;
Commit;

Empty
940

Data
in Seen
memory
others
940
940
12,940
940

Empty
940

940
2,140

940
940

Empty

2,140

2140

3
4
5

by

TABLE - Read Consistency and the Role played by Undo


Notice how when SID 99 has no active transaction, there is no undo.
When the transaction started (state 2), Oracle9i allocates an undo area to keep a
copy of the pretransaction balance.
Before the transaction started, the
information for account 55524 was on disk, not having yet been read into
memory. As the transaction begins, the data is scooped into memory, the update
applied, and undo space reserved for the sake of other users. When the
rollback; is issued, the data that was supposed to have been updated is left in
memory, with its old value, and the undo released. It is the same story when the
transaction is reinitiated, and upon commit; the undo is released and the new
value, in memory, is available to SID 99 and all other sessions. The secret of this
read consistent model is illustrated in another way in Table 3 showing how the
concurrent user community sees the data in account 55524.
-------------------------------------------------------------------------------------------------Balance Value Seen and from Where
( D = database, M = Memory, U = undo)
State

SID 99

Other Sessions

1
940 (D)
940 (D)
2
12,940 (M)
940 (U)
3
940 (M)
940 (M)
4
2,140 ( M)
940 (U)
5
2.140 (M)
2,140 (M)
--------------------------------------------------------------------------------------------------TABLE- Who Views What Value and from Where
The m word (memory) keeps surfacing in this section. Speaking of memory, let
us move on and look at two significant areas in shared memory -the library

BRBRAITT-JUN-2011

212

Information Technology For JTOs PH-II- IT


cache and the data cache. The next section will just about round out the
discussion of Oracle9i architecture.

Significant Memory Structures


Oracle9i is a fabulous user of computer memory. Here, we are going to
have a look at the two most significant memory structures-the library cache and
the data cache.

The Data Cache


Oracle9i sets aside a portion of its SGA to hold data read from the
database files and / or getting ready to be written back to those same files. The
size of the data cache is determined by a handful of INIT.ora parameters, the
most common being db_cache_size. This entry specifies a default cache size in
megabytes (using m) or an absolute number of bytes.
Figure highlights how Oracle 9i uses its data cache. User sessions read
and manipulate data in this cache. They do not directly interact with the
database files. All data, regardless of what ends up happening to it, passes
through memory on its way to these user sessions.
Oracle9i deliberately uses memory to store data as it is massaged by the
user community.
Printing, reading from disk drives, and memory access are
common activities performed as systems operate, listed from slowest to fastest.
One can justifiably claim that the speed with which the printer churns out the
printed word ,sets the standard for the speed of the computer. The point of all
this ? If you had a choice between reading Oracle9i data directly from disk or
memory, which would you choose- access at the speed of the printer or from
memory? Here is a hint- when read from memory, the access is virtually at the
speed of light, or 280,000 kilometers per second.
Oracle9i moves data into memory before making it accessible to user
sessions. These sessions work with the data in memory, the data gets marked
as changed, where appropriate, and eventually gets written back to disk.
Oracle9i performs all its data manipulation in the data cache, a finite amount of
computer memory.

BRBRAITT-JUN-2011

213

Information Technology For JTOs PH-II- IT

USER SESSIONS
User sessions read data from
and return data to the data cache

Data cache

SGA

Library
cache

Background processes move data


between the data cache and the database
files
Oracle 9i database files

FIGURE HOW ORACLE 9i USES THE DATA CACHE


Cache sizes of 400MB to 500MB are common on some of the higher-end UNIX
Servers. Oracle9i manages the space in the data cache using a least recently
used, or LRU, algorithm. Data gets aged out of the cache when the space it
occupies is required for other data. The LRU rule ensures that data used the
longest time ago is flushed before the more active data. Once an Oracle9i
instance is started, you need not perform any manual maintenance of the data
cache
The Library Cache
The library cache is where all the SQL and PL/SQL statements reside in
memory. All theOracle9i database engine understands is SQL; regardless of
what you use to facilitate user interaction with the database. SQL is what gets
sent off to the software for processing. This cache is sized primarily by
shared_pool_size in INIT.ora, with absolute values in bytes or the megabyte
measurement followed by the m abbreviation. In a nutshell, the following steps
are how Oracle9i processes SQL:

Statement is passed to Oracle9i for processing.


.Before it is placed in the library cache, a hash value is computed that
represents a number of characteristics of the SQL.
Oracle compares the computed hash value against those values in a
hash table it maintains for SQL statements already in the cache.
If a match is found, the new SQL statement is thrown away and the one
sitting in the cache is executed on its behalf.

BRBRAITT-JUN-2011

214

Information Technology For JTOs PH-II- IT

If no match is found, further processing is done on the new SQL


statement, and entry is made in the library cache hash table for the
newly arrived code, and it is placed in the library cache.

Any SQL statement executed against the Oracle9i database must first be
placed in the library cache and marked ready-to-execute. This library cache, is
also referred to as the shared pool.
Locks and Latches
Locks and latches are fundamental to the protection of your data and
shared memory structures. Oracle9i runs in a multi user environment, and
without these protection mechanisms, the smooth and consistent operation of the
database would be in question.
Locks
Oracle9i uses locks to ensure that different sessions are not able to
interact with the same data in use by other sessions. Interact in this context
means anything other than select. This protects the integrity of the data and is
managed automatically by Oracle9i, without need for manual intervention. Locks
are acquired as SQL statements begin their interaction with data and last for the
duration of a transaction. Transactions commonly end with a commit or
rollback, the latter restoring data to its pre-transaction state. Oracle9i uses two
locking modes:
Exclusive mode will not allow the locked resource to be shared what-soever by any concurrent sessions. This lock is acquired to modify data or
define the structures within which data resides.
Share mode allows concurrent read access to the same chunk of data,
with escalation to an exclusive mode lock when change is initiated.
Oracle 9i obtains a share mode lock on a row of data as it is accessed as
part of the result set to a query. If, and only if, that query leads to an update or
delete statement, the lock is escalated to an exclusive row lock, if the row is not
already locked in that mode. Oracle9i allows simultaneous updates to rows
sitting in the same data block. If two sessions request update access to the
same row in the same data block, they queue up and go about their business in
a serial fashion. There are two types of locks Oracle9i acquires on its data;

DML locks, or data manipulation locks, ensure data integrity in multi- user
environments for the purposes of protecting data.
DDL locks, or data definition locks, protect the structure of objects and are
acquired for data definition activities.

Oracle9i requests a lock in the least restrictive mode possible and,


from time to time, may convert a number of row locks to a table lock to reduce
BRBRAITT-JUN-2011

215

Information Technology For JTOs PH-II- IT


the number of locks being acquired. Oracle9i chooses this path when the
management of a table lock requires less overhead than the protection provided
by multiple row locks.

Latches
Latches are low-level mechanisms that help manage the internal
operations of the Oracle9i software. They can be thought of as a type of lock,
acquired and released in subsecond time periods . Latches are almost always
obtained when requested , but, as the activity on an Oracle9i database
increases, often queue behind one another for getting hold of precious
resources. Remember the redo logs and how transaction information is written
to these files as the database operates. A special redo copy latch ensures that
one and only one process writes to the redo logs, at a time. Obtaining a latch is
only part of the work; there is a cleanup phase that comes into play as a latch is
released.
Latches are required when working with shared memory structures in the
SGA. If working with a particular structure requires a latch and that structure is in
use, a wait situation is created. There are two types of latches:

Willing to wait means that , if a latch cannot be obtained at once, a


persistent request is resubmitted until it can be satisfied. Latches in the
library cache are examples of ones that fall into this category.
Requests for no-wait latches are cancelled if the latch cannot be obtained
immediately and are resubmitted as a new request. Latches related to
redo log copies fall into this class.

DBA need not worry themselves about latches unless they cause
problems in their databases, if they ever do. Suffice it to say, latches are part
of the puzzle fundamental to the operation of the Oracle9i database and,
most of the time, go about their work unnoticed. They are an essential player
in the running of the instance . We find it almost ironic that the words lock and
latch both start with the same letter-/-and the words look out start with the
same letter, which is what you will do if your locks and latches lead to
significant wait situations. The hourglass displayed by the mouse cursor
when a window is busy is a familiar example of a wait situation.
We have given you a framework of how the Oracle9i database is
put together and what pieces play what role. Each component in the software
equation may not be all that important on its own; bring all of them together
and you have a powerful, robust, and fast database management system i.e.
Oracle9i.

BRBRAITT-JUN-2011

216

Information Technology For JTOs PH-II- IT


USER MANAGEMENT
The Oracle database has several layers of security and gives
you the ability to Audit each level.
Security Capabilities
Oracle makes several levels of security available to the DBA.

Account security for validation of users.


Access security for database objects
System level security for managing global privileges.

Account Security
In order to access data in an Oracle database, you must have
access to an account in that data base. Each account must have a
password associated with it. A database account can also be tied to
an operating system account. Passwords are set for a user when the
users account is created and may be altered after the account is
created.
A users ability to alter the account password will be limited by the
tools to which the user is granted access. The data base stores an
encrypted version of the password in a Data Dictionary table. If the
account is directly related to an OS account, it is possible to by-pass
the password check and rely on the operating system authentication
instead.
The passwords can expire and the DBA can establish the conditions
under which a password can be re-used in a database setting for
password history. You can use profiles to enforce standards for the
passwords and can automatically lock accounts, if there are multiple
consecutive failure to connect to the account.

Object Privileges
Access to objects within a database is enabled via Privileges.
These allow specific database commands to be used against specific
database objects via the Grant Command

System Level Roles & Privileges


You can use roles to manage the system level commands available
to users. These commands include CREATE TABLE and ALTER
INDEX. The CONNECT and RESOURCE Roles are useful for the
BRBRAITT-JUN-2011

217

Information Technology For JTOs PH-II- IT


basic system privileges required by end users. Users who have the
resource role are also granted the unlimited table space system
privilege. Because of this additional privilege, you should restrict the
use of Resource role to development and test environments.

Implementing Security
The security capabilities in oracle include roles, Profiles and direct
grant of privileges. The Oracle Enterprise Manager toolset provides a
security Manager tool to enable the management of user accounts,
roles, privileges and profiles.

Creating Users
When creating a user, your goal is to establish a secure, useful
account that has adequate privileges and proper default settings.
When the account is created, it will not have any capabilities and users
will not even be able to login, until that privilege is granted.
All of the necessary settings for a user account can be specified
within a single create user command. These settings include values
for all of the parameters listed.

ALTER USER
Modify the security settings for an existing database user, to change
the options associated with that user. Options that can be changed
through the Alter user command are:

Password
OS Authentication
Default tablespace
Temporary tablespace
Quota for Tablespace
Profile
Default Roles

Modifications to the security settings for a user do not affect current


sessions, only subsequent sessions.

Changing the quota per tablespace either reduces or increase


space for a user.

Changing the quota to o revokes access from the table space


entirely.

BRBRAITT-JUN-2011

218

Information Technology For JTOs PH-II- IT

Profiles are altered, if the DBA decides to alter the limitations on


system resources.

Roles should be assigned if a user changes departments and


requires different privileges for the new departments tables.

SYNTAX:
ALTER USER
username
IDENTIFIED
by password / externally
DEFAULT TABLESPACE tablespace_name
TEMPORARY TABLESPACE tablespace_name
QUOTA integer / unlimited ON tablespace_name
DEFAULT ROLE role_name /All except role/
None;
WHERE :
Default Role
Default Role
Default Role
Default Role
Default Role

- establishes default roles for


the user
rolename
all
all except rolename
none

The ALTER USER system privilege is required to alter the user.


Only options specified within the Alter user SQL command are
changed.
All previously given resources remain.
Once a quota of O is re-assigned, the objects owned by the user
remain in the revoked tablespace. Yet the objects cannot be
allocated any new space.

DROP AN EXISTING USER


Drop a data base user with the Drop user SQL command.
SYNTAX
DROP USER Username CASCADE;
WHERE
User user to drop

BRBRAITT-JUN-2011

219

Information Technology For JTOs PH-II- IT


CASCADE drops all objects in the users schema before dropping the
user.
- When a user is dropped with the cascade option, the username and
associated schema are removed from the data dictionary and all
schema objects contained in the users schema are immediately
dropped.
- a user that is currently connected to a database cannot be dropped.
- DROP USER system privilege is required to drop a user.
Monitor Users
View user and profile information in the data dictionary, which stores
information about every username. The data dictionary includes
information on:
All users in the data base
The default tablespace for the tables, clusters and indexes of each
user.
The total space used for temporary segments
Space quotas.

Data Dictionary Views


The data dictionary for an Oracle database is a set of tables and views
that are used as a read only reference guide of the database . The data
dictionary views give up- to- date information about users and objects.
Helpful data dictionary views
DBA _USERS
ALL_USERS
USER_USERS

DBA_PROFILES
DBA_TS_QUOTAS
USER_TS_QUOTAS

Example 1: Display information about all users of the database with the
DBA_USERS data dictionary view.
SELECT * from DBA_USERS;
Example 2:Display tablespace quotas
USER_TS_QUOTAS data dictionary view.

for

the

current

user

with

the

SELECT * from USER_TS_QUOTAS;


Kill a User session:
When necessary, terminate a users session while that user is logged
on to the database.
BRBRAITT-JUN-2011

220

Information Technology For JTOs PH-II- IT

Killing a user session


Prevents a user from issuing further database calls.
Frees locked resources
Will display a message to the user
Requires the ALTER SYSTEM privilege.
SYNTAX
ALTER SYSTEM kill session integer1, integer2;
Where:
Kill session terminates a session
Integer1
- specifies the user sessionid
Integer2
-specifies the user serial number
-A user session is killed when the user is holding resources urgently needed
by another user, or when the DBA needs to shut down the database.

When a user session is killed, tasks performed are:

- Rolls back the users current transaction


- Release all currently held table on row locks.
- Frees all resources currently reserved for the user.
- If the user is performing some activity that must
be completed, such as
waiting for a reply or rolling back a transaction, the Oracle server waits for this
activity to complete.

Query the V$Session data dictionary view to identify the session ID and
serial number of user session.
SELECT SID, SERIAL#, username from V$session;

USER PROFILES
You can use profiles to place limits on the amount of system and
database resources available to a user and to manage password restrictions. If
no profiles are created in a database ,then the default profile, which specifies
unlimited resources for all users will be used.
Resources that can be limited via profiles
SESSIONS_PER_USER
in an instance
BRBRAITT-JUN-2011

-Number of concurrent sessions a user can have

221

Information Technology For JTOs PH-II- IT


CPU_PER_SESSION
-The CPU time in hundredths of seconds, that a
session can use
CPU_PER_CALL
- The CPU time in hundredths of seconds
CONNECT_TIME
- The number of minutes, a session can be connected
to a database.
IDLE_TIME
- The number of minutes, a session can be
connected to the database without being actively used.
FAILED_LOGIN_ATTEMPTS
- The number of consecutive failed login
attempts that will cause an account to be locked.
PASSWORD_LIFE_TIME
- The number of days a password can be used
before it expires.
PASSWORD_REUSE_TIME
- The number of days that must pass before a
password can be re-used.
PASSWORD_REUSE_MAX
- The number of times a password must be
changed before a password can be re-used.
PASSWORD_LOCK_TIME
- The number of days an account will be
locked, if the failed_ Login_ attempts setting are exceeded.
PASSWORD_GRACE_TIME
- The length in days of the grace period,
during which a password can still be changed when it has reached its
password_life_time settings
Eg:Create profile Limited_profile
Limit
Failed_ Login_ Attempts 5;
Create user sam
Identified by john
Profile limited_profile;

Password Management
You can use profiles to manage the expiration, re-use and complexity of
passwords.

You can limit the life time of a password and lack an account whose
password in too old.
You can also force a password to be at least moderately complex and lock
an account that has repeatedly failed login attempts . If you set the
failed_ login_ attempts resource of the users profile to 5, then five
consecutive failed login attempts will be allowed for the account, the6th
will cause the account to be locked. If the correct password is supplied on
the fifth attempt, then the failed-login-attempt count is reset to O, allowing

BRBRAITT-JUN-2011

222

Information Technology For JTOs PH-II- IT

for 5 more consecutive unsuccessful login attempts before the account is


locked.
If an account becomes locked due to repeated connection failures, it will
automatically become unlocked when it profiles password_lock_time vale
is exceeded. If password_lock_time is set to 1, then the account which is
locked due to repeated Connection failure would be locked for 1 day, at
which point the account will be unlocked.
To unlock an account, use the account unlock clause of the Alter user
command from a DBA account.
ALTER USER sam account unlock;

can manually lock on account


ALTER USER sam account lock;

You can establish a maximum life time for a password via


the Password_ life_time resource, within profiles. You can force users to change
their passwords every 30 days as in the following example.
CREATE PROFILE limited_profile
LIMIT
PASSWORD_LIFE_TIME 30;
CREATE USER sam
Identified by john
PROFILE limited_profile;
Each account that uses limited_ profile will have its password
expire after30 days. If you password has expired, you must change it the next
time you login, unless the profile has a specified grace period for expired
password. An expired account requires manual intervention by the DBA, to be
re-enabled.
ALTER USER sam PASSWORD expire;
- when sam attempts to connect to his account next time, he is immediately
prompted for a new password for the account.
You can also force users to change their password when they first
access their account via the password expire clause of the create user
command.
To see the password expiration date of any account, query the
expiry_date column of the DBA_USERS data dictionary and USER_USERS

BRBRAITT-JUN-2011

223

Information Technology For JTOs PH-II- IT


expiry- date column to see the password expiration date of the account of the
current user.

PRIVILEGES
You can grant users privileges to access the database and objects
within the database and allow them specific system privileges.
Privilege Type
1.

SystemPrivileges

A privilege or a right to perform a particular action or to perform a


particular action on a particular type of object
2.

Object Privileges

A privilege or right to perform a particular action on a specific table,


view, sequence, procedure, function or package.

System Privileges
Allows users to perform a particular database operation or class of
operation.
Types of system Privileges
1.

In ones own schema


The privilege to create a table , create a sequence in ones own schema.

2.

On all objects of a specified type

Theprivilege to create a table in any schema or the privilege to


update rows in any table or view in any schema.
3.

On the System or a User.


The privilege to create a user or the privilege to create a session.

Grant system Privileges


Grant system privileges to and from users and roles using the
Grant system Privileges.
Syntax
BRBRAITT-JUN-2011

224

Information Technology For JTOs PH-II- IT

GRANT System Privilege / role


To user / role / PUBLIC
WITH ADMIN OPTION;
Where
Role is a role name to be granted
PUBLIC - grants system privileges/role to all
users.
With Admn Option Allows the grantee to grant the system
Privilege or role to other users or
roles.
- Grants made with Admin option are not
hierarchical .
- Revoking a Grant with Admin option,
does not Cascade.

Display system Privileges


Example: List the system privileges that have been granted
By querying the view DBA_SYS_PRIVS.
SELECT * FROM DBA_SYS_PRIVS ;

Revoke system Privileges


Syntax:
REVOKE SYSTEM PRIVILEGE / ROLE
FROM USER /ROLE / PUBLIC;
Where
PUBLIC
users.

- revokes the system privilege or role from all

Object Privileges
Allows users to perform a particular action on a specific table, view,
sequence or stored procedures by granting them object privileges. The type of
object privileges vary from object to object. Different object privileges allow the
use of specific SQL statements.

BRBRAITT-JUN-2011

225

Information Technology For JTOs PH-II- IT

Object Privilege

SQL Statement Permitted

SELECT
Select from Object (table, view)
UPDATE
Update object (table or view)
ALTER
Alter object(table or sequence)
DELETE
Delete from object
EXECUTE
Execute object (Procedure/function)
INDEX
Create Index On Object (Tables only)
REFERENCES
Create or Alter table statement
defining a Foreign key
Integrity constraint on object (tables
only)
- You can grant object privileges to users and roles with the Grant command.
Syntax:
GRANT Object privilege / ALL [column]
ON Object TO user / Role / Public
WITH GRANT OPTION;
Where
Object Privilege
Column

- is an object privilege to be granted.


- Specifies a column from a table or view
on which privileges are granted.
-Only specify columns when granting
Insert, References or update privilege.
-If columns are not listed, the grantee
has privileges on all columns
in the table or view.
ALL
-Specifies all object privileges.
ON
-Identifies the object on which the
privileges are granted
TO
-Identifies users or roles to which the
object Privileges is granted.
PUBLIC
With grant

- grants to al users.
- allows the grantee to grant the object
Privileges to other users/roles

Grant option cannot be granted to a role

BRBRAITT-JUN-2011

226

Information Technology For JTOs PH-II- IT

Example:
GRANT Select ON EMP TO Emi with Grant option;
Note:
Emi can grant the privilege to another user or role.
Display object privileges
Select * from DBA_TAB_PRIVS;
Helpful Data Dictionary views
DBA_TAB_PRIVS
DBA_COL_PRIVS
base.
USER_TAB_PRIVS

-Display all privileges on objects in the


Database.
-All privilege on Columns in the data-

-All privileges on objects for which the


User is the owner, grantor or grantee.
USER_COL_PRIVS -Privileges on columns for which the
user is the Owner, grantor or grantee.

Revoke Object Privileges


Syntax
Revoke Object privilege on Object
From user / role / public
Cascade constraints;
Where
Cascade

drops any referential integrity constraints


defined using REFERENCES privilege.

Grantors can revoke privilege from only those users to whom they have
granted privileges.

Example;
REVOKE SELECT ON EMP
From Emi;

Revoke object privileges with Grant option, has a cascading effect.

ROLES

BRBRAITT-JUN-2011

227

Information Technology For JTOs PH-II- IT

Roles are named groups of related privileges that are granted to


users or other roles.
Role characteristics

Can consist of both system and object privileges.


Are not owned by anyone, not in any schema
May be granted to any user or role
Can be enabled or disabled for each authorized user.
Description of roles are stored in the data dictionary.

Create Roles
Define categories of privileges for particular groups of users by
creating roles containing those privileges.

Create a role for each application (Application role)


Create a role for each type of user (User role)
Can GRANT user and application roles to users.

Syntax:
CREATE ROLE Role_name not identified / identified BY
password / externally;
Where
Role name
Not identified

- is the name of the role to be created


- Indicates that no password is required
to Enable the role.

Identified

- Indicates that users granted the role


must be verified to enable it.
indicates that the user must specify
the password to enable the role.

By password
Externally

- ensures that the Oracle server verifies


user access to the Role using on operating
system utility.

The CREATE ROLE PRIVILEGE IS REQUIRED TO CREATE ROLES.


Example:
CREATE ROLE manager NOT identified;

BRBRAITT-JUN-2011

228

Information Technology For JTOs PH-II- IT


Grant create session, create any Table to
Manager;
Grant Manager to Emi;
Establish Default Roles
ALTER USER Username
DEFAULT ROLE rolename / all / all except
role_name /none;
- Default role :

establishes default roles for the user.

The Oracle server enables the users default roles at login.


By default, all Roles granted to the user are Default roles.
Helpful Data Dictionary views

ROLE_SYS_PRIVS
ROLE_TAB_PRIVS
ROLE_ROLE_PRIVS
SESSION_ROLES
USER_ROLE_PRIVS
DBA_ROLES

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

BRBRAITT-JUN-2011

229

S-ar putea să vă placă și