You are on page 1of 169

MASTERING

ORACLE SQL & PL/SQL


WITH PRACTICAL EXERCISES
Table of Contents

Chapters Titles Page No

1 Introduction to databases 1

2 Writing Basic Select Statements 9

3 SQL Functions 19

4 Using Sub queries To Solve Problems 32

5 Constraints 36

6 Retrieving Data From Multiple tables 43

7 Creating And Managing Tables 53

8 Other Database Objects 58

9 Manipulating Data 66

10 Transaction Control Language 69

11 Data Control Language 72


CHAPTER 1
1.0 INTRODUCTION TO DATABASES
Databases, in their most simple form, are a mechanism for storing data. The data
can be logical, like the values stored in a computer program, or may be physical,
like a file or receipt. You probably have databases in existence all around you,
but you may not see them as such. For example, the shoebox in which you’ve
placed your tax receipts for the accountant is a database of your annual
expenses. When you open a file cabinet and take out a folder, you are accessing
a database. The content of the file or folder is your data (e.g., your credit card
statements, your bank statements, invoices, purchase orders, etc.). The file
cabinet and drawers are your data storage mechanisms.
Before the advent of computers, all data was stored in some easily recognizable
physical form. The introduction of computers simply changed the data from a
physical form to a digital form that is represented by a series of 1’s and 0’s.
When data began to move from a physical form to a logical form using
computers, the terminology database became inevitable in IT industry.

1.1 What is a database?


Most definitions for a database state that it is a collection of data. Even though
this describes a database, the actual or the refined definition of a database is that
it is an organized collection of related information. In other words a database can
be defined as an application that manages information and allows fast storage
and retrieval of these information.

1.2 Advantages of a database


 The information can be easily stored and accessed.
 More number of users can concurrently load, manipulate and access their
data.
 Improved data security.
 Information can be accessed at a greater speed.
 A single set of data can be viewed in different formats without affecting the
base data.
-1-
1.3 How data is stored in a database?
A database stores the related information in the form of two-dimensional tables
that is rows (records) and columns (fields). These tables have a structure where
all the rows or records are stored. For example an organization needs to store
the information like the employee id, employee name, designation, salary, date of
joining etc; a table is created as shown in the example below.

Example Table
The table EMP is used to store information about employees:
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7369 SMITH CLERK 7902 17-DEC-80 800 20

7499 ALLEN SALESMAN 7698 20-FEB-81 1600 500 30

7521 WARD SALESMAN 7698 22-FEB-81 1250 300 30

7902 FORD ANALYST 7566 03-DEC-81 3000 10

7698 BLAKE MANAGER 01-MAY-81 3850 10

Table 1.1
1.4 Database management system (DBMS)
For managing huge volume of data an application or a system is required. This
system is called as DATABASE MANAGEMENT SYSTEM (DBMS). It is a
software system that uses a standard method of cataloging, retrieving, and
running queries on data. The DBMS manages incoming data, organizes it, and
provides ways for the data to be modified or extracted by users or other
programs. Relational database management system is a DBMS based on the
relational model, which was introduced by E.F.Codd. Here data is stored in
tables as shown above. Oracle is a relational database management system with
object extensions (ORDBMS).

-2-
1.5 What is a relational database?
A British engineer Ted Codd working for IBM explained the theory of relational
databases "A Relational Model of Data for Large Shared Data Banks" in the
1970s whilst working for IBM. At the core of this relational model is the concept of
normalization, which is the separation of the logical and physical data models.
This enables you to "see" the database in a completely different way to its
underlying structure
A relational database, therefore, can be regarded as containing a set of 2-
dimensional tables ("relations") with each table comprising rows ("tuples"or
"records") and columns ("domains" or "fields"). Relationships between database
tables are created when one table has a column with the same meaning as a
column in another table. The actual values of the columns are irrelevant but they
must refer to or mean the same thing.
Let's take the example of a very simple database with just 2 tables

 EMPLOYEES
 DEPARTMENTS

The employees table has just three columns:


 Employee_id
 Employee_ name
 Department_id
The department table has just two columns:
 Department_id
 Department_name
There is a relationship between these two tables via the department_id column in
each table. The department_id column in the employees table relates to the
department_id column in the departments table. This enables you to assign
employees to a department and determine which employees work for which
department. Now we can say that these two tables are related

-3-
1.6 Oracle Database Server
When oracle RDBMS software is installed in a computer and a database is
created in that computer then that machine becomes the oracle server. One or
more databases can be created in a single server.

Figure 1.1

1.7 Communicating with the server


To store the information in the database, to manipulate the existing data and to
retrieve the data from the database, first a connection must be established to the
server. Establishing a connection can be done in the following ways

Log on to the same server where the database resides (host based)
Log on from a different machine (client), which is directly connected to the server
(Client  database server) or (two tier)
Log on from a machine, which is having just a user interface to an Application
server where the application processing is done and then to the database server
where the actual data is stored.
(Client application server (middle tier)  database server) or (three tier/N tier)

-4-
1.8 Introduction to SQL
In a database environment the client should send a request to the server and the
server should respond to the client’s request. For any communication a language
is necessary. The language used here is the Structured Query Language,
commonly called as SQL. It is a simple English like language easy to understand
and write. SQL is tied very closely with the relational model

1.8.1 Languages in SQL

1) Data Retrieval Language (DRL) -- retrieves data from the server.


Key word -- select

2) Data Definition Language (DDL) -- defines the structure of the objects in


the database.
Key words
i) Create ---- creates a new object in the database.
ii) Alter ---- changes the structure of the objects
iii) Drop ---- removes the object from the database
iv) Truncate ---- removes all the records and retains the
structure of the Table
v) Rename ---- changes the name of the table

3) Data Manipulation Language (DML) -- Manipulates the existing records


Key words
i) Insert ----- adds a new record or row to the table
ii) Update ----- changes the values of the existing records
iii) Delete ----- removes one or more records from the table.
iv) Merge ----- optionally insert or update data in a table

-5-
4) Transaction Control Language (TCL) Controls the transactions
Key words
i) Commit ----- saves the changes in the database.
ii) Rollback ----- undo the change made.
iii) Savepoint ----- intermediate buffer or a point between the
transactions
5) Data Control Language (DCL) Controls the database actions and data
access.
Key words
i) Grant ----- provide access or privileges on the database
objects to the users.
ii) Revoke ----- removes user access rights or privileges to the
database objects

1.9 Environments for communication


Environment or user interface plays a vital role in communication. If a person has
to communicate with others then he can use any one of the environments like
talk directly, send a mail, write a letter, call through mobile etc. To communicate
with the database server by the client, many front end tools are used and Oracle
Corporation supplies some environments or user interfaces such as sql*plus,
isql*plus and developer 2000 (D2K)

1.9.1 The SQL*PLUS Environment


SQL*PLUS is a command line interface. It is the user-friendly interactive SQL
interface to access databases. It allows the user to type the SQL statements and
execute directly against an Oracle database. SQL*Plus has the ability to format
database output, save often used commands and can be invoked from other
Oracle tools or from the operating system prompt.

-6-
Running SQL*Plus under Windows

To run the SQL*Plus command line program from Windows, click on the
button, Programs, Oracle – OraDB10g_Home1, Application Development and
then SQL*Plus. The SQL*Plus login screen as shown below will appear

Figure 1.2

In the User Name field, type in your Oracle username.


In the Password field, type your Oracle password.
In the Host String field, type in the name of the Oracle database to be connect
to.

Finally, click on the OK button to complete the Oracle log in process.


SQL*Plus will then establish a session with the Oracle DBMS and the
SQL*Plus prompt (SQL>) will appear. The following figure shows the results
of logging into Oracle using SQL*Plus:

-7-
Figure 1.3
In the Above figure we have two pieces of information.
First one is

This is the version of the client software. That is version is oracle 9i release 2
Next we have

This is the version of the Oracle Database. That is the database version is Oracle
10g release 2 and the edition is enterprise edition.
1.9.2 The iSQL*PLUS Environment
iSQL*Plus is a version of SQL*Plus that is delivered through a web browser.
iSQL*Plus enables you to use a web browser to connect to Oracle database and
perform the same actions as you would through the command line version of
SQL*Plus.
You can use iSQL*Plus to write SQL*Plus, SQL and PL/SQL commands to:
 Enter, edit, run and save SQL commands and PL/SQL blocks.
 Calculate, and print query results.
 List column definitions for any table.
 Access and copy data between databases.
 Perform database administration.

-8-
CHAPTER 2

2.0 WRITING BASIC SELECT STATEMENTS

The SELECT statement, that represents Data Retrieval Language (DRL) in SQL,
is the statement used to construct database queries. The SELECT statement is
not a standalone statement, which means that one or more additional clauses
(elements) are required for a syntactically correct query. In addition to the
required clauses, there are optional clauses that increase the overall functionality
of the SELECT statement. The SELECT statement is by far one of the most
powerful statements in SQL.

2.1 The SELECT Statement

The SELECT statement is used in conjunction with the FROM clause to extract
data from the database in an organized, readable format. The SELECT part of
the query is for selecting the data you want to see according to the columns in
which they are stored in a table. The FROM part of the query denotes the table
or tables from which the data is retrieved.
The syntax for a simple SELECT statement is as follows:

SELECT [* | DISTINCT | column1, column2,…………] FROM table_name;

The SELECT keyword in the above query is followed by a list of columns that you
want to display as part of the query output. The FROM keyword is followed by a
list of one or more tables from which you want to select data. The asterisk (*) is
used to denote that all columns in a table should be displayed as part of the
output. The DISTINCT option is to eliminate the display of duplicate records.

Notice that the columns following the SELECT are separated by commas.

-9-
Examples:
Selecting all the columns from the table
SQL> SELECT * FROM employees;

Selecting specific columns


SQL> SELECT employee_id, employee_name FROM employees;

Eliminating duplicate values


SQL> SELECT DISTINCT department_id FROM employees;

2.2 Capabilities Of SELECT Statement


Next let us explore the basic capabilities of the SELECT statement
1) Projection: Choose the columns in a table that are returned by the query.
2) Selection: Choose the rows in a table that are returned by the query.
3) Joining: Select data from different tables by specifying a link between
them.
Note:
1) SQL statements are case insensitive but the records are case sensitive.
2) SQL statements can be written in multiple lines.
3) Key words cannot be abbreviated.
4) All SQL statements are terminated by a semicolon ;
5) Optionally a slash / can be used to run the statements. But this / must be
the first character in a new line.

2.3 Defining a Column Alias


A column alias:
• Renames a column heading.
• Is useful with calculations.
• Immediately follows the column name (There can also be the optional AS
keyword between the column name and alias.).
• Requires double quotation marks if it contains spaces or special characters,
or if it is case-sensitive.
- 10 -
Example
SQL> SELECT employee_id emp_number, employee_name “Name”,
job as designation FROM employees;

Normally the alias name for the column will follow immediately after the column
name. The default display of the column alias will be in upper case. If the alias
name has to be case sensitive then enclose it within double quotes. Ex:
“Name”. Optionally can be specified using as. Ex: job as designation.
Note that the alias name will be applicable only for that query output. The
original name of the column will not be changed in the table.

2.4 Describing structure of the table: To find the structure of the table that is
to view the column names and their data types use describe command.
Syntax: DESCRIBE or DESC table_name

SQL> DESC dept

Figure 2.1

2.5 Limiting or restricting rows using selection


The WHERE clause allows you to filter the results from an SQL statement -
select, insert, update, or delete statement. A WHERE clause contains a
condition that must be met, and it directly follows the FROM clause. If the
condition is true, the row meeting the condition is processed.

- 11 -
Syntax:
SELECT column_list FROM table_name WHERE condition operator value.

Example: SQL> SELECT * FROM emp WHERE employee_name=’SCOTT’;

SQL> SELECT ename, salary FROM emp WHERE salary <= 3000;

SQL> SELECT * FROM emp WHERE comm. IS NOT null;

2.6 SQL Operators

An operator manipulates individual data items and returns a result. The data
items are called as arguments. Operators can be classified as
A) Arithmetic operators.
B) Comparison or Relational operators.
C) Logical operators.
D) Concatenate operator.

A) Arithmetic operators
These operators, just as the name implies, are used for arithmetic
computations.

Operator Description
+ Addition
- subtraction
* multiplication
/ division

Table 2.1
- 12 -
Calculate the salary after a raise of 100 for all the employees

Example1: SQL> SELECT ename, sal, sal+100 FROM emp;

Calculate the annual salary of all the employees

Example2: SQL> SELECT empno, ename, sal, sal*12 FROM emp;

Calculate the annual salary of all the employees after the raise of 100

Example 3:
SQL> SELECT employee_name, salary, (sal+100)*12 FROM employees;

Order of precedence: Multiplication, Division, Addition, Subtraction.

To override the above order use parenthesis.

- 13 -
B) Comparison operators
Comparison operators are used to compare one value or expression to
another

Operator Description Example


= Equality test. SELECT ENAME
"Employee" FROM EMP
WHERE SAL = 1500;

!=, <> Inequality test. SELECT ENAME FROM


EMP WHERE SAL != 5000;

> Greater than SELECT ENAME


"Employee", JOB "Title"
FROM EMP WHERE SAL >
3000;
< Less than SELECT * FROM PRICE
WHERE MINPRICE < 30;

>= Greater than or equal to SELECT * FROM PRICE


WHERE MINPRICE >= 20;

<= Less than or equal to SELECT ENAME FROM


EMP WHERE SAL <= 1500;

IN "Equivalent to any member of the given set of SELECT * FROM EMP


values" WHERE ENAME IN
('SMITH', 'WARD');
NOT IN Evaluates to FALSE if any member of the set is SELECT * FROM DEPT
NULL. WHERE LOC NOT IN
('NEW YORK', 'DALLAS');

[NOT] [Not] greater than or equal to x and less than or SELECT ENAME, JOB
BETWEEN x equal to y. FROM EMP WHERE SAL
and y BETWEEN 3000 AND
5000;

x [NOT] LIKE TRUE if x does [not] match the pattern y. Within y, SELECT * FROM EMP
y the character "%" matches any string of zero or more WHERE ENAME LIKE
characters except null. The character "_" matches '%E%';
any single character. Any character following
ESCAPE is interpreted literally, useful when y
contains a percent (%) or underscore (_).
IS [NOT] Tests for nulls. This is the only operator that should SELECT * FROM EMP
NULL be used to test for nulls. WHERE COMM IS NOT
NULL AND SAL > 1500;

- 14 -
Note:
All character and date records must be enclosed within single quotes.
When using like operator - (underscore) denotes one character and % denotes n
number of characters.
NULL is a value, which is not known or unassigned. It is not equal to zero or
white space. Null with anything the result will be NULL.

Examples:

Find the employees details who are having an E as the first character in
their name.
SQL> SELECT * FROM emp WHERE ename LIKE‘E%’;

Find the employees details who are having an E as the last character in
their name.

SQL> SELECT * FROM emp WHERE ename LIKE ‘%E’;

Find the employees details who are having an E anywhere in their name.

SQL> SELECT * FROM emp WHERE ename LIKE ‘%E%’;

Find the employees details who are having an E as the second character in
their name.

SQL> SELECT * FROM emp WHERE ename LIKE ‘_E%’;

- 15 -
C) Logical operators
These operators compare two conditions at a time to determine whether a
row can be selected for the output. When retrieving data using a SELECT
statement, you can use logical operators in the WHERE clause, which
allows you to combine more than one condition.
Operator Description Example
NOT Returns TRUE if the following condition is FALSE. SELECT * FROM EMP WHERE
Returns FALSE if it is TRUE. If it is UNKNOWN, it deptno NOT in (10,20)
remains UNKNOWN.
SELECT * FROM EMP WHERE
NOT (sal BETWEEN 1000 AND
2000)
AND Returns TRUE if both component conditions are SELECT * FROM EMP WHERE
TRUE. Returns FALSE if either is FALSE; job='CLERK' AND deptno=10
otherwise returns UNKNOWN.
OR Returns TRUE if either component condition is SELECT * FROM emp WHERE
TRUE. Returns FALSE if both are FALSE. job='CLERK' OR deptno=10
Otherwise, returns UNKNOWN.

Table 2.3
D) Concatenate operator
The concatenation operator will concatenate columns or character strings
to other columns. It is represented by two vertical bars (||).

Operator Description Example

|| Concatenates character SELECT 'The Name of the employee


strings or columns is: ' || ENAME FROM EMP;
Select empno||’ ‘||ename from emp;

Table 2.4

- 16 -
2.7 Sorting the output
The order of the rows that are returned by the query is undefined. To sort the
result of a query, use order by clause. The order by clause must be the last
clause in a select query. The default mode of sorting is ascending order. Use
DESC for descending order.

Examples:
SELECT * FROM emp ORDER BY salary;
SELECT * FROM emp WHERE deptno=10 ORDER BY hiredate desc;

Sorting data using multiple columns:


You can sort query results by more than one column. In the ORDER BY clause
specify the column names and separate the column names using commas. It
you want to reverse the order of a column specify DESC after its name

Examples:
SQL> SELECT ename, deptno, sal FROM emp
ORDER BY deptno, sal;

SQL> SELECT ename, deptno, sal FROM emp


ORDER BY deptno, sal desc;

- 17 -
EXERCISES
1) Show the structure of the EMP table. Select all the data from the EMP
table.
2) Write a query to display the last name, job, hiredate and the employee
number for each employee.
3) Write a query to display unique jobs from the EMP table.
4) Display the last name concatenated with the job separated by a comma
and space and name the column Employee and Title.
5) Write a query to display the name and salary of employees earning more
than 2,000.
6) Write a query to display the employee name and department number for
employee number 7782.
7) Display the name and salary of all employees whose salary is not in range
of 1300 and 2,000.
8) Write a query to display all the details of employee ‘Blake’.
9) Display the name, job and hiredate of employees hired between February
20, 1980 and May1,1981. Order the query in ascending order of hiredates.
10) Display the name and department number of all employees in department
number 20 and 30 in alphabetical order by name.
11) List the name and salary of employees who earn between 3,000 and
2,000. Label the columns Employee and Monthly Salary, respectively.
12) Display the name and hiredate of every employee who had hired in the
year 81.
13) Display the name and hiredate of the employees whose name starts with
‘M’.
14) Display the name and job of all employees who do not have a manager.
15) Display the name, Salary, and Commission for all employees who earn
commission. Sort data in descending order of salary and commissions.
16) Display the details of the employees who earn a commission.
17) Display the name, job and salary for all employees whose job is salesman
or clerk and whose salary is not equal to $2,500,$3,500 or $7,000.

- 18 -
CHAPTER 3
3.0 SQL FUNCTIONS

Functions are a powerful feature in SQL. They can be used to do the following
 Perform calculations on data
 Modify individual data items.
 Manipulate output for group of rows.
 Format dates and number for display.
 Convert column data types.

3.1 Types of Functions


Functions are broadly classified into two.1) Single row functions and 2) multiple
row or group or aggregate functions.

3.2 Single row functions


Single row functions act on each row that is returned by the query and gives one
result per row.
 Single row functions can manipulate data items.
 Accepts arguments and return one value.
 Can modify data type.
 Arguments can be a column or expression.
 Can be nested.
 Can be used in the select list, where clause etc.

3.2.1 Types of Single row functions


i) Character functions: Accept character data as input and can return both
character and numeric values. Character functions can be classified into the
following:
 Case Manipulation Functions.
 Character Manipulation Functions.

- 19 -
A) Case Manipulation Functions.
These functions convert case for character string. They accept only one
argument.
Types of Case Manipulation Functions:
UPPER: Converts Lower case string to Upper case.
LOWER: Converts Upper case string to Lower case.
INITCAP: Converts the first letter of the string to upper case and rest in lower
case.
Examples:
SQL> SELECT UPPER (ename) FROM emp; Output: SCOTT
SQL> SELECT LOWER (ename) FROM emp; Output: scott
SQL> SELECT INITCAP (ename) FROM emp; Output: Scott

B) Character Manipulation Functions: These functions manipulate character


string.
Types of Character Manipulation Functions
1) CONCAT: Joins values together (only two arguments can be passed)
SQL> SELECT CONCAT (‘hello’,’students’) FROM dual; output hellostudents
SQL> SELECT CONCAT (ename,job) FROM emp; output scottmanager.
2) SUBSTR: Returns 'n' number of characters from 'string_value' starting from
the 'm' position. Accepts 3 arguments
Syntax substr (string, n, m)
SQL> SELECT SUBSTR (‘hello’, 1, 3) FROM dual; output hel
SQL> SELECT SUBSTR (‘hello’, 2, 3) FROM dual; output ell
3) LENGTH: Displays the length of the given string
SQL> SELECT LENGTH (‘hello’) FROM dual; output 5
SQL> SELECT LENGTH (ename) FROM emp; output 4 (for KING)
4) INSTR: Finds the numeric position of the named character
SQL> SELECT INSTR (‘hello’, ‘o’) FROM dual; output 5

- 20 -
5) LPAD: Returns 'string_value' left-padded with 'pad_value’. The length of the
whole string will be of 'n' characters.
SQL> SELECT LPAD (salary,’*’, 10) FROM emp; output ******4000

6) RPAD: Returns 'string_value' right-padded with 'pad_value’. The length of the


whole string will be of 'n' characters.
SQL> SELECT RPAD (salary,’*’, 10) FROM emp; output 4000******

ii) Number functions: Number functions accept numeric input and return
numeric values.
1) ROUND: Rounds off the numeric value to the given decimal places.
Round(x,y) Round off value of the number 'x' up to the number 'y' decimal places
If y is negative, the numbers to left of the decimal point are rounded
SQL> SELECT ROUND (54.926, 2) FROM dual; output 54.93
SQL> SELECT ROUND (54.926,-1) FROM dual; output 50
2) TRUNC: Truncates value of number 'x' up to 'y' decimal places
SQL> SELECT TRUNC (54.926, 2) FROM dual; output 55
3) MOD: Returns the remainder of ‘x’ divided by ‘y’
SQL> SELECT MOD (1600, 300) FROM dual; output 100

What is a DUAL Table in Oracle?


This is a single row and single column predefined table provided by oracle. The
owner of this table is sys user and all users can access this table. This is used to
perform mathematical calculations without using a table.

iii) Date Functions:


Oracle stores dates in an internal format:
Century, Year, Month, Day, Hours, minutes, Seconds.
The default format for display and input is DD-MON-RR.

1) SYSDATE: sysdate is a function which returns the current server date.


SQL> SELECT sysdate FROM dual;
- 21 -
2) MONTHS_BETWEEN (date d1, date d2): Returns the number of the month
between the dates d1 and d2
SQL> SELECT months_between (sysdate, hiredate) FROM emp;
3) ADD_MONTHS (date d1, n): Add n number of months to the date d1.
SQL> SELECT add_months (sysdate, 6) FROM dual;
4) NEXT_DAY (date ‘d1’, ‘day’): Parameters: A date d1 and a day of the week.
It returns the date after d1 whose day of the week is day
SQL> SELECT next_day (sysdate,’friday’) FROM dual;
The result will be the date of the next Friday.
5) LAST_DAY (date ‘d1’): Returns the date that corresponds to the last day of
the month in d1
SQL> SELECT last_day (sysdate) FROM dual;
6) TRUNC (date,’format’): Returns the date truncated to the unit specified by the
format
SQL> SELECT trunc (sysdate, ‘month’ or ‘year’) FROM dual;
7) ROUND (date): Returns the date rounded to the unit specified by the format
SQL> SELECT round (sysdate, ‘month’ or ‘year’) FROM dual;

Arithmetic with dates: Since the date is stored as a number in oracle database
arithmetic operations can be performed with dates.
Operation Result Description
Date+number Date Adds a number of days to the date
Date-number Date Subtracts a number of days from
the date
Date-Date Number of days Subtracts one date from another
Date+number/24 Date Adds a number of hours to a date

Table 3.1
Example:
SQL> SELECT last_name, (SYSDATE-hire_date)/7 AS WEEKS
FROM employees WHERE department_id = 90;

- 22 -
iv) Conversion Functions: These are functions that help us to convert a value
form one data type to another.
Three different types of conversion functions are: a) to_char, b) to_date,
c) to_number
a) TO_CHAR: Converts Numeric and Date values to a character string value
Using the TO_CHAR Function with Dates: Converts a date value to character
Syntax to_char (date,’format_model’)
The format model:
• Must be enclosed by single quotation marks.
• Is case sensitive.
• Can include any valid date format element.
• Is separated from the date value by a comma.
SELECT last_name, TO_CHAR (hire_date, 'DD Month YYYY') FROM
employees;
Elements of Date format models

Element Result
YYYY Full year in numbers
YEAR Year spelled out
MM Two digit value for month
MONTH Full name of the month
MON Three letter abbreviation of month
DY Three letter abbreviation of the day of the week
DAY Full name of the day
DDD or DD or D Numeric day of the year or month or week
TH Ordinal number ex 7th
DDSPTH Date spelled out in ordinal number

Table 3.2

- 23 -
Using the TO_CHAR Function with Numbers: Converts a number to character
Syntax to_char (number,’format_model’)
There are some of the format elements that you can use with the TO_CHAR
function to display a number value as a character
Element Result
9 Represents a number
0 Forces a Zero to be displayed
$ Places a floating dollar sign
L Represents the local currency
. Prints a decimal point
, Prints a comma as thousands
indicator

Table 3.3
SQL> SELECT TO_CHAR(salary, '$99,999.00') SALARY FROM employees
WHERE last_name = 'Ernst';

b) TO_DATE: The Oracle TO_DATE sql function is used to convert a TEXT


representation of a date into an Oracle DATETIME value.

Syntax : to_date (‘date in string format’,’ format’);


SQL> SELECT to_date (‘19/dec/2012’,’dd/mon/yyyy’) FROM dual;
Output: 19-DEC-12

c) TO_NUMBER: converts a string to a number.

The syntax for to_number function is: to_number( string1, format)

string1 is the string that will be converted to a number.


format is optional. This is the format that will be used to convert string1 to a
number.

SQL> SELECT to_number(‘678.980’) FROM dual;

- 24 -
v) General Functions: The general functions work with any data type and are
mainly used to handle null values.
The Oracle general functions are:
1) NVL Function
The syntax of NVL function is NVL (expr1, expr2)
The NVL function takes two arguments as its input. If the first argument is NULL,
then it returns the second argument otherwise it returns the first argument.

SQL> SELECT ename, NVL (comm, 0) FROM emp;

2) NVL2 Function
The syntax of NVL2 function is NVL2 (expr1, expr2, expr3)
The NVL2 function takes three arguments as its input. If the expr1 is NOT NULL,
NVL2 function returns expr2. If expr1 is NULL, then NVL2 returns expr3.

SQL> SELECT ename, nvl2 (comm, comm, sal) FROM emp;

3)NULLIF Function: The NULLIF function compares the two expressions and
returns NULL if they are equal otherwise it returns the first expression.
The Syntax of NULLIF function is NULLIF (expr1, expr2)

SQL> SELECT NULLIF (length (first_name), length (last_name)) FROM emp;


4) COALESCE Function: The COALESCE function takes n number of
arguments as its input and returns the first NOT-NULL argument

The Syntax of COALESCE function is COALESCE (expr1, expr2, expr3...)

SQL> SELECT COALESCE (sal, comm., 0) FROM emp;

vi) Conditional expressions: These expressions provide the use of IF-THEN-


ELSE logic within a SQL statement

 two methods are available:

 CASE expression
 DECODE function

- 25 -
Case expression:
A simple CASE expression takes the following format
CASE expr WHEN comparison_expr1 THEN return_expr1
WHEN comparison_expr2 THEN return_expr2
WHEN comparison_exprn THEN return_exprn
ELSE else_expr
END
Example
SQL> SELECT last_name, job_id, salary,
CASE job_id WHEN 'IT_PROG' THEN 1.10*salary
WHEN 'ST_CLERK' THEN 1.15*salary
WHEN 'SA_REP' THEN 1.20*salary
ELSE salary
END
FROM employees;
DECODE Function: Facilitates conditional inquiries by doing the work of a
CASE expression or an IF-THEN-ELSE statement:
Syntax: DECODE(col|expression, search1, result1
, search2, result2
, default)
Example
SQL> SELECT last_name, salary,
DECODE (TRUNC(salary/2000, 0), 0, 0.00,
1, 0.09,
2, 0.20,
3, 0.30,
4, 0.40,
5, 0.42,
6, 0.44,
0.45) TAX_RATE
FROM employees;

- 26 -
3.3 Multiple Row Functions or Group Functions
Group functions operate on sets of rows and returns one result per group or set.
These sets may comprise the entire table or the table split into groups

Types of Group Functions


 Avg
 Count
 Max
 Min
 Sum etc;
Example:
SQL> SELECT AVG (salary), MAX (salary), MIN (salary), SUM (salary),
COUNT (salary) FROM emp WHERE job_id LIKE '%REP%';

SQL> SELECT MIN (hire_date), MAX (hire_date) FROM emp;

Note:
 Group functions ignore null values.
 Avg and sum can be used only for numeric data.
COUNT (*) returns the no. of rows in the table

SQL> SELECT COUNT (*) FROM emp;

- 27 -
3.3.1 Creating Groups of Data
At times, you need to divide the table information into smaller groups. For
example you need to find the total salary earned in each department. This can be
done by including a GROUP BY clause in the select statement. The GROUP BY
clause will gather all of the rows together that contain data in the specified
column(s) and will allow aggregate functions to be performed on one or more
columns.

Syntax
SELECT column1, group_function (column2) FROM table_name
GROUP BY "column-list";
Example:
SQL> SELECT deptno, SUM (sal) FROM emp
GROUP BY deptno;

3.3.2 Grouping Multiple columns: Sometimes you need to retrieve the results
for groups within groups. For example to find the total salary of that is paid to
each job within a department.
SQL> SELECT department_id as dept_id, job_id, SUM (salary)
FROM employees
GROUP BY department_id, job_id;
Note: The columns which are listed in the select list must be included in the
GROUP BY clause.

To restrict the rows before grouping use WHERE clause before GROUP BY
clause.
SQL> SELECT job_id, SUM (salary)
FROM employee WHERE job_id NOT LIKE '%REP%'
GROUP BY job_id;

- 28 -
To restrict the rows after grouping use HAVING clause.
The HAVING clause allows you to specify conditions on the rows for each group
- in other words, which rows should be selected will be based on the conditions
you specify. The HAVING clause should follow the GROUP BY clause
When you use the HAVING clause, the Oracle server restricts groups as follows:
• Rows are grouped.
• The group function is applied.
• Groups matching the HAVING clause are displayed.

Syntax:
SELECT column, group_function FROM table_name
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition];

Example:
SQL> SELECT department_id, MAX (salary) FROM employees
GROUP BY department_id
HAVING MAX (salary)>10000;

- 29 -
EXERCISES

1) Write a query to display the current date. Label the column DATE.
2) For each employee, display the employee number, name, salary and
salary increased by 15% and expressed as a whole number. Label
the column New Salary.
3) Write a query that displays the employee’s name with the first letter
capitalized and all other letters lowercase and the length of the name
for all employees.
4) Display the employee’s name, and calculate the number of months
between today and the date the employees hired. Label the column
MONTHS_WORKED.order your results by the number of months
employed.
5) Create a query to display the name and salary for all employees.
Format the salary to be 15 characters long, left-padded with *.Label
the column SALARY.
6) Display the last name, hiredate and day of the week on which the
employee started.
7) Display each employee's name, hiredate and salary review date,
which is the first Monday after six months of service. Label the
column REVIEW. Format the dates to appear in the format similar to
"Monday, the Thirty-First of July, 2000."
8) Write a query that displays the employee's name and commission. If
an employee does not earn commission, put “No Commission.".

- 30 -
9) Using a DECODE function; write a query that displays the grade of
all employees based on the value of the column JOB, as per the
following data.
JOB GRADE
PRESIDENT A
SALESMAN B
IT_PROG C
SA_REP D
ST_CLERK E
None of the above O

10) Rewrite the statement in the above question using CASE.


11) Find the highest, lowest, sum, average salary of all the employees.
12) Find the number employees working in each department.
13) Write a query to display the maximum, minimum and average
salaries of all the employees in each job.
14) Find the number of employees having the same job.
15) Find out the number of managers without listing them.
16) Find the difference between the lowest and the highest salaries.
17) Find the hiredate date of senior most and junior most employees
18) List the manager id and the amount of lowest paid employee for that
manager.

- 31 -
CHAPTER 4

4.0 USING SUB QUERIES TO SOLVE PROBLEMS

Sub query or Inner query or Nested query is a query in a query. A subquery is


usually added in the WHERE Clause of the sql statement or in the create table
command. Most of the time, a subquery is used when you know how to search
for a value using a SELECT statement, but do not know the exact value.
Subqueries are an alternate way of returning data from multiple tables.
For example you need to find the employees working with SCOTT

SQL> SELECT * FROM emp


WHERE deptno= (SELECT deptno FROM emp
WHERE ename=’SCOTT’);
In the above example you have two queries. SELECT * FROM emp WHERE
deptno= is the main query or the outer query and (SELECT deptno FROM emp
WHERE ename=’SCOTT’) is the subquery or the inner query. The inner query
executes first and returns the department number of SCOTT. Based on the result
of the inner query the outer query executes.
Always enclose the subquery within parenthesis.
Inner query can retrieve data from the same table or another table.

4.1 Types of Subqueries


1) Single row subqueries and
2) 2) multiple row subqueries.

4.1.1 Single row sub queries: Single row sub queries returns only one row.
Single row subqueries can be used only along with the comparison operators like
=, <, >, >=, <=.

- 32 -
Subquery Syntax
SELECT select_list FROM table
WHERE expr operator (SELECT select_list FROM table);
Examples
SQL> SELECT last_name, salary FROM employees
WHERE salary > (SELECT salary FROM employees
WHERE last_name = 'Abel');

SQL> SELECT last_name, job_id, salary FROM employees


WHERE job_id = (SELECT job_id FROM employees
WHERE employee_id = 141)
AND salary > (SELECT salary FROM employees
WHERE employee_id = 143);
The subquery (inner query) executes once before the main query (outer query).
The result of the subquery is used by the main query.

4.1.2 Multiple-Row Subqueries: Subqueries that return more than one row are
called as multiple row subqueries. Use multiple row operators with the multiple
row subqueries.
List of multiple row operators

Operator Meaning
IN Equal to any member in the list
ANY Compare value to each value returned by the subquery
ALL Compare value to every value returned by the subquery
>ANY Greater than the minimum value returned by the subquery
<ANY Lesser than the maximum value returned by the subquery
>ALL Greater than the maximum value returned by the subquery
<ALL Lesser than the minimum value returned by the subquery

Table 4.1

- 33 -
Examples
SQL> SELECT employee_id, last_name, job_id, salary FROM employees
WHERE salary < ANY (SELECT salary FROM employees
WHERE job_id = IT_PROG');

In this example, the subquery SELECT salary FROM employees


WHERE job_id = IT_PROG’ returns the salary earned by all the IT
PROGRAMERS. Here Single row comparison operators cannot be used. To
compare multiple values multiple row comparison operators must be used.

SQL> SELECT employee_id, last_name, job_id, salary FROM employees


WHERE salary < ALL (SELECT salary FROM employees
WHERE job_id = 'IT_PROG')
AND job_id <> 'IT_PROG';

Note: If the subquery returns a null value then the main query will not return any
rows.

- 34 -
EXERCISES
1) Find the employees whom are working with ‘Allen’.
2) Write a query to find the employees who earn more than the average
salary.
3) Find the employees who are working in ‘New York’.
4) Find the details of the senior most employee.
5) Write a query to find the details of the employees who are reporting to
SMITH.
6) Write a query to find the name, job and salary of the employees who work
as ‘clerk’.
7) Write a query to find the employees who earn more than the highest paid
salesman.
8) Give a list of job types for which the minimum salary exceeds the
company average.
9) Find the details of the employees who work in a department with any
employee
whose last name contains a “T”
10) Find the name, department number and job of the employees who are
working in ‘ADMIN’ department.

11) Find the departments having more than 3 employees.

12) Find the job which pays the highest salary.

- 35 -
CHAPTER 5

5.0 CONSTRAINTS
Constraints are used to apply business rules for the database tables. They
prevent invalid data entry into the table. They Prevent deletion of rows from a
table if there are dependencies. The rules are enforced when the data is inserted
or updated or deleted.
Constraints can be defined in two ways

 The constraints can be specified immediately after the column


definition. This is called as column level constraint.
 The constraints can be specified after all the columns are defined.
This is called table-level constraint.

The following are the types of constraints

Constraint Description
NOT NULL Column cannot have a null value
UNIQUE Column cannot have duplicate values
PRIMARY KEY Uniquely identifies each row of the table
FOREIGN KEY Establishes a relationship between the column and the
primary key column.
CHECK Specifies a condition that must be true.

Table 5.1
Note:
Not null constraint cannot be defined at the table level.
Constraints can be defined at the time of table creation or after the table has
been created.
More than one constraint can be defined for a single column.
Only one primary key can be defined for a table.

- 36 -
A single primary key can be referred by more than one foreign key either from
the same table or from the different tables.
All constraints are stored in the data dictionary.
Name of the constraint must be unique in a schema.
NOTE:If name is not specified while defining a constraint, then Oracle server will
generate a name with the format SYS_Cn where n is a unique number.

General Syntax:
Column name data type [CONSTRAINT constraint_name] constraint_type,

5.1 THE NOT NULL CONSTRAINT


By default all columns in a table can contain null values. If you want to ensure
that a column must always have a value, i.e. it should not be left blank, then
define a NOT NULL constraint on it. NOT NULL constraint ensures that null
values are not permitted for the column.

Example 1
When creating the table.
SQL> CREATE TABLE employees (employee_id number (5),
last_name varchar2 (20) CONSTRAINT lastname_e_nn NOT NULL,
Manager_id number (5));

Example 2:
After creating the table
SQL> ALTER TABLE emp MODIFY last_name CONSTRAINT name_e_nn NOT
NULL;

5.2 THE UNIQUE KEY CONSTRAINT


Ensures the uniqueness of the rows in the column. That is no duplicates are
allowed to that column (allows null values).

- 37 -
Example 1:
When creating the table.
SQL> CREATE TABLE emp (empno number (5), ename varchar2
(20)CONSTRAINT constraint ename_e_un UNIQUE,
Manager_id number (5));
Example 2:
After creating the table
SQL> ALTER TABLE employees ADD CONSTRAINT ename_e_un
UNIQUE (last_name);

5.3 THE PRIMARY KEY CONSTRAINT


Primary key uniquely identifies the records or rows in table. In other words no
null vales and duplicates are allowed for a column which is declared with a
primary key. Table which is declared with a primary key is called the Master table
or Parent table. There can be only one primary key for a table.

Example 1:
When creating the table.
SQL> CREATE TABLE emp (empno number CONSTRAINT empno_e_pk
PRIMARY KEY, last_name varchar2 (20) CONSTRAINT lastname_e_un
UNIQUE, Manager_id number (5));

Example 2:
After creating the table
SQL> ALTER TABLE employees ADD CONSTRAINT empid_e_pk
PRIMARY KEY (employee_id);

5.4 THE FOREIGN KEY CONSTRAINT


It is a rule that is defined on a column or set of columns in one table that
guarantees that the values in that column match the values in a column in a
related table (the referenced value).It is also called as referential integrity
- 38 -
constraint. It also includes the rules that dictate what types of data manipulation
are allowed on referenced values and how these actions affect dependent
values. The referenced table is called the parent table while the table with the
foreign key is called the child table. The foreign key in the child table will
generally reference a primary key in the parent table.

The rules associated with referential integrity are:


 Set to Null: When referenced data is updated or deleted, all associated
dependent data is set to NULL.
 Set to Default: When referenced data is updated or deleted, all associated
dependent data is set to a default value.
 Cascade: When referenced data is updated, all associated dependent
data is correspondingly updated. When a referenced row is deleted, all
associated dependent rows are deleted.
 No Action: Disallows the update or deletion of referenced data. Oracle
uses No Action as its default action.
A foreign key can be defined in either a CREATE TABLE statement or an ALTER
TABLE statement.

Example 1: No Action

While creating the table:


SQL> CREATE TABLE employees (emp_id number (5) CONSTRAINT
empid_e_pk PRIMARY KEY,last_name varchar2 (20) CONSTRAINT
lastname_e_un UNIQUE,
Manager_id number (5), Department_id number (3) CONSTRAINT
depid_e_fk REFERENCES departments (department_id));

In the above example the department_id column of the employees table refers
the values in the department_id column of the departments table where a primary
key is declared.

- 39 -
After creating the table:
SQL> ALTER TABLE employees ADD CONSTRAINT depid_e_fk
FOREIGN KEY (department-id)
REFERENCES departments (department_id);

Example 2: Set NULL

SQL> CREATE TABLE employees (employee_id number (5),


last_name varchar2 (20) Manager_id number (5),
Department_id number (3) CONSTRAINT depid_e_fk REFERENCES
departments (department_id)
ON DELETE SET NULL);

SQL> ALER TABLE employees ADD CONSTRAINT depid_e_fk FOREIGN KEY


(department_id) REFERENCES departments (department_id)
ON DELETE SET NULL;

Example 3: CASCADE
SQL> CREATE TABLE employees (employee_id number (5), last_name
varchar2 (20),Manager_id number (5), Department_id number (3)
CONSTRAINT depid_e_fk REFERENCES departments
(department_id) ON DELETE CASCADE);

SQL> ALTER TABLE employees ADD CONSTRAINT depid_e_fk


FOREIGN KEY (department_id) REFERENCES departments (department_id)
ON DELETE CASCADE;

5.5 THE CHECK CONSTRAINT


Oracle check constraint insures that updated or inserted values meet a specific
condition. If the Oracle check constraint condition returns as TRUE when you use
- 40 -
Oracle check constraint, the value is accepted by the constraint. If Oracle check
constraint returns the condition as FALSE, the value is rejected.

Example:
SQL> CREATE TABLE employees (employee_id number (5),
last_name varchar2 (20), Manager_id number (5),
Department_id number (3),
sal number (6) CONSTRAINT sal_e_ck CHECK (sal>1000));

In this example the rule is that the salary of all the employees must be above
1000.So if a value less than 1000 is entered then it will be rejected.

After creating the table


SQL> ALTER TABLE employees ADD CONSTRAINT sal_e_ck
CHECK (sal>1000);

To view the constraints that are declared for a table use the following data
dictionary
SQL> SELECT * FROM user_constraints WHERE table_name=’EMPLOYEES’;

To view the column names for which the constraints are declared
SQL> SELECT * FROM user_cons_columns
WHERE table_name=’EMPLOYEES’
To drop the constraints
SQL> ALTER TABLE table_name DROP CONSTRAINT constraint_name;

SQL> ALTER TABLE employees DROP CONSTRAINT sal_e_ck;


5.6 Constraint Guidelines: Always name a constraint while declaring it or the
Oracle server generates a name with the SYS_Cn format.Ex: SYS_C450679.
USE THE FOLLOWING STANDARD NAMING CONVENTIONS
- 41 -
PRIMARY KEY ----- PK
FOREIGN KEY ----- FK
NOT NULL ---- NN
CHECK ---- CK
UNIQUE ----- UK

EXERCISES

1) Create a table emp. Add a PRIMARY KEY constraint to the emp table on
the empno column. The constraint should be named at the time of
creation.
2) Add a foreign key constraint on the deptno column of the emp table.
3) Add a constraint to the comm.. Column that ensures that a commission
value is greater than ZERO.
4) Confirm that the constraints that were added through the data dictionary.
5) Disable the constraint which you have created in question no. 1
6) Enable the above constraint.
7) Drop the primary key constraint. What happens?

- 42 -
CHAPTER 6

6.0 RETRIEVING DATA FROM MULTIPLE TABLES


In a relational database system, the total required data might not be available in
a single table. Generally the data is scattered. Because, if the total data is stored
in a single table it will lead to a lot of redundancy. So, often we have to bring the
data of two or more tables together to get the required information.
The act of combining two or more tables in such a way that you retrieve values
from the columns of all the tables, to get the required data is called as joining.
The query's select list can select any columns from any of these tables. If any of
these tables have a column name in common, you must qualify with the table
names all references to these columns throughout the query to avoid ambiguity.
Most join queries contain WHERE clause conditions that compare two columns,
each from a different table. Such a condition is called a join condition. To
execute a join, Oracle combines pairs of rows, each containing one row from
each table, for which the join condition evaluates to TRUE. The columns in the
join conditions need not also appear in the select list.

Example tables

EMPLOYEES

Table 6.1

- 43 -
DEPARTMENTS

Table 6.2

6.1 Types of joins

6.2 Cross Join or Cartesian products


Cross Joins produce results that consist of every combination of rows from two or
more tables. That means if table A has 3 rows and table B has 2 rows, a
CROSS JOIN will result in 6 rows. There is no relationship established between
the two tables you literally just produce every possible combination. All rows in
the first table are joined to all rows in the second table A cross join will be the
result of a query where a join condition is omitted or invalid.

Example:
SQL> SELECT employee_id, last_name, department_id, department_name
FROM employees, departments;

SQL> SELECT employee_id, last_name, department_id, department_name


FROM employees cross join departments;

In the above examples two tables are joined and no join condition is specified.
The result will be a Cartesian product.

- 44 -
6.3 Equi Joins: The Join condition specified determines what type of join it is.
When you relate two tables on the join condition by equating the columns with
equal (=) symbol, then it is called an Equi-Join. Frequently a primary key and
foreign key relationship is used in this type of joins.

Examples:
To get the department name of an employee from the departments table, you
need to compare the department_id column in the employees table with the
department_id column of the departments table.

SQL> SELECT employee_id, last_name, department_name, location_id


FROM employees, departments
WHERE employees.department_id=departments.department_id;

Output:

Table 6.3

SQL> SELECT employee_id, last_name, department_name,


department_id, location_id
FROM employees, departments
WHERE employees.department_id=departments.department_id;

In the above example we have department_id column common to both the


tables. If this column is listed in the select list then it results in error since the
department_id column is ambiguously defined. To avoid such error the common
columns must be qualified with table name.

- 45 -
So the query should be
SQL> SELECT employee_id, last_name, department_name,
location_id, employees.department_id
FROM employees, departments
WHERE employees.department_id=departments.department_id;

6.3.1 Using table Aliases: While joining the table we have to qualify the
columns that are in more than one table using the table name. If table name is
lengthy this process could be very tedious. Table alias is a short name that can
be used to refer to the table name in the query. Qualifying the columns with table
name or alias improves the query performance.

Example:
SQL> SELECT e.employee_id, e.last_name, d.department_name,
d.location_id, e.department_id
FROM employees e, departments d
WHERE e.department_id=d.department_id;

Here ‘e’ is the alias to table employees and ‘d’ is the alias for departments.
Throughout the query table employees can be referred using the alias e and
departments table using alias d. As the purpose of using an alias is to shorten
the reference to table, alias is generally very short. Also remember alias is
available only in the query in which it is created.

6.4 Creating Natural Joins:


• Another method for an equi join
• The NATURAL JOIN clause is based on all columns in the two tables that have
the same name.
• It selects rows from the two tables that have equal values in all matched
columns.
- 46 -
• If the columns having the same names have different data types, an error is
returned.

Example:
SQL> SELECT department_id, department_name, location_id, city
FROM departments NATURAL JOIN locations;

6.5 Creating Joins with the USING Clause


• If several columns have the same names but the data types do not match,
natural join can be applied by using the USING clause to specify the columns
that should be
used for an equijoin.
• Use the USING clause to match only one column when more than one column
matches.
• Do not use a table name or alias in the referenced columns.
• The NATURAL JOIN and USING clauses are mutually exclusive.

Example:
SQL> SELECT e.employee_id, e.last_name,d.location_id, department_id
FROM employees e JOIN departments d
USING (department_id);

6.6 Retrieving Records with the ON Clause

SQL> SELECT e.employee_id, e.last_name, e.department_id,


d.department_id, d.location_id
FROM employees e JOIN departments d
ON (e.department_id = d.department_id);

- 47 -
6.7 Non Equi Joins
Non equi joins is used to return result from two or more tables where exact join is
not possible. In other words a non equi join uses an operator other than equal to
operator.

EMPLOYEES

Table 6.4
JOB_ GRADES

Table 6.5

Consider the above tables. We have employees table and job_grades table. The
job_grades table contains grade and their low salary and high salary. Suppose
you want to find the grade of employees based on their salaries then you can use
NON EQUI join.

SQL> SELECT e.last_name, e.salary, j.grade_level FROM employees e,


job_grades j WHERE e.salary BETWEEN j.lowest_sal AND j.highest_sal;

- 48 -
OUTPUT

Table 6.7

6.8 Self Joins : A self join is a join of a table to itself. This table appears twice in
the FROM clause and is followed by table aliases that qualify column names in
the join condition. To perform a self join, Oracle combines and returns rows of
the table that satisfy the join condition.

For example the following query returns employee names and their manager
names for whom they are working.

SQL> SELECT e.employee_id, e.last_name, m.last_name “Manager” FROM


employees e, employees m
WHERE e.manager_id=m.employee_id;

6.9 Joining More Than Two Tables


Just like how two tables are joined, more than two tables can also be joined to
get the required information. For example, in the above queries we retrieved
information about employees and departments alone. What if we want to get
name of the location and not just the location id? Then we have to use locations
table along with employees and departments tables.

- 49 -
LOCATIONS

Table 6.8
Example:
SQL> SELECT e.employee_id, e.last_name, d.department_id,
d.department_name,
d.location_id, l.city
FROM employees e, departments d, locations l
WHERE e.department_id= d.department_id
AND d.location_id=l.location_id

To join n tables together, you need a minimum of n–1 join conditions. For
example, to join three tables, a minimum of two join conditions are required.

6.10 Outer joins:


When two tables are joined, only the rows that contain the common values are
selected. That means if the employees and the department tables are joined, you
get the details of departments which have a corresponding department_id in the
employees table. If an employee had not been allotted a department yet then his
details will not be listed in the output since no matching can be found. To include
this outer joins are used. An outer join returns all rows that satisfy the join
condition and also returns some or all of those rows from one table for which no
rows from the other satisfy the join condition.
• You use an outer join to see rows that do not meet the join condition.
• The outer join operator is the plus sign (+).
• Specify the (+) sign to the table column which is lacking values.

- 50 -
Example
DEPARTMENTS

Table 6.9
EMPLOYEES

Table 6.10
Ps: There are no employees in department no 190.

SQL> SELECT e.last_name, e.department_id, d.department_name


FROM employees e, departments d
WHERE e.department_id(+) = d.department_id ;

- 51 -
OUTPUT

Table 6.11

EXERCISES

1) Write a query to display the name, job, salary, department name and the
department number of all the employees.
2) Display the name, hiredate, salary, department name and the department
number of all the employees who work in New York.
3) Your next task is to find the manager names of each employee. Write a
query to display the employee id, employee name, manager id and the
manager name of all the employees.
4) Modify the above query to display the name, job, salary, department
name and the department number of all the employees. The query should
include the employee ‘KING’ also who is having no manager.

5) Display the name, job, salary and the salary grade of each employee

- 52 -
CHAPTER 7

7.0 CREATING AND MANAGING TABLES


Tables are the basic unit of data storage in an Oracle database. Data is stored in
rows and columns. You define a table with a table name (such as employees)
and set of columns. You give each column a column name (such as
employee_id, last_name, and job_id), a data type (such as VARCHAR2, DATE,
or NUMBER), and a width. The width can be predetermined by the data type, as
in DATE. If columns are of the NUMBER data type, define precision and scale
instead of width. A row is a collection of column information corresponding to a
single record.

Before a table is created the following factors of a table are to be finalized.


* What data table is supposed to store?
* The name of the table. It should describe the content of the table.
* What are the columns that table should contain.
* The name, data type and maximum length of each column of the table.
* What are the rules to be implemented to maintain data integrity of the table.

7.1 Naming Rules


Table names and column names:
• Must begin with a letter
• Must be 1–30 characters long
• Must contain only A–Z, a–z, 0–9, _, $, and #
• Must not duplicate the name of another object owned by the same user
• Must not be an Oracle server–reserved word
• Must not contain space in between

- 53 -
7.2 CREATE TABLE Statement
Syntax
CREATE TABLE table_name (column1_name data type, column2_name data
type, column_name3 data type ……….);
7.3 Data types:
Below is the list of some commonly used data types.

Data Type Description


VARCHAR2(size) Variable-length character data (upto 4000 KB)
CHAR(size) Fixed-length character data (upto 2000 KB)
NUMBER(p,s) Variable-length numeric data (p is precision and s is scaling)
DATE Date and time values

Table 7.1
Create the table DEPT.
SQL> CREATE TABLE dept
(deptno NUMBER(2),
dname VARCHAR2(14),
loc VARCHAR2(13),
create_date DATE);

Confirm table creation.

DESCRIBE dept OR DESC dept

Table 7.2

- 54 -
Example 2:
SQL> CREATE TABLE emp (empno number(4), ename varchar2(20),
hiredate date, job char(10), sal number(6));

7.4 Altering the table: Use the ALTER TABLE statement to alter the definition of
a table

7.6.1 Adding a new column to the table


SQL> ALTER TABLE table_name ADD column_name data type (size);
SQL> ALTER TABLE tb_emp ADD manager_id number (4);

7.6.2 Adding multiple columns to the table


SQL> ALTER TABLE tb_emp ADD (comm number (4), deptno number);

Note that the newly added columns will be added at the end.

7.6.3 Modifying the columns: changing the size, data type and the name of the
columns
SQL> ALTER TABLE tb_emp MODIFY deptno number (3);
SQL> ALTER TABLE tb_emp MODIFY job varchar (10);
SQL> ALTER TABLE tb_emp RENAME COLUMN job to designation;

Note: If a column data type has to be changed then the column should be empty.
If the length is decreased then the values in the column must be
compatible.

7.6.4 Dropping columns: The column(s) in a table can be removed from the
table. All the values in the column(s) will also be removed from the table.
SQL> ALTER TABLE tb_emp DROP COLUMN comm;
SQL> ALTER TABLE tb_emp DROP (job, deptno);

- 55 -
7.5 Renaming the table: Rename command changes the name of the table.
Syntax: RENAME old_tablename to new_tablename
SQL> RENAME dept to tb_dept;

7.6 Dropping a Table


• All data and structure in the table are deleted.
• Any pending transactions are committed.
• All indexes are dropped.
• All constraints are dropped.
• You cannot roll back the DROP TABLE statement.

SQL> DROP TABLE tb_dept;

7.7 TRUNCATE Statement


• Removes all rows from a table, leaving the table empty and the table structure
intact
• Is a data definition language (DDL) statement cannot easily be undone

Syntax:
SQL> TRUNCATE TABLE table_name;
Example:
SQL> TRUNCATE TABLE employees;

7.8 The flashback technology


Prior to Oracle 10g, a DROP command permanently removed the table and the
indexes from the database. But in Oracle 10g a new feature called recycle bin is
introduced to recover the objects that were dropped. In Oracle 10g, a DROP
command places the object in the recycle bin. You can query the recycle bin to
find the objects that are available in it.

SQL> SELECT * FROM user_recyclebin;


To get back the dropped table which is available in the recycle bin
- 56 -
Syntax
SQL> FLASHBACK TABLE table_name TO BEFORE DROP;
Example
SQL> FLASHBACK TABLE tb_dept TO BEFORE DROP;

To drop permanently a table without storing in the recycle bin

SQL> DROP TABLE table_name PURGE;


SQL> DROP TABLE emp PURGE;

Exercises
1. Create the following tables with suitable datatypes for columns

a. Customer (Custid, Custname, Addr, phno,panno)


b. Loan (Loanid, Amount, Interest,Custid)
c. Account (Accd, Accbal, Custid)

2. Add a column mailid to customer table.


3. Find the structure of the above tables.
4. Change the name of the column phno to mobileno.
5. Remove the addr from customers table.
6. Drop the account table.
7. Drop amount and interest columns from loan table.
8. Change the name of the customer table to cust_details.

- 57 -
CHAPTER 8

8.0 OTHER DATABASE OBJECTS


8.1 What is a schema?
A schema is a collection of database objects owned by a specific user. When a
user is created automatically a schema is created. There are around 30 objects
available in the database. The schema will have the same name of the user.

Common Database Objects are


1) Tables
2) Indexes
3) Views
4) Sequences
5) Synonyms
6) Procedures
7) Functions
8) Packages
9) Triggers etc;

8.2 VIEWS
View is a subset of one or more base tables. A view takes the output of a query
and treats it as a table. Therefore, a view can be thought of as a stored query or
a virtual table. A view will not have data of its own like a table. It depends on the
base tables for data. A view is stored as a select statement in the data dictionary.

8.2.1 Advantages of a view


a. Views restrict data access.
b. Views make complex query simple.
c. Views reduce the query compilation time.
d. A single set of data can be represented in different formats
through views.

- 58 -
8.2.2 How Views are Stored
Unlike a table, a view is not allocated any storage space, nor does a view
actually contain data. Rather, a view is defined by a query that extracts or derives
data from the tables that the view references. These tables are called base
tables. Base tables can in turn be actual tables or can be views themselves.
Because a view is based on other objects, a view requires no storage other than
storage for the definition of the view (the stored query) in the data dictionary

8.2.3 Creating a View


SQL> CREATE VIEW vu_emp AS SELECT * FROM tb_emp;

Create the EMPVU80 view, which contains details of


employees in department 80:

SQL> CREATE VIEW vu_emp80


AS SELECT employee_id, last_name, salary
FROM employees WHERE department_id = 80;

• Describe the structure of the view by using the DESCRIBE command:

SQL> DESCRIBE empvu80

8.2.4 With Check option: The Check Option prohibits changes to the table
(through the view) which would produce rows that are not included in the view.

SQL> CREATE OR REPLACE VIEW empvu20


AS SELECT * FROM employees
WHERE department_id = 20
WITH CHECK OPTION CONSTRAINT empvu20_ck ;

Any attempt to change the department number for any row in the view fails
because it violates the WITH CHECK OPTION constraint.
- 59 -
8.2.5 Denying DML Operations
• You can ensure that no DML operations occur by adding the WITH READ
ONLY option to your view definition.
• Any attempt to perform a DML operation on any row in the view results in an
Oracle server error.

SQL> CREATE OR REPLACE VIEW empvu10


AS SELECT employee_id, last_name, job_id
FROM employees
WHERE department_id = 10
WITH READ ONLY;

To view the details about the views which are created in your schema.

SQL> SELECT * FROM user_views;

Note: When the base table is dropped all the views corresponding to the base
tables will not be dropped, instead the status of the view will be changed to
invalid.

8.3 INDEXES
The best way of understanding an index in Oracle (or any database system) is
by comparing it with the index that we find at the end of a textbook. For instance,
if you want to read about indexing in an Oracle textbook, you will use index of the
book to locate the topic indexing. Once the topic is found in index then you take
the page number of that topic from index. Then you go to the page with that page
number and start reading about indexing. The concept of indexing in Oracle is
same as the concept of book index.

- 60 -
First let us look at the features of an index of a textbook.
* It is at the end of the textbook so that you need not search for the index in the
first place.
* It contains all topics of the book in the ascending (alphabetical) order of the
topics.
* After the topic the page number(s) where the topic is found in the book is listed.
* Index does increase the size of the book by a few pages.
* We use index only when we need it. In other words, we use index when we feel
it is going to help locating the topic quickly.

All the characteristics of an index in a textbook will be found in an index of


Oracle. The following are the characteristics of an index in Oracle.
 Index is used to search for required rows quickly.
 Index occupies extra space. Index is stored separately from table.
 Index contains the values of key column on which index is created in the
ascending order.
 Just like the page number in book index, Oracle index stores ROWID - a
unique value to internally identify each row of the table. For each entry in
the index a key and corresponding ROWID are stored.
 Oracle uses index only when it feels the index is going to improve
performance of the query.

Note: ROWID is a unique value assigned to each row created in a table. Once
ROWID is assigned to a row it doesn’t change during the lifetime of the row.
Oracle access rows internally using ROWID.

Why to Use an INDEX


An index in Oracle is used for two purposes.
_ To speed up searching for a particular value thereby improving performance of
query.
_ To enforce uniqueness.
- 61 -
8.3.1 Creating an Index
Syntax
SQL> CREATE INDEX index_name ON table_name(column_name);

SQL> CREATE INDEX ind_emp ON tb_emp(ename);

8.3.2 Guidelines for creating an index.


Here are some guidelines from creating efficient indexes:

 Index if you need to access no more than 10-15% of the data in the table.
 Do not use indexes on small tables
 Index the columns that are involved in multi-table join operations
 Index columns that are used frequently in where clauses.
 Index columns that are involved in order by, group by, union and distinct
operations.
 Columns that are frequently updated are bad for indexing
 Choose tables where few rows have similar values
 Keep the number of indexes small, too many will cause performance
problems on inserting data.

To view the information about indexes on a table

SQL> SELECT * FROM user_indexes WHERE table_name=’EMPLOYEES’;


To drop the index:
SQL> DROP INDEX index_name;
SQL> DROP INDEX ind_emp;

If the table is dropped all the corresponding indexes for that table will be
automatically dropped.

- 62 -
8.4 SEQUENCES

A sequence is an object in Oracle that is used to generate a number sequence.


This can be useful when you need to create a unique number to act as a primary
key.

A sequence:
• Can automatically generate unique numbers
• Is a sharable object
• Can be used to create a primary key value
• Replaces application code
• Speeds up the efficiency of accessing sequence values when cached in
memory

8.4.1 CREATE SEQUENCE Statement


Syntax
CREATE SEQUENCE sequence_name
[INCREMENT BY n]
[START WITH n]
[{MAXVALUE n | NOMAXVALUE}]
[{MINVALUE n | NOMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n | NOCACHE}];

Example:
SQL> CREATE SEQUENCE dept_deptid_seq
INCREMENT BY 10
START WITH 120
MAXVALUE 9999
NOCACHE
NOCYCLE;

- 63 -
When a sequence is created, its values can be accessed in SQL statements with
the CURRVAL pseudo column which returns the current value of the sequence
or the NEXTVAL pseudo column which returns the next value after incrementing.

8.4.2 NEXTVAL and CURRVAL Pseudocolumns


• NEXTVAL returns the next available sequence value. It returns a unique value
every time it is referenced, even for different users.
• CURRVAL obtains the current sequence value.
• NEXTVAL must be issued for that sequence before CURRVAL contains a
value.
Syntax:
SQL> SELECT sequence_name.NEXTVAL FROM dual;
SQL> SELECT sequence_name.CURRVAL FROM dual;
Examples:
SQL> SELECT dept_deptid_seq NEXTVAL FROM dual;
SQL> SELECT dept_deptid_seq. CURRVAL FROM dual;

8.4.3 Using sequences


Let us create a small table to use the above sequence.
SQL> CREATE TABLE test_seq (invoice_no number, customer_id number);

To automatically generate the invoice numbers use the sequence.


SQL> INSERT INTO test_seq VALUES (dept_deptid_seq.NEXTVAL, 100);
Note: Sequences can be used in update statements also.
Sequences can be used by multiple users.
To remove the sequence
SQL> Drop sequence sequence_name;
SQL> Drop sequence dept_deptid_seq;

To view the sequences that was created in your schema


SQL> SELECT * FROM user_sequences;

- 64 -
8.5 SYNONYMS

A synonym is an alternative name for objects such as tables, views, sequences,


stored procedures, and other database objects. They are also used to Shorten
lengthy object names.

Syntax:

CREATE SYNONYM synonym_name FOR object_name;

Example:

Create a shortened name for ALL_EMPLOYEES_DETAILS table:


SQL> CREATE SYNONYM empys FOR all_employees_details;

To view the synonyms that was created in your schema


SQL> SELECT * FROM user_synonyms;

Drop a synonym:
SQL> DROP SYNONYM empys;

- 65 -
CHAPTER 9

9.0 MANIPULATING DATA

Data Manipulation Language (DML) is a core part of SQL. When you add, update
or delete data in the database you execute a DML statement.

A DML statement is executed when you:


– Add new rows to a table
– Modify existing rows in a table
– Remove existing rows from a table

9.1 Adding Data with the INSERT Statement

You can use the SQL INSERT statement to add a row of data to a table. The
data inserted must be valid for the datatype and size of each column of the table.
• List values in the default order of the columns in the table.
• Optionally, list the columns in the INSERT clause.
• Enclose character and date values in single quotation marks.
Syntax:
INSERT INTO table_name VALUES (value1, value2, value3 ...);

Examples:
The following inserts data for all the columns in a row
SQL> INSERT INTO dept VALUES (10,'ADMIN','New York');
Inserting values to specific columns in row:
SQL> INSERT INTO dept (deptno, dname) VALUES (20,’PROGRAMING’);
With this syntax, only one row is inserted at a time.
Note: If values are specified for all the columns then the column list is not
required in the insert clause.

- 66 -
9.1.1 Inserting Rows with Null Values
• Implicit method: Omit the column from the column list.
SQL> INSERT INTO dept (department_id, department_name) VALUES (30,
'Purchasing');

• Explicit method: Specify the NULL keyword in the VALUES clause.


SQL> INSERT INTO departments VALUES (100, 'Finance', NULL);

9.1.2 Copying Rows from another Table


• Write your INSERT statement with a subquery:
• Do not use the VALUES clause.
• Match the number of columns in the INSERT clause to those in the subquery.

SQL> INSERT INTO sales_reps(id, name, salary, commission_pct) SELECT


employee_id, last_name, salary, commission_pct FROM employees
WHERE job_id LIKE '%REP%';

SQL> INSERT INTO copy_emp SELECT * FROM emp;

9.2 Changing Data in a Table


Use the update command to change single row, groups of rows, or all rows in a
table. As in all data modification statements, you can change the data in only one
table at a time.
Syntax:
UPDATE table SET column = value [, column = value ...] [WHERE condition];

• Specific row or rows are modified if you specify the WHERE clause:
SQL> UPDATE employees SET department_id = 70
WHERE employee_id = 113;

- 67 -
• All rows in the table are modified if you omit the WHERE clause:
SQL> UPDATE employees SET department_id = 110;
9.2.1 Updating multiple Columns:
SQL> UPDATE employees set salary=7000, job=’MANAGER’
WHERE employee_id = 113;
9.3 Removing a Row from a Table: To remove a row or rows from the table use
DELETE command.
DELETE FROM table [WHERE condition];
• Specific rows are deleted if you specify the WHERE clause:
SQL> DELETE FROM departments WHERE department_name = 'Finance';
• All rows in the table are deleted if you omit the WHERE clause:
SQL> DELETE FROM copy_emp;

9.4 MERGE Statement


• Provides the ability to conditionally update or insert data into a database table
• Performs an UPDATE if the row exists, and an INSERT if it is a new row.
– Avoids separate updates
– Increases performance and ease of use
– Is useful in data warehousing applications
The merge statement inserts or updates rows in a single operation based on a
join condition. The rows in the target table that match the join condition are
updated; if the join condition is not satisfied then those rows are inserted into the
target table
Example:
SQL> MERGE INTO copy_emp ec
USING emp e
ON (ec.empno=e.empno)
WHEN MATCHED THEN
UPDATE SET ec.sal=e.sal
WHEN NOT MATCHED THEN
INSERT (empno,ename,sal) VALUES (ec.empno,ec.ename,ec.sal);

- 68 -
CHAPTER 10

10.0 TRANSACTION CONTROL LANGUAGE (TCL)

Transaction control statements manage changes made by DML statements.

10.1. Database Transactions: A collection of DML statements that form a


logical unit of work is called as a transaction.

10.1.1 Transaction.
• Begins when the first DML SQL statement is executed
• Ends with one of the following events:
– A COMMIT or ROLLBACK statement is issued.
– A DDL or DCL statement executes (automatic commit).
– The user exits SQL Developer or SQL*Plus.
– The system crashes.

TCL Statements available in Oracle are

COMMIT : Make changes done in transaction permanent.


ROLLBACK : Rollbacks the state of database to the last commit point.(UNDO)
SAVEPOINT : Use to specify a point in transaction to which later you can
rollback.

10.2 COMMIT

To make the changes done in a transaction permanent or to save the changes


give COMMIT statement.

The syntax of COMMIT Statement is


SQL> COMMIT ;
Example
SQL> INSERT INTO emp (empno,ename,sal) VALUES (101,’Abid’,2300);
SQL> COMMIT ;
- 69 -
10.3 ROLLBACK

To rollback the changes done in a transaction give rollback statement. Rollback


restore the state of the database to the last commit point.
Example :

SQL> DELETE FROM emp;

SQL> ROLLBACK;

10.4 SAVEPOINT
Specify a point in a transaction to which later you can roll back.
Example
SQL> INSERT INTO emp (empno,ename,sal) VALUES (109,’Sami’,3000);
SQL> SAVEPOINT a;
SQL> INSERT INTO dept VALUES (10,’Sales’,’Hyd’);
SQL> SAVEPOINT b;
SQL> INSERT INTO salgrade VALUES (‘III’,9000,12000);

Now if you give


SQL> ROLLBACK TO a;
Then a row from salgrade table and dept will be roll backed. Now you can
commit the row inserted into emp table or rollback the transaction.
If you give
SQL> ROLLBACK TO b;
Then row inserted into salgrade table will be roll backed. Now you can commit
the row inserted into dept table and emp table or rollback to savepoint a or
completely rollback the transaction.

If you give
SQL> ROLLBACK;
Then the whole transactions will be roll backed.

- 70 -
If you give
SQL> COMMIT;
Then the whole transaction will be committed and all save points are removed.

Note:
• An automatic commit occurs under the following circumstances:

 DDL statement is issued


 DCL statement is issued
 Normal exit from SQL Developer or SQL*Plus, without explicitly
issuing COMMIT or ROLLBACK statements

• An automatic rollback occurs under an abnormal termination of SQL Developer


or SQL*Plus or a system failure.

- 71 -
CHAPTER 11

11.0 DATA CONTROL LANGUAGE (DCL)

Data Control Statements are one of the SQL statement types which enforce
database security at database and object level. It deals with the access
permissions and rights of a user.

DCL commands are used to assign security levels in database, which involves
multiple user setups. They are used to grant defined role and access privileges to
the users. There are two types of DCL commands in Oracle:
1. GRANT
2. REVOKE.
First let us discuss about the privileges in the database environment.
A privilege is a right to execute an SQL statement or to access another user's
object. In Oracle, there are two types of privileges: system privileges and object
privileges.

11.1 System Privilege: System privilege is a right to perform an action in the


database. For example the most commonly performed actions in the database
are
 logging in to the database
 creating a table or a view or a sequence
 creating a user
 altering a table or a view or a sequence
 accessing the table owned by another user and so on

11.1.1 Oracle System Privileges

System privileges allow the user to perform system level activities. This might
include such things as being able to actually connect to the system, or it might
include the ability to do things like create objects in schemas other than your own

- 72 -
schema. In the next sections we will discuss the grant command, which you use
to grant system privileges. Also the revoke command is used to revoke privileges
from users.

11.1.2 Granting Oracle System Level Privileges

The grant command is used to grant system level privileges. System level
privileges are those privileges that you need to actually do something on the
system or database. For example you grant system level privileges to a user so
that they can:

* Connect to the database (create session)


* Create objects (create table, create view etc ;)
* Perform DBA activities, like backup the database (SYSDBA, SYSOPER)
* Alter session related parameters (alter session)

Basically, even if you create a user account, it will not be able to do anything until
you have granted it a basic set of privileges. Typically you would always grant the
create session privilege so that the user can connect to the database.

The grant command is pretty simple to use, you just need to know what privilege
you want to grant and who you want to grant that privilege to.

For example if the user has to log on to the database he needs create session
privilege.

Example: GRANT create session, create table, create sequence, create view TO
Scott;
If the user wants to view the system privileges that were granted to him then
SQL> SELECT * FROM session_privs;
The above view lists out the system privileges that were granted to the user.

By default, if you are granted a privilege, you cannot assign your privilege to
others. You can’t grant or revoke that privilege to or from anyone else.
Sometimes you want to grant privileges to users and have them be able to grant
- 73 -
those privileges to other users. When this is the case, we include the with admin
keyword in the grant command. When this keyword is used, it will allow the user
granted the privilege to grant that privilege to other users. Here is an example of
the usage of the with admin option keyword.

SQL> GRANT CREATE TABLE TO Robert WITH ADMIN OPTION;

Now the user Robert can grant the create table privilege to others.

11.1.3 Revoking System Level Privileges

The revoke command is used to revoke system level privileges that were
previously granted with the grant command. Simply enter the privilege you wish
to revoke in the body of the revoke command as seen in this example:

SQL> REVOKE CREATE TABLE FROM Robert;

To be able to revoke a privilege from another user, you must have been granted
that privilege with the admin option, as demonstrated earlier in this section.
Revoking system level privileges will only impact the user that you are revoking
the privileges from. Any other user who was granted system privileges by that
user will still continue to have those privileges.

To view whether the user had received the privilege with admin option

SQL> SELECT * FROM user_sys_privs;

11.2 Object Privileges: It is the right to access and manipulate the objects
owned by other users.

Once you have created users and given them system privileges, they will start
creating objects. Once objects are created, only the user who created those
objects will be able to actually do anything with them. This is not particularly
useful since you don’t want to be giving out your user id and password to
everyone in the world.

- 74 -
Oracle gives us the grant and revoke commands so that we can give other users
access to objects in the database. Let’s look at these commands in more detail.

11.2.1 Granting Object Level Privileges

In order to allow other users to access your objects you can use the grant
command (yes, the very same grant command used to grant system privileges)
to allow different kinds of access to your objects. For example, we can grant the
user TOM access to the EMP table in the SCOTT account (or schema) with this
command:
SQL> GRANT SELECT ON emp TO tom;

Only the user who owns the object can grant privileges to that object unless the
with grant option is included in the command. The with grant option allows you
to give the user you are assigning the privilege to the right to grant that privilege
to other users. Here is an example of the use of the with grant option:

SQL> GRANT SELECT ON emp TO scott WITH GRANT OPTION

Revoking Object Level Privileges

When we no longer wish a user to have access rights to an object we can use
the revoke command to remove those rights as seen in this example:

SQL> REVOKE SELECT on emp FROM scott;

There is one major difference in the revocation of object privileges and system
privileges. With objects, if you revoke a privilege from a user who had been
granted it previously with the with grant option, Oracle acts a bit different. In this
case, the revoke operation will affect not only the user that you are revoking the
privilege from, but all other users who that user had granted privileges to will
have those privileges revoked as well. Hence, be careful revoking object
privileges, you might find that you end up breaking something. Only the user who
had originally granted the object privilege alone can revoke the same from the
user.
- 75 -
11.3 ROLES: Administration of large numbers of objects and privileges can be
difficult. Roles allow you to localize the administration of objects. Oracle roles are
most helpful when large numbers of users will need the same system and object
privileges.

What is a role?

A role is a set or group of privileges that can be granted to users or another role.
This is a great way for database administrators to save time and effort.

11.3.1 Creating a Role

To create a role, you must have CREATE ROLE system privileges.

Syntax for creating a role: CREATE ROLE role_name;

SQL> CREATE ROLE hr_admin;

After creating the role grant the necessary privileges to the role.

SQL> GRANT create session,create table TO hr_admin;

Now this role can be granted to a user or to another role.

SQL> GRANT hr_admin TO tom;

All the privileges that were granted to the role will be automatically granted to the
user or role.

To revoke the role

SQL> REVOKE hr_admin FROM tom;

To remove the role from the database

DROP ROLE role_name;

SQL> DROP ROLE hr_admin;

- 76 -
Note:

Role is a non-schema object.

Role can be granted to users or other roles. But it cannot be granted to itself.

To check the roles that was enabled for the session

SQL> SELECT * FROM session_roles;

11.4 Confirming Privileges Granted: To confirm the privileges that were


granted use the following data dictionary views.

Data Dictionary View Description


ROLE_SYS_PRIVS System privileges granted to roles
ROLE_TAB_PRIVS Table privileges granted to roles
USER_ROLE_PRIVS Roles accessible by the user
USER_TAB_PRIVS_MADE Object privileges granted on the user’s objects
USER_TAB_PRIVS_RECD Object privileges granted to the user
USER_COL_PRIVS_MADE Object privileges granted on the columns of
the user’s objects
USER_COL_PRIVS_RECD Object privileges granted to the user on
specific columns
USER_SYS_PRIVS System privileges granted to the user

Table 11.1

11.5 CREATING A NEW USER


One of the more common tasks of the Database administrator is the creation of
the database user. Each database user is assigned a unique username. Users
will log into the database using that username, and having logged in, users can
issue various database SQL statements to create objects, query objects and
manage the database. When a database is created automatically SYS user and
- 77 -
SYSTEM user will be created. SYS is a very powerful user who has all the
privileges in the database. SYS user is the owner of the database and the owner
of the important data dictionary. The SYSTEM user is used to create additional
tables and views that display administrative information, and internal tables and
views used by various Oracle options and tools.

Syntax: CREATE USER username IDENTIFIED BY password;

Example: CREATE USER tom IDENTIFIED BY sql;

After creating the user grant the necessary privileges to the user.

11.5.1 How the user can change his password?

Option 1: ALTER USER username IDENTIFIED BY password;

SQL> ALTER USER tom IDENTIFIED BY oracle;

Option 2: Type password in the sql prompt

SQL> password

A password change dialog box appears

Type the old password then the new password and confirm it.

To Find the name of the current user


SQL> SHOW USER.
Note: For creating a new user you must have the CREATE USER system
privilege.

- 78 -
Lab 1: The ORACLE interfaces

The learning objectives of this lab are to:

• Learn how to use standard ORACLE interface to SQL (SQL*PLUS).


• How to set the line size and page size.
• Learn how to create tables.

Exercise 1:

1 Initiate SQL*PLUS and connect to your schema in the database


2 Set the line size to 100 and page size to 100
3 Create the following tables using the given fields.

(1) Student Information Table:


Student_id number(8)
First_name varchar2(20)
Last_name varchar2(25)
Dob varchar2(20)
Address varchar2(300)
City varchar2(20)
State varchar2(2)
Zip Code varchar2(9)
Email varchar2(100)

(2) Department Information Table:

Department_Id varchar2(20)
Department_Name varchar2(25)

(3) Course Information Table:

Course_Name varchar2(5)
Department_Id varchar2(20)
Title char(60)
Description varchar2(200)

(4) Student Course Registration Table


Student_id number(8)
Course_Id varchar2(5)
Date_of_joininig date

(5) Student Grade Information Table:


Student_Id varchar2(20)
Grade Varchar2(2)
Lab 2: Altering the tables

The learning objectives of this lab are to:

Learn how to alter the table by adding new columns, changing the data
types, changing the name of the columns and dropping columns, changing
the length of the columns.

i) Find the descriptions of the above tables.

ii) Alter the student table to make the following changes:

 Add a new column SEX which is of char datatype.


 Alter the column size of First_Name to 25.
 Alter the datatype of Dob to Date.
 Change the name of the column first_name to student_name.
 Drop the column last_name.

iii) Alter the Student Grade Table to make the following changes:

1 Add a new column sem1_marks of number (3)


2 Add a new column sem2_marks of number (3)
3 Add a new column sem3_marks of number (3)
4 Add a new column total_marks of number (6)
5 Change the length of the column grade to (4)

iv) Confirm your changes.


v) Change the data type of department_id column to number in all the
Tables.
vi) Remove the description& title columns from the
Department Information Table
vii) Rename the Student Course Registration Table to
Student Registration Table.
Lab 3: Loading Data.

The learning objective of this lab are to:

Load data into the tables. (How to use insert command)

i) Insert 10 records in the above tables as per the hints given below
ii) Save the changes

Hints: Department_id value must be the same in all the tables.


Department_name must be ARTS, SCIENCE, COMMERCE, IT and
Computer Science.
Course_name should be BA, BSc, Bcom, Etc

Lab 4: Retrieving The Records

The learning objectives of this lab are to:

1 Write queries to retrieve records from the tables.

1. Display all the information from the student table.


2. Display the student_id, city and DOB for all the students.
3. Display the information of a student who is not having a mail id.
4. Find the students whose city is Chennai.
5. Find the students who are from the state starts with the letter ‘T’.
6. Find the names of the students whose name ends with ‘R’.
7. Display the name concatenated with the DOB separated by a space. Label
the column Name and DOB.
8. Display the students name, city, DOB whose name contains ‘I’ in the
second position.
9. Display all the information of the students where name is of only 5
characters.
10. Display the id, name and age of all the students.
11. Display the id, name and DOB of all the students whose age is more than
18.

12. Display the name, DOB, Mail id of the students whose birthday falls on
‘Monday’.
13. Display the id, name and address of the students who were born in the
month of January.
14. Display the details of eldest male student.
15. Display the details of the youngest female student.
16. Display the id and name of the students whose length of the name are
same.
17. Display the name of the students with all letters capitalized, city with first
letter capitalized and address with all letters in lower case.
18. Display the current server date.
19. Display the last day of the current month.
20. Display the name and DOB of all the students. The output should be in the
format as per the example. “John born on Monday the fourteenth may
1982”.
21. Find out the courses available in the college.
22. Display the first day of the given year.
23. Find the students who were born in leap year.
24. Display the name and no. Of months of the students since their birth.
25. Display the average age of the students.
26. Find the cities to which the students belong.
27. Display the Date of birth of the students rounded of to the nearest month.
28. Display the id, name and Zip code of the students whose zip code contains
two zeros.
29. Find the department that has the maximum no.of students.
30. Display the name, id, Course id and date of joining of all the students.
31. Display a unique listing of all the courses from the students Registration
table.
32. Find the average number of students registered for each department.
33. List out the name and marks obtained by each student in all semesters.
34. Find the name and id of the students who have passed.
35. Find the number of students who have failed.
Lab 5: Manipulating Data

The learning objectives of this lab are to:

Update the existing records


Remove the records from the table.

A. UPDATE

1. Change the Name of the students who does not have a telephone
number to Clark.
2. Change the course IT to information Technology.
3. Update the name of the city Chennai to 'Madras'.
4. Update state column for whose name starts with the letter 'T' to a
value of 'TN’.
5. Update Name whose state ends with the letter 'A' to a value of 'AAA'.
6. Update Students name to 'XXX', Dob to current date whose name
contains 'A' in the Fourth position.
7. Update Students name to 'YOUTH' whose age is less than 20.
8. Update Students name to 'BIRTHDAY' whose Birthday falls today.
9. Update the eldest male Student's name from the Student table to
'SENIOR'.
10. Update students name to 'JAN' whose birthday falls on January.

B. DELETE

1. Delete all information’s from the Student table whose name is null.
2. Delete the information from Student table that doesn't have a
telephone and an email.
3. Delete Students information who’s Birthday falls on June 05.
4. Delete the Students information whose birthday falls in the month of
October.
5. Remove all the records from the student registration table.
Lab 6: Constraints

The learning objectives of this lab are to:

Set rules for records at table level and column level


Relate multiple tables

1. Declare a constraint so that the name column must have a value


2. Declare suitable constraints so that all the department id columns
refer the department id column of department information table.
3. The DOB must be less than sysdate.
4. All marks must be less than 100.
5. The student id column of the other tables must refer the student id
column of students table.
6. Mail id must be unique.
7. Update the Mail id column so that the mail id must be the first 3
characters of the name of the student and the last 2 digits of the year
of DOB @xyz.com.
8. The Length of Student names must be minimum of 3 characters.
9. Check the Constraints, which you have declared on the tables.
10. Try to disable the primary key constraint on the students table. Load
Duplicate data. Enable the constraint what happens?
11. Enable the above constraint.
12. Drop the constraint.
Lab 7: Other Database Objects

The learning objectives of this lab are to:

1 Create and manage Indexes, views and sequences.

1) Create an unique index for Course_id column.


2) Create a sequence for student_id column
The id number must start with 1000 and incremented by 1
Max. Number should be 9999

3) Create a view for student table.


4) Grant the alter, update, insert, select privileges to your friend on the student
table.
5) Create a synonym course_alais for course table.
Table of Contents

Chapters Titles Page No

1 Introduction 1

2 Declaring PLSQL Variables 8

3 Interacting With Oracle Server 16

4 Control Structures 17

5 Cursor 23

6 Using Explicit Cursors 25

7 Exceptions 36

8 Stored Procedure 48

9 Stored Function 59

10 Package 63

11 Triggers 70
CHAPTER 1

1. INTRODUCTION TO PLSQL

1.1 PL/SQL stands for Procedural Language extension of SQL


1 PL/SQL is a combination of SQL along with the procedural features
of programming languages.
2 It was developed by Oracle Corporation in the early 90’s to enhance
the capabilities of SQL statement.
3 The procedural construct and database access are present in
PL/SQL. PL/SQL can be used in both in Oracle Server and in Client
side application development tools.
4 PL/SQL language includes object oriented programming techniques,
such as function, overloading, information hiding.
5 PL/SQL is one of three key programming languages embedded in
the Oracle Database, along with SQL itself and Java.

1.2 Difference between SQL and PL/SQL


Both SQL and PL/SQL are languages used to access data within Oracle
databases.
SQL is a limited language that allows you to directly interact with the
database. You can write queries to SELECT, manipulate objects and
retrieve data with SQL statement. However, SQL doesn't include all the
things that normal programming languages have such as loops and
IF...THEN...ELSE statements.
PL/SQL is a normal programming language that includes all the features of
most other programming languages. But, it has one thing that other
programming languages don't have, the ability to easily integrate with SQL.
Some of the key differences are:

1
SQL is executed one statement at a time. PL/SQL is executed as a
block of code.
SQL tells the database what to do (declarative), not how to do it. In
contrast, PL/SQL tell the database how to do things (procedural).
SQL is used to code queries, DML and DDL statements. PL/SQL is
used to code program blocks, triggers, functions, procedures and
packages.
You can embed SQL in a PL/SQL program, but you cannot embed
PL/SQL within a SQL statement.

1.3 Advantages PL/SQL

Procedural Language Support: PL/SQL is a development tool that


not only support data Manipulation but also provides the Condition,
Checking, Looping or Branching Operations.
Reduces Network Traffic: PL/SQL engine processes multiple SQL
statements simultaneously as a single block, thereby reducing
network traffic.
Error Handling: PL/SQL handles errors or exceptions effectively
during the execution of a PL/SQL program. Once an exception is
caught, specific actions can be taken depending upon the type of the
exception or it can be displayed to the user with a message.
Declare Variable: PL/SQL allows to declare and use of variables in
a block of code, which will use these variables to store intermediate
result of query for later processing.
Intermediate Calculation: PL/SQL calculations are done quickly
and efficiently without the use of oracle engine and improve the
transaction.
Portable Application: Applications written in PL/SQL are portable
in any computer or hardware for any system means Applications are
independent to run in any computer.

2
1.4 PL/SQL Environment
Every PL/SQL block is first executed by PL/SQL engine. This is the engine
that compiles and executes PL/SQL blocks. PL/SQL engine is available in
Oracle Server and in certain Oracle tools such as Oracle Forms and Oracle
Reports. PL/SQL engine executes all procedural statements of a PL/SQL of
the block, but sends SQL command to SQL statements executor in the
Oracle RDBMS. That means PL/SQL separates SQL commands from
PL/SQL commands and executes PL/SQL commands using Procedural
statement executor, which is a part of PL/SQL engine.

Figure 1.1

1.5 Displaying output from PL/SQL


In order to display output from a PL/SQL block, we have to use
DBMS_OUTPUT package. A package is a collection of procedures and
functions. DBMS_OUTPUT is a package that comes along with Oracle

3
database and used to display data onto screen from a PL/SQL block.
The following are the procedures available in DBMS_OUTPUT package.
PUT and PUT_LINE procedures. Both these procedures are used to
display a NUMBER, VARCHAR2 or DATE type value.
PUT allows you to put multiple pieces that make up a line.
PUT_LINE puts the given data followed by end-of-line character.
When you use the DBMS_OUTPUT.PUT_LINE procedure, the procedure
will write the passing string into the Oracle buffer. In order to print the
content of the Oracle buffer, you should use the SET SERVEROUTPUT ON
command.

SET SERVEROUTPUT ON

SET SERVEROUTPUT ON is the SQL*Plus command to activate the


console output. You only need to issue this command once in a SQL*Plus
session.

1.6 PL/SQL Block Structure


1 Provides a block structure for executable units of code. Maintenance
of code is made easier with such a well-defined structure.
2 Provides procedural constructs such as:
Variables, constants, and types
Control structures such as conditional statements and loops.
Reusable program units that are written once and executed many
times.
[DECLARE]
Declaration statements;
BEGIN
Execution statements;
[EXCEPTION]
Exception handling statements;
END;
/
Figure 1.2

4
1 DECLARE: Variable and constants are declared within this section and
we may initialize them with value.
2 BEGIN: It contains the PL/SQL statements, which implement the actual
programming logic. This section contains conditional statements
(IF..ELSE), looping statements (FOR, WHILE) and Branching
Statements (GOTO) etc.
3 EXCEPTION: Used to handle runtime errors and warning. Error can
arise due to syntax, logical or validation rules.
Note:
1. BEGIN and END; are compulsory sections of any PL/SQL program.
2. DECLARE and EXCEPTION are optional sections.

Block Types

Anonymous Procedure Function

[DECLARE] PROCEDURE name FUNCTION name


BEGIN IS RETURN datatype
--statements BEGIN IS
[EXCEPTION] --statements BEGIN
END; [EXCEPTION] --statements
END; RETURN value;
[EXCEPTION]
END;

A PL/SQL program comprises one or more blocks. These blocks can


be entirely separate or nested within another block. There are two types of
blocks that make up a PL/SQL program.
They are:
1 Anonymous blocks or unnamed blocks
2 Subprograms or named blocks
– Procedures
– Functions
– Packages (Grouping of procedure and function is called
package)

5
1.6.1 Anonymous blocks: Anonymous blocks are unnamed blocks. They
are declared inline at a point in an application where they are to be
executed and are compiled each time when the application is executed.
These blocks are not stored in the database. If you want to execute the
same block again, you have to rewrite the block.

1.6.2 Subprograms: Subprograms are complementary to anonymous


blocks. They are named PL/SQL blocks that are stored in the database.
Because they are named and stored, you can invoke them whenever you
want (depending on your application). You can declare them either as
procedures or as functions.

PL/SQL block structure Examples


Let’s take a look at the simplest block that does nothing.
BEGIN
NULL;
END;
If you execute the above anonymous block in SQL*Plus you will see that it
issues a message saying that
“PL/SQL procedure successfully completed.”
Now if you want to output a message on screen, you can execute the
following block:
SET SERVEROUTPUT ON SIZE 1000000
BEGIN
DBMS_OUTPUT.PUT_LINE(‘Welcome to PLSQL’);
END;
/
The first command does not belong to the anonymous block. It is telling
SQL*Plus to echo the database’s output to the screen after executing
PL/SQL code.

6
Example
DECLARE
V_SAL NUMBER(10); --Variable Declaration
BEGIN
SELECT SUM(SAL) INTO V_SAL FROM EMP
WHERE DEPTNO =10;
DBMS_OUTPUT.PUT_LINE (‘TOTAL SALARY FOR DEPARTMENT 10
IS :‘||V_SAL);
END;
/

Note:
1 Between begin and end there must be atleast one executable
statement or null
2 All plsql and sql statements are terminated by a semicolon (;)
3 / Is used to run the block. This / must be the first character in a new
line.

7
CHAPTER 2

2. DECLARING PLSQL VARIABLES

2.1 PL/SQL Variables


Variables can be used for:
1 Temporary storage of data
2 Manipulation of stored values
3 Reusability
2.1.1 Handling Variables in PL/SQL
Variables are Declared and initialized in the declarative section used and
assigned new values in the executable section Passed as parameters to
PL/SQL subprograms and used to hold the output of a PL/SQL
subprogram.

2.1.2 PL/SQL Variable Naming Convention


Like other programming languages, a variable in PL/SQL must follow the
naming rules as below:
The variable name must be less than 31 characters. Try to make it as
meaningful as possible within 31 characters.
The starting of a variable must be an ASCII letter. It can be either
lowercase or uppercase. Notice that PL/SQL is not case-sensitive.
A variable name can contain numbers, underscore, and dollar sign ($)
characters followed by the first character. Again, do not make your
variables hard to read and understand.
2.1.3 PL/SQL Variable Assignment
To assign a value or a variable to a variable in PL/SQL, you use the
assignment operator ( := ) which is a colon( : ) followed by an equal sign
( = ).

8
2.1.4 Identifiers
Identifiers are used for:
- Naming a variable
- Providing conventions for variable names
- Must start with a letter
- Can include letters or numbers
- Can include special characters (such as dollar sign, underscore,
and pound sign)
- Must limit the length to 30 characters.
- Must not be reserved words

Syntax

Identifier [CONSTANT] datatype [NOT NULL]


[:= | DEFAULT expr];

Examples
Various way of declaring variable
1 DECLARE
EMP_HIREDATE DATE;
EMP_DEPTNO NUMBER(2) NOT NULL := 10;
LOCATION VARCHAR2(13) := 'ATLANTA';
C_COMM CONSTANT NUMBER := 1400;

2 DECLARE
V_DNO NUMBER(5) :=&V_DNO;
V_SAL NUMBER(10);
BEGIN
SELECT SUM(SAL) INTO V_SAL FROM EMP
WHERE DEPTNO=V_DNO;
DBMS_OUTPUT.PUT_LINE('THE TOTAL VALUES IS '||V_SAL);
END;
/

9
OUTPUT:
Enter value for v_dno: 30
old 2: V_DNO NUMBER :=&V_DNO;
new 2: V_DNO NUMBER :=30;
THE TOTAL VALUES IS 29025

2.2 Types of Variables

1 PL/SQL variables:

TYPE DESCRIPTION DATATYPE


Scalar Scalar data types hold a single
NUMBER, CHAR, LONG,
value. VARCHAR, VARCHAR2,
DATE,TIMESTAMP etc;
Composite Composite data types allow TABLE, VARRAY,
group of fields to be defined and RECORD
manipulated in PL/SQL blocks.
Reference Reference data types hold BFILE, BLOB, CLOB,
values, called pointers that point NCLOB
to a storage location.
Large LOB data types hold values, REF CURSOR,
object called locators that specify the BOOLEAN, DATE
(LOB) location of large objects (such as
graphic images) that are stored
out of line.

2 Non-PL/SQL variables: Bind variables

2.3 Attributes
Allow us to refer to data types and objects from the database. PL/SQL
variables and Constants can have attributes. The main advantage of using
Attributes is even if you Change the data definition, you don’t need to
change in the application.

10
2.3.1 %TYPE
The %TYPE attribute provides the datatype of a variable or database
column. This is particularly useful when declaring variables that will hold
database values.

Declaring Variables with the %TYPE Attribute


Syntax
Identifier table.column_name%TYPE;

Declaring variable with %TYPE of table's column has two advantages:


We don’t have to worry about exact data type of the column for which
we are declaring variable.
Also if later on, data type changes or column length gets increased or
decreased, we don’t need to change the program. Oracle takes care
of it automatically at run time.

Example
emp_lname employee.last_name%type;
emp_sal employee.salary%type;

2.3.2 %ROWTYPE
Records are used to group data in PL/SQL, a record consists of a
number of related fields in which data values can be stored.
The %ROWTYPE attribute provides a record type that represents
a row in a table.
The record can store an entire row of data selected from the table
or fetched from a cursor or cursor variable.
Columns in a row and corresponding fields in a record have the
same names and datatypes.

11
Syntax

identifier reference%ROWTYPE;
Example
Emp_rec emp%rowtype;

Advantages of Using %ROWTYPE


The number and data types of the underlying database columns
need not be known—and in fact might change at run time.
The %ROWTYPE attribute is useful when retrieving a row with the
SELECT * statement.

Apart from obvious advantages shown above, it also makes code concise
and readable. Another major advantage which people are not aware is that
one can insert the record using PL/SQL record type and can update the row
as well using record type rather than stating the individual column list.

2.4 Declaring Boolean Variable


A BOOLEAN datatype is a native PL/SQL type that lets you signify a TRUE
or FALSE condition. A BOOLEAN is NULL until explicitly assigned a value.
A BOOLEAN is assigned like other variables:

DECLARE
v_bool BOOLEAN;
v_bool2 BOOLEAN := TRUE;
v_bool3 BOOLEAN := FALSE;
BEGIN
v_bool := TRUE;
END;

12
You cannot use BOOLEAN in SQL. There is no SQL counterpart to the
PL/SQL BOOLEAN data type. It would be easy enough to add one.
You can use BOOLEAN as a parameter, a return type or an OUT variable to
procedures and functions in PL/SQL. If you use it as an input or return value
for a function, you cannot use that function in SQL.

2.5 Bind Variables


2.5.1 Bind variables are
Created in the environment
Also called host variables
Created with the VARIABLE keyword
Used in SQL statements and PL/SQL blocks
Accessed even after the PL/SQL block is executed
Referenced with a preceding colon

2.5.2 Creating Bind Variables


To create a bind variable in iSQL*Plus or in SQL*Plus, use the VARIABLE
Command.
For example, you declare a variable of type NUMBER and VARCHAR2 as
follows:
VARIABLE return_code NUMBER
VARIABLE return_msg varchar2(20)
Both SQL*Plus and iSQL*Plus can reference the bind variable, and
iSQL*Plus can display its value through the SQL*Plus PRINT command
otherwise use the SET AUTOPRINT ON command to automatically display
the bind variables used in a successful PL/SQL block.

13
Example

VARIABLE G_SAL NUMBER

BEGIN
SELECT SAL INTO :G_SAL FROM EMP
WHERE EMPNO=7902;
END;
/
PL/SQL procedure successfully completed.

PRINT G_SAL

G_SAL
----------
3000

Note: If you are creating a bind variable of type NUMBER, you cannot
specify the precision and scale.

2.6 Nesting Blocks


It is possible to define a block within another block. When blocks are defined
one within another they are said to be nested.
The following is an example of nested block. Main block contains a single
variable X and nested block contains a single variable Y.

DECLARE
X NUMBER(5);
BEGIN
-- put executable code of main block here
DECLARE /* beginning of nested block */
Y NUMBER(3);
BEGIN
-- put executable code of nested block
EXCEPTION
-- exception handing for nested block
END; /* end of nested block */
-- code of main block continues.
EXCEPTION
-- Exception handing for Main block
END; /* end of main block */

14
2.6.1 Scope and visibility of variables
Scope of the variable refers to the region of the program in which the
variable can be used. A variable is said to be visible when it can be referred
without any qualifier.

Example:

DECLARE
V_NAME VARCHAR2(20);
V_JOB VARCHAR2(20);
V_SAL NUMBER(10);
X NUMBER(10) :=100;
BEGIN --begin of main block
LOOP
BEGIN --begin of subblock
SELECT ENAME,JOB,SAL INTO V_NAME,V_JOB,V_SAL
FROM EMP
WHERE EMPNO=X;
DBMS_OUTPUT.PUT_LINE(X||V_NAME||V_JOB||V_SAL);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE(X||'INVALID EMPNO');
END; --end of sub block
X:=X+1;
EXIT WHEN X>110;
END LOOP;
END; --end of main block

15
CHAPTER 3

3. Interacting With Oracle Server


Retrieve data from the database with a SELECT statement
Syntax

select select_list into {variable_name[, variable_name]... |


record_name}
from table [where condition];

3.1 Guidelines for Retrieving Data in PL/SQL


Terminate each SQL statement with a semicolon (;).
Every value retrieved must be stored in a variable using the INTO
clause.
The WHERE clause is optional and can be used to specify input
variables, constants, literals, and PL/SQL expressions. However,
when you use the INTO clause, you should fetch only one row; using
the WHERE clause is required in such cases.
Specify the same number of variables in the INTO clause as the
number of database columns in the SELECT clause. Be sure that
they correspond positionally and that their data types are
compatible.
Group functions such as SUM can be used in a SQL statement.

Example
DECLARE
V_ENAME EMP.ENAME%TYPE;
V_EMPNO EMP.EMPNO%TYPE;
V_SAL EMP.SAL%TYPE;
BEGIN
SELECT ENAME,SAL INTO V_ENAME,V_SAL FROM EMP
WHERE EMPNO=&V_EMPNO;
DBMS_OUTPUT.PUT_LINE(V_ENAME||V_SAL);
END;
/

16
CHAPTER 4

4. Writing Control Structures


4. 1 PL/SQL Condition Control
PL/SQL If Statements
PL/SQL IF statement is used to transfer the control of program depending
on a specified condition. If we want to know greater of given 2 numbers then
we can use the IF statement for comparing the 2 values.
You can change the logical flow of statements using conditional IF
statements and loop control structures.
Conditional IF statements:
1. IF-THEN-END IF
2. IF-THEN-ELSE-END IF
3. IF-THEN-ELSIF-END IF
4. IF-THEN-ELSIF-ELSE-END IF

4.1.1 Simple IF Statement Syntax

IF <condition> THEN
<statement>;
END IF;

Example
Set the manager ID to 22 if the employee name is ALLEN.
IF v_ename = 'ALLEN' THEN
v_mgr := 22;
END IF;

4.1.2 IF..ELSE Statement


This construct allows selection of action from several mutually exclusive
alternatives The IF statement can have any number of ELSIF statements.
The final ELSE is optional Conditions are evaluated one by one from top to
bottom

17
Syntax
IF <condition> THEN
<statement>;
ELSE
<statement>
END IF;

Example
DECLARE
V_SUB1 NUMBER(3);
BEGIN
V_SUB1 := &V_SUB1;
IF V_SUB1 >= 35 THEN
DBMS_OUTPUT.PUT_LINE('PASS');
ELSE
DBMS_OUTPUT.PUT_LINE('FAIL');
END IF;
END;

4.1.3 Nested IF Statement Syntax

IF <condition-1> THEN
<Statements>;
ELSE
IF <condition-2> THEN
<Statements>;
ELSE
<Statements>;
END IF;
END IF;

Alternative Nested IF Syntax

IF <condition-1> THEN
<Statements>;
ELSIF <condition-2> THEN
<Statements>;
ELSIF <condition-3> THEN
<Statements>;
……………
……………
..................
ELSE
<Statements>;
END IF;

18
Note: ELSIF and ELSE are optional in an IF statement. You can have any
number of ELSIF keywords but only one ELSE keyword in your IF
statement. END IF marks the end of an IF statement and must be
terminated by a semicolon.

Example

DECLARE
V_EMPNO NUMBER(10) :=&V_EMPNO;
V_JOB VARCHAR2(20);
BEGIN
SELECT JOB INTO V_JOB FROM EMP
WHERE EMPNO=V_EMPNO;
IF V_JOB =’PRESIDENT’ THEN
UPDATE EMP SET SAL=SAL+2000
WHERE EMPNO=V_EMPNO;
ELSIF
V_JOB =’MANAGER’ THEN
UPDATE EMP SET SAL=SAL+1000
WHERE EMPNO=V_EMPNO;
ELSIF
V_JOB =’CLERK’ THEN
UPDATE EMP SET SAL=SAL+500
WHERE EMPNO=V_EMPNO;
END IF;
END;
/

4.2 Iterative Control


4.2.1 PL/SQL Looping Control
Loop statements let you execute a sequence of statements multiple times.
1. SIMPLE Loop - that performs repetitive actions without overall
conditions (exit check).
2. WHILE Loop - that perform iterative actions based on a condition
(entry check).
3. FOR Loop - that perform iterative actions based on a count.
Note: An EXIT statement can be used to terminate loops. A basic loop must
have an EXIT.

19
4.2.2 Guidelines for Loops
Use the basic loop when the statements inside the loop must
execute at least once.
Use the WHILE loop if the condition must be evaluated at the start of
each iteration.
Use a FOR loop if the number of iterations is known.

4.2.3 Simple Loop


Syntax

LOOP
<Sequence of statements>
EXIT;
{or EXIT WHEN condition;}
END LOOP;

Example

DECLARE
I NUMBER(2);
BEGIN
I:=0;
LOOP
DBMS_OUTPUT.PUT_LINE(I);
I:=I+1;
EXIT WHEN I>5;
END LOOP;
END;
/
Output:
0
1
2
3
4

20
4.2.4 While Loop
Syntax

WHILE <condition>
LOOP
<action>
END LOOP;

Note: Condition is evaluated at the beginning of each iteration.

Example

DECLARE
I NUMBER(3);
BEGIN
WHILE I<5
LOOP
DBMS_OUTPUT.PUT_LINE('I');
I:=I+1;
END LOOP;
END;
/

Output:
1
2
3
4

4.2.5 FOR Loop


Syntax
FOR variable IN[REVERSE] start..end
LOOP
<action>
END LOOP;

21
Example

BEGIN
FOR I IN 1..5
LOOP
DBMS_OUTPUT.PUT_LINE(I);
END LOOP;
END;
/

Output
1
2
3
4
5

22
CHAPTER 5

5. Cursors
5.1 What is Cursor
Oracle allocates an area of memory known as context area for the
processing of SQL statements. The pointer that points to the context area is
a cursor.
5.2 How to Use Cursor
PL/SQL implicitly declares a cursor for all SQL data manipulation
statements, including queries that return only one row.
Queries that return more than one row, you can explicitly declare a cursor to
process the rows individually.

5.3 Classification of CURSORS


1. Implicit Cursor or Internal Cursor – Managed by Oracle itself or
Internal Process itself.
2. Explicit Cursor or User-defined Cursor - Managed by the
user/Programmer or External Processing.
5.3.1 Implicit Cursor
Oracle uses implicit cursors for its internal processing. Even if we
execute a SELECT statement Oracle reserves a private SQL area in
memory called cursor. Implicit cursor attributes return information about the
execution of an INSERT, UPDATE, DELETE, or SELECT INTO statement.

5.3.2 Implicit Cursor Attributes

Cursor Attributes Cursor Variable Description


Is true if DML statement
%NOTFOUND SQL%NOTFOUND
was not successful
Is true if DML statement was
%FOUND SQL%FOUND
successful
Returns number of rows
%ROWCOUNT SQL%ROWCOUNT
affected by a DML statement

23
Example
Consider the emp table, update employee 'Bhavesh' department to 'web
developer'.

EMP_NO EMP_NAME EMP_DEPT EMP_SALARY


1 Jay Web Developer 4500
2 Ajay Program Developer 3800
3 Bhavesh Program Developer 3400
4 Jigar Web Developer 4200

Example: Implicit cursor

BEGIN
UPDATE emp SET emp_dept=’web developer’
WHERE emp_name=’bhavesh’;
IF SQL%FOUND THEN
dbms_output.put_line(‘found-updated’);
END IF;
IF SQL%NOTFOUND THEN
dbms_output.put_line(‘not found-not updated’);
END IF;
IF SQL%ROWCOUNT>0 THEN
dbms_output.put_line(‘sql%rowcount||’row updated’);
ELSE
dbms_output.put_line(‘no rows updated’);
END IF;
END;
/

24
CHAPTER 6

6. Using Explicit Cursors


Explicit Cursor is declared by the user. The user has to declare the cursor,
open cursor to reserve the memory and fetch the populated data from the
active data set one at a time, apply logic and finally close the cursor.
6.1 Explicit cursor functions
1. Can do row-by-row processing beyond the first row returned by a query.
2. Keep track of which row is currently being processed.
3. Enable the programmer to manually control explicit cursors in the
PL/SQL block.

Note: You cannot reference cursor attributes directly in a SQL statement.

6.2 Working with PL/SQL Cursor

Figure 6.1

6.3 Explicit Cursor Attribute

CURSOR CURSOR VARIABLE DESCRIPTION


ATTRIBUTE
Evaluates to true, if last
%NOTFOUND CURSOR_NAME%NOTFOUND fetch failed, i.e. , no more
rows left
Evaluates to true, if last
%FOUND CURSOR_NAME %FOUND
fetch succeeded
Returns the number of rows
%ROWCOUNT CURSOR_NAME%ROWCOUNT
fetched
Evaluates to true, if the
%ISOPEN CURSOR_NAME%ISOPEN
cursor is open

25
6.3.1 Step for Using Explicit Cursor
1. Declare Cursor
2. Open Cursor
3. Loop
4. Fetch Record into Cursor
5. Exit Loop
6. Close Cursor
1. Declare Cursor:
Syntax

CURSOR cursor_name IS select_statement;

Note:
Do not include the INTO clause in the cursor declaration because it
appears later in the FETCH statement.
If processing rows in a specific sequence is required, use the
ORDER BY clause in the query.
The cursor can be any valid SELECT statement, including joins,
subqueries and so on.

Example

DECLARE
CURSOR emp_cur IS SELECT ename,job,sal FROM emp;
v_ename emp.ename%TYPE;
v_job emp.job%TYPE;
v_sal number;

2. Open Cursor:
Syntax

OPEN cursor_name;

26
The OPEN statement executes the query associated with the cursor,
identifies the active set, and positions the cursor pointer at the first row. The
OPEN statement is included in the executable section of the PL/SQL block.
OPEN is an executable statement that performs the following operations:
1. Dynamically allocates memory for a context area.
2. Parses the SELECT statement.
3. Binds the input variables (sets the values for the input variables by
obtaining their memory addresses).
4. Identifies the active set (the set of rows that satisfy the search
criteria). Rows in the active set are not retrieved into variables when
the OPEN statement is executed. Rather, the FETCH statement
retrieves the rows from the cursor to the variables.
5. Positions the pointer to the first row in the active set.
Note: If the query returns no rows when the cursor is opened, PL/SQL does
not raise an exception. However, you can test the status of the implicit
cursor after a fetch by using the SQL%ROWCOUNT cursor attribute.
For explicit cursors, use <cursor_name>%ROWCOUNT.
Example
DECLARE
CURSOR emp_cur IS SELECT ename,job,sal FROM emp;
v_ename emp.ename%TYPE;
v_job emp.job%TYPE;
v_sal number;
BEGIN
OPEN emp_cur;

3. Fetching Data from the Cursor


Syntax

FETCH cursor_name INTO [ variable1, variable2, ...] |


record_name ];

27
The FETCH statement performs the following operations:
1. Reads the data for the current row into the output PL/SQL variables.
2. Advances the pointer to the next row in the active set.

Note:
1. Include the same number of variables in the INTO clause of the
FETCH statement as the columns in the SELECT statement, and be
sure that the data types are compatible.
2. Match each variable to correspond to the columns positionally.
3. Alternatively, define a record for the cursor and reference the record
in the FETCH INTO clause.
4. (%notfound)Test to see whether the cursor contains rows. If a fetch
acquires no values, there are no rows left to process in the active set
and no error is recorded.

Example

DECLARE
CURSOR EMP_CUR IS SELECT ENAME,JOB,SAL FROM EMP;
V_ENAME EMP.ENAME%TYPE;
V_JOB EMP.JOB%TYPE;
V_SAL NUMBER;
BEGIN
OPEN EMP_CUR;
LOOP
FETCH EMP_CUR INTO V_ENAME,V_JOB,V_SAL;
EXIT WHEN EMP_CUR%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(V_ENAME||V_JOB||V_SAL);
END LOOP;

4. Closing the Cursor:


Syntax
Close cursor_name;

The CLOSE statement disables the cursor, releases the context area, and
undefined the active set. Close the cursor after completing the processing

28
of the FETCH statement. You can reopen the cursor if required. A cursor
can be reopened only if it is closed. If you attempt to fetch data from a cursor
after it has been closed, then an INVALID_CURSOR exception will be
raised.

Note: Although it is possible to terminate the PL/SQL block without closing


cursors, you should make it a habit to close any cursor that you declare
explicitly to free up resources. There is a maximum limit on the number of
open cursors per session, which is determined by the OPEN_CURSORS
parameter in the database parameter file. (OPEN_CURSORS=50 by
default.)

Example

DECLARE
CURSOR EMP_CUR IS SELECT ENAME,JOB,SAL FROM EMP;
V_ENAME EMP.ENAME%TYPE;
V_JOB EMP.JOB%TYPE;
V_SAL NUMBER(10,2);
BEGIN
OPEN EMP_CUR;
LOOP
FETCH EMP_CUR INTO V_ENAME,V_JOB,V_SAL;
EXIT WHEN EMP_CUR%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(V_ENAME||V_JOB||V_SAL);
END LOOP;
CLOSE EMP_CUR;
END;
/

6.4 Cursor using FOR loop


PL/SQL cursor for loop is a one of the advantages for the loop to be
continued till row not found. Cursor FOR Loop is used in a PL/SQL block or
procedure to let PL/SQL do most of the things for us. Cursor For Loop is
used instead of the OPEN, FETCH, and CLOSE statements. No need to
declare variable for storing the result.

29
Example
DECLARE
CURSOR C_EMP IS SELECT ENAME,SAL,COMM FROM EMP;
TOTAL NUMBER(10);
BEGIN
FOR EMP_REC IN C_EMP
LOOP
TOTAL := EMP_REC.SAL + EMP_REC.COMM;
DBMS_OUTPUT.PUT_LINE(C_EMP%ROWCOUNT||' '||TOTAL);
EXIT WHEN C_EMP%NOTFOUND;
END LOOP;
END;

6.5 Cursor Using Subqueries


A subquery is a query (usually enclosed by parentheses) that appears
within another SQL data manipulation statement. When evaluated, the
subquery provides a value or set of values to the statement. Often,
subqueries are used in the WHERE clause. For example, the following
query returns employees not located in Chicago:
DECLARE
CURSOR C1 IS SELECT EMPNO, ENAME FROM EMP
WHERE DEPTNO IN (SELECT DEPTNO FROM DEPT
WHERE LOC <> 'CHICAGO');
V_EMPNO EMP.EMPNO%TYPE;
V_ENAME EMP.ENAME%TYPE;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO V_EMPNO,V_ENAME;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(V_EMPNO||V_ENAME);
END LOOP;
CLOSE C1;
END;
6.6 Cursor with Parameters
PL/SQL Parameterized cursor passes the parameters into a cursor and
uses them in to query. Default values are assigned to the Cursor
parameters and scope of the parameters is local. Parameters datatypes are
the same as scalar datatypes without size.

30
Syntax

CURSOR cursor_name [( parameter_name datatype, ...)]


IS
select_statement;

1) Pass parameter values to a cursor when the cursor is opened and the
query is executed.
2) Open an explicit cursor several times with a different active set each
time.

Example

DECLARE
CURSOR X(DNO NUMBER) IS SELECT ENAME,SAL FROM EMP
WHERE
DEPTNO=DNO;
EN EMP.ENAME%TYPE;
S EMP.SAL%TYPE;
BEGIN
OPEN X(&DNO);
LOOP
FETCH X INTO EN,S;
EXIT WHEN X%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(EN||S);
END LOOP;
CLOSE X;
END;

6.7 The FOR UPDATE Clause


If there are multiple sessions for a single database, there is the possibility
that the rows of a particular table were updated after you opened your
cursor. You see the updated data only when you reopen the cursor.
Therefore, it is better to have locks on the rows before you update or delete
rows. You can lock the rows with the FOR UPDATE clause in the cursor
query. This statement allows you to lock the records in the cursor result set.
You are not required to make changes to the records in order to use this
statement. The record locks are released when the next commit or rollback
statement is issued.

31
Syntax

SELECT ... FROM TABLE_NAME


...
FOR UPDATE [OF column_name] [NOWAIT | WAIT n];

1. Explicit locking lets you deny access for the duration of a transaction.
2. Lock the rows before the update or delete.

Example: FOR UPDATE


SQL> SELECT * FROM emp1 FOR UPDATE;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
……………………………………………………………………………..
7839 KING …….
7698 BLAKE …..

SQL> UPDATE emp1 SET sal = 1;


14 rows updated

SQL> GRANT ALL ON emp1 TO username;


SQL> CONNECT username / password
SQL>SELECT * FROM username.EMP1;
SQL> UPDATE emp1 SET sal = 1000;|
SQL> SHOW USER
USER is “VIMAL”
SQL>COMMIT;
commit complete.

SQL> CONNECT username / password


SQL>SELECT * FROM username.EMP1;
SQL> UPDATE emp1 SET sal = 1000;
14 rows updated.

32
Example
DECLARE
CURSOR C IS SELECT EMPNO,ENAME FROM CEMP WHERE
DEPTNO=20 FOR UPDATE;
BEGIN
FOR T IN C LOOP
DELETE FROM CEMP WHERE CURRENT OF C;
END LOOP;
END;

6.7.1 FOR UPDATE – NOWAIT


The optional NOWAIT keyword tells the Oracle server not to wait if
requested another user has locked rows. Control is immediately returned to
your program so that it can do other work before trying again to acquire the
lock. If you omit the NOWAIT keyword, the Oracle server waits until the
rows are available.

Example: FOR UPDATE - NOWAIT

SQL> SELECT * FROM emp1 FOR UPDATE;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


……………………………………………………………………………..

7839 KING …….


7698 BLAKE …..

SQL> UPDATE emp1 SET sal = 1;

14 rows updated

SQL> CONNECT username / password

SQL>SELECT * FROM username.EMP1 FOR UPDATE NOWAIT;


….
14 rows selected.

SQL> UPDATE emp1 SET sal = 1000;

ERROR at line 1:
ORA-00054: resource busy and acquire with NOWAIT specified.

33
Example: The FOR UPDATE Clause

DECLARE
CURSOR C2 IS SELECT SAL FROM EMP FOR UPDATE OF SAL
NOWAIT;
BEGIN
FOR E IN C2 LOOP
UPDATE EMP SET SAL=E.SAL+100
WHERE CURRENT OF C2;
END LOOP;
COMMIT;
END;

6.7.2 The WHERE CURRENT OF Clause


Syntax
WHERE CURRENT OF cursor

1 Use cursors to update or delete the current row.


2 Include the FOR UPDATE clause in the cursor query to lock the rows
first.
3 Use the WHERE CURRENT OF clause to reference the current row
from an explicit cursor.

The where current of clause in an Update or Delete statement states that


the most recent row fetched from the table should be updated or deleted.
We must declare the cursor with the for update clause to use this feature.
Inside a cursor loop, WHERE CURRENT Of allows the current row to be
directly updated.

When the session opens a cursor with the For Update clause, all rows in the
return set will hold row-level exclusive locks. Other sessions can only query
the rows, but they cannot update, delete or select with for update.
Oracle provides the FOR UPDATE clause in SQL syntax to allow the
developer to lock a set of oracle rows for the duration of a transaction.

34
Example
The following example opens a cursor for employees and updates the
commission, if There is no commission assigned based on the salary level.

DECLARE
CURSOR C1 IS SELECT EMPNO,ENAME,SAL FROM EMP
WHERE COMM IS NULL FOR UPDATE OF COMM;
V_COMM NUMBER(10,2);
BEGIN
FOR I IN C1 LOOP
IF I.SALARY<5000 THEN
V_COMM := I.SALARY*0.25;
ELSIF SALARY<10000 THEN
V_COMM := I.SALARY*0.20;
ELSIF SALARY<30000 THEN
V_COMM := I.SALARY*0.15;
ELSE
V_COMM := I.SALARY*0.12;
END IF;
UPDATE EMP SET COMM=V_COMM WHERE CURENT OF C1;
END LOOP;
END;
/

35
CHAPTER 7

7. HANDLING EXCEPTIONS

7.1 What is an Exception


In PL/SQL, errors or warnings raised during execution are called as
exceptions. There are number of reasons due to which run time errors may
be raised during the execution of a PL/SQL block. Although you cannot
anticipate all possible errors, you can plan to handle certain kinds of errors,
meaningful to your PL/SQL program. With many programming languages,
unless you disable error checking, a runtime error such as stack overflow or
division by zero steps normal processing and returns control to the
operating system. With PL/SQL, a mechanism called exception handling
lets you "bulletproof" your program so that it can continue operating in the
presence of errors.
When an error occurs, an exception is raised; normal execution is stopped
and control is transferred to an exception-handling section of PL/SQL
program. A specific section can be defined in the program to handle
exceptions. Separate subroutines called exception handlers can be created
to perform all exception processing. Once an exception is raised and
control is transferred to the exception part of a program, it cannot return to
the execution part of the program again. Exceptions are the ways in which
Oracle could handle runtime errors in a PL/SQL block. Exceptions are
always useful to debug the code as well as ensure a smooth end for a
Program without interrupting the calling Program/Block.
An exception can be raised:
1 Implicitly by the Oracle server
2 Explicitly by the program

36
7.2 Handling of Errors
Errors are handles in two ways,
1. To trap the error.
2. To propagate to the calling environment.
7.2.1 Trapping an exception
If the exception is raised in the executable section of the block, processing
branches to the corresponding exception handler in the exception section of
the block. If PL/SQL successfully handles the exception, then the exception
does not propagate to the enclosing block or environment. The PL/SQL
block terminates successfully.
7.2.2 Propagating an Exception
If the exception is raised in the executable section of the block and there is
no corresponding exception handler, the PL/SQL block terminates with
failure and the exception is propagated to the calling environment.

7.3 Exception Types


There are two types of exceptions:
1. Implicitly raised exceptions
2. Explicitly raised exceptions

7.3.1 Implicitly raised exceptions


PL/SQL provides a predefined set of exceptions that are implicitly raised
(automatically raised) by the system at run time in that case an error is
encountered in PL/SQL.
There are two types of implicitly raised exceptions:
1. Predefined Oracle Server /Named system Exception
2. Non-predefined Oracle Server/ Unnamed system exception

37
7.3.2 Explicitly raised exceptions:
User can also define their own set of exceptions called as User-defined
exceptions and explicitly raise them on encountering an error condition.

User-defined Exception

Exception Description Directions for Handling


Predefined One of approximately You need not declare these
Oracle server 20 errors that occur exceptions. They are predefined
most often in PL/SQL by the Oracle server and are
code. raised implicitly.
Non-predefined Any other standard Declare within the declarative
Oracle server Oracle Server error section and enable the Oracle
server
to raise them implicitly.
User-defined A condition that the Declare in the declarative
Developer determines section and raise explicitly
is abnormal

Syntax

EXCEPTION WHEN exception1 [OR exception2 ………] THEN


Statement1;
Statement2;
[WHENexception3 [OR exception4 ………] THEN
Statement1;
Statement2;
..…………..]
[WHEN OTHERS THEN
Statement1;
Statement2;
..…].

38
7.4 Some Guidelines to Trap Exception
Begin the exception-handling section of the block with the keyword
EXCEPTION.
Define several exception handlers, each with its own set of actions,
for the block.
When an exception occurs, PL/SQL processes only one handler
before leaving the block.
Place the OTHERS clause after all other exception-handling
clauses.
You can have at most one OTHERS clause.
Exceptions cannot appear in assignment statements or SQL
statements.

7.5 Advantages of Exceptions


Using exceptions for error handling has several advantages.
These are:
1. With exception handling no need to check errors after each SQL
command. So, errors processing is not mixed with normal
processing. Without exception handling, every time you issue a
command, you must check for execution errors.
2. Exceptions improve readability by letting you isolate error-handling
routines.
3. Exceptions also improve reliability. You need not worry about
checking for an error at every point it might occur. Just add an
exception handler to your PL/SQL block. If the exception is ever
raised in that block (or any sub-block), you can be sure it will be
handled.
4. All error conditions can be captured with OTHERS clause in the
exception handler, which provides a mechanism to process all
expected errors as well as those unforeseen.

39
7.6 Named System Exceptions (or) Predefined Error
Trapping Predefined Oracle Server errors
PL/SQL has a set of exceptions that are predefined for the common Oracle
system errors. Predefined exceptions are used to detect and handle Oracle
system errors that occur internally at program run time. An internal
exception is raised implicitly whenever your PL/SQL program violates an
Oracle rule or exceeds a system-dependent limit. Every Oracle error has a
number, but exceptions must be handled by name. So, PL/SQL predefines
some common Oracle errors as exceptions. For example, PL/SQL raises
the predefined exception NO_DATA_FOUND if a SELECT INTO statement
returns no rows.
You can write handlers for predefined exceptions using the names in
the following list.
Oracle
Exception Raised When
Error
A SELECT INTO statement returns
no rows, or your program
NO_DATA_FOUND references a deleted element in a ORA-01403
nested table or an uninitialized
element in an index-by table.
A SELECT INTO statement returns
TOO_MANY_ROWS ORA-01422
more than one row.
ZERO_DIVIDE A program attempts to divide a ORA-01476
number by zero.
A program attempts a cursor
INVALID_CURSOR operation that is not allowed, such ORA-01001
as closing an unopened cursor.
CURSOR_ALREADY_OPEN A program attempts to open an ORA-06511
already open cursor. A cursor must
be closed before it can be
reopened. A cursor FOR loop
automatically opens the cursor to
which it refers, so your program
cannot open that cursor inside the
loop.
A program attempts to store
duplicate values in a database
DUP_VAL_ON_INDEX ORA-00001
column that is constrained by a
unique index.

40
An arithmetic, conversion,
VALUE_ERROR truncation, or size-constraint error ORA-06502
occurs.
In a SQL statement, the conversion
of a character string into a number
INVALID_NUMBER ORA-01722
fails because the string does not
represent a valid number.

For Example: Suppose if a NO_DATA_FOUND exception is raised in a


program, we can write a code to handle the exception as given below.

DECLARE
v_ename VARCHAR2(20);
v_job VARCHAR2(30);
v_empno NUMBER(10);
BEGIN
SELECT ename,job INTO v_ename,v_job FROM emp
WHERE empno=&v_empno;
DBMS_OUTPUT.PUT_LINE(v_ename||v_job);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE(‘Enter valid Employee Number’);
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE(‘More than 1 record available
,Duplicate EMPNO is existing');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Technical Error, check the data ');
END;

7.7 Unnamed System Exceptions


Trapping Non-Predefined Oracle Server Errors
Non-predefined exceptions are similar to predefined exceptions; however,
they are not defined as PL/SQL exceptions in the Oracle server. They are
standard Oracle errors. You create exceptions with standard Oracle errors
by using the PRAGMA EXCEPTION_INIT function. Such exceptions are
called non-predefined exceptions. You can trap a non-predefined Oracle
server error by declaring it first. The declared exception is raised implicitly.
In PL/SQL, PRAGMA EXCEPTION_INIT tells the compiler to associate an
exception name with an Oracle error number. That enables you to refer to
any internal exception by name and to write a specific handler for it.

41
Note: PRAGMA (also called pseudo instructions) is the keyword that
signifies that the statement is a compiler directive, which is not processed
when the PL/SQL block is executed. Rather, it directs the PL/SQL compiler
to interpret all occurrences of the exception name within the block as the
associated Oracle server error number. Those system exception for which
oracle does not provide a name is known as unnamed system exception.
These exceptions do not occur frequently.

These Exceptions have a code and an associated message.


There are two ways to handle unnamed system exceptions:
1. By using the WHEN OTHERS exception handler, or
2. By associating the exception code to a name and using it as a named
exception.
We can assign a name to unnamed system exceptions using a Pragma
called EXCEPTION_INIT. EXCEPTION_INIT will associate a predefined
Oracle error number to a programmer defined exception name.

Steps to be followed to use unnamed system exceptions are


They are raised implicitly.
If they are not handled in WHEN others they must be handled
explicitly.
To handle the exception explicitly, they must be declared using
Pragma EXCEPTION_INIT and handled referencing the
user-defined exception name in the exception section.

42
The general syntax to declare unnamed system exception using
EXCEPTION_INIT is:
Syntax
DECLARE
exception_name EXCEPTION;
PRAGMA EXCEPTION_INIT (exception_name, Err_code);
BEGIN
Execution section
EXCEPTION
WHEN exception_name THEN
handle the exception
END;

EXAMPLE

DECLARE
V_ENAME VARCHAR2(20);
V_SAL NUMBER(10);
XX EXCEPTION;
PRAGMA EXCEPTION_INIT(XX,-01400);
BEGIN
V_ENAME :='&ENAME';
V_SAL:=&SAL;
INSERT INTO EMP(ENAME,SAL) VALUES(V_ENAME,V_SAL);
COMMIT;
EXCEPTION
WHEN XX THEN
DBMS_OUTPUT.PUT_LINE('NULL VALUES CANNOT INSERT
TO EMPNO’);
END;
/

7.8 User-defined Exceptions


Apart from system exceptions we can explicit define exceptions based on
business rules. These are known as user-defined exceptions.
User defined exceptions are used to handle error conditions specific to an
application program. For example, in case of Library system the date of
issue of a book cannot be more than date of return, if that happens then an
error must be raised explicitly by the application programmer and that
facility is developed with the help of User defined exceptions.

43
Unlike predefined exceptions, user-defined exceptions must be declared
and must be raised explicitly by RAISE statements.
7.8.1 Steps to trap user-defined exceptions
1. Declare the name for the user-defined exception within the declarative
section.
Syntax
Exception_name EXCEPTION;

Here exception_name is the name of the exception.

2. Use the RAISE statement to raise the exception explicitly within the
executable section.
Syntax
RAISE exception_name;

Here: exception is the previously declared exception.

3. Reference the declared exception within the corresponding exception


handling routine.
Example
DECLARE
V_ENAME VARCHAR2(10) :='&NAME';
V_DEPTNO NUMBER(5) :=&DNO;
V_SAL NUMBER(10) :=&SAL;
V_COUNT NUMBER(5);
XX EXCEPTION;
BEGIN
SELECT COUNT(*) INTO V_COUNT FROM TEST
WHERE ENAME=V_ENAME;
IF V_COUNT>=1 THEN
RAISE XX;
ELSE
INSERT INTO TEST VALUES(V_ENAME,V_DEPTNO,V_SAL);
COMMIT;
END IF;
EXCEPTION
WHEN XX THEN
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NAME ALREADY EXISTING');
END;

44
7.9 RAISE_APPLICATION_ERROR
It is a built-in procedure in oracle, which is used to display the user-defined
error messages along with the error number whose range is in between
-20000 and -20999.
Whenever a message is displayed using RAISE_APPLICATION_ERROR,
all previous transactions which are not committed within the PL/SQL Block
are rolled back automatically (i.e. change due to INSERT, UPDATE, or
DELETE statements).
RAISE_APPLICATION_ERROR raises an exception but does not handle it.
RAISE_APPLICATION_ERROR is used for the following reasons,
To create a unique id for an user-defined exception.
To make the user-defined exception look like an Oracle error.
The General Syntax to use this procedure is:

RAISE_APPLICATION_ERROR (error_number,
error_message);

The Error number must be between -20000 and -20999.


The Error_message is the message you want to display when the
error occurs.

7.9.1 Steps to be followed to use RAISE_APPLICATION_ERROR


procedure:
1 Declare a user-defined exception in the declaration section.
2 Raise the user-defined exception based on a specific business rule
in the execution section.
3 Finally, catch the exception and link the exception to a user-defined
error number in RAISE_APPLICATION_ERROR.

45
Example
DECLARE
V_DEPTNO NUMBER;
BEGIN
DELETE FROM DEPT WHERE DEPTNO=&V_DEPTNO;
IF SQL%NOTFOUND THEN
RAISE_APPLICATION_ERROR (-20200, ' INVALID DEPARTMENT
NUMBER');
END IF;
END;
/

7.9.2 Retrieving the Error Code and Error Message: SQLCODE and
SQLERRM
In an exception handler, you can use the functions SQLCODE and
SQLERRM to find out which error occurred and to get the associated
error message.
For internal exceptions, SQLCODE returns the number of the Oracle
error. The number that SQLCODE returns is negative unless the
Oracle error is no data found, in which case SQLCODE returns
+100. SQLERRM returns the corresponding error message. The
message begins with the Oracle error code.
For user-defined exceptions, SQLCODE returns +1 and SQLERRM
returns the message User-Defined Exception.
If no exception has been raised, SQLCODE returns zero and
SQLERRM returns the message : ORA-0000: normal, successful
completion.
You can pass an error number to SQLERRM, in which case
SQLERRM returns the message associated with that error number.
Make sure you pass negative error numbers to SQLERRM.

46
You cannot use SQLCODE or SQLERRM directly in a SQL statement.
Instead, you must assign their values to local variables, then use the
variables in the SQL statement, as the following example shows:

Example

DECLARE
V_ERRCODE NUMBER(10);
V_ERRMSG VARCHAR(1000);
BEGIN
DELETE FROM DEPT WHERE DEPTNO=10;
EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
V_ERRCODE:=SQLCODE;
V_ERRMSG:=SQLERRM;
DBMS_OUTPUT.PUT_LINE(V_ERRCODE||CHR(10)||V_ERRMSG);
END;
/

47
CHAPTER 8

8. Stored Procedure
A PL/SQL subprogram is a named PL/SQL block that can be invoked with a
set of parameters (if it has them). A subprogram can be either a procedure
or a function. Typically, you use a procedure to perform an action and a
function to compute and return a value.
You can create a subprogram either at schema level, inside a package, or
inside a PL/SQL block (which can be another subprogram).
A subprogram created at schema level is a standalone stored subprogram.
You create it with the CREATE PROCEDURE or CREATE FUNCTION
statement. It is stored in the database until you drop it with the DROP
PROCEDURE or DROP FUNCTION statement.
A subprogram created inside a package is a packaged subprogram. It is
stored in the database until you drop the package with the DROP
PACKAGE statement.
A subprogram created inside a PL/SQL block is a nested subprogram. You
can either declare and define it at the same time, or you can declare it first
(forward declaration) and then define it later in the same block. A nested
subprogram is stored in the database only if it is nested in a standalone or
packaged subprogram.

8.1 What is a stored Procedure


As we have seen in the introduction to PL/SQL that there are two types of
PL/SQL blocks – anonymous and stored procedures.
A procedure is a group of PL/SQL statements that you can call by name. It
is invoked using the name. Each procedure is meant for a specific purpose.
A stored procedure is stored in the database as an object. It is also called as
database procedure as it is stored in the database. A procedure may take
one or more parameters. If a procedure takes parameters then these
parameters are to be supplied at the time of calling the procedure.

48
When you create a Procedure or function, you have to define these three
parameters.
1) IN type parameter: These types of parameters are used to send values
to stored procedures.
2) OUT type parameter: These types of parameters are used to get values
from stored procedures. This is similar to a return type in functions.
3) IN OUT parameter: These types of parameters are used to send values
and get values from stored procedures.
NOTE: If a parameter is not explicitly defined a parameter type, then by
default it is an IN type parameter.

8.2 Creating a stored procedures


Syntax
CREATE [OR REPLACE] PROCEDURE name
[(parameter[,parameter, ...])]
{IS |AS}
[local declarations]
BEGIN
executable statements
[EXCEPTION
exception handlers]
END [name];

Each component is used in the following ways:

OR REPLACE - Oracle creates procedure even though the procedure is


not valid but it displays the message saying that the procedure is created
with errors. Then you have to rectify the errors and recreate the procedure.
If OR REPLACE option is not given Oracle doesn’t allow you to replace an
existing stored procedure. So, it is better you use OR REPLACE option so
that the existing invalid version of the procedure will be replaced with the
valid version.

49
Name
The name of the procedure comes directly after the keyword
PROCEDURE.
Parameters
An optional list of parameters that you define to both pass information into
the procedure and send information out of the procedure, back to the calling
program.
Declaration statements (Optional)
The declarations of local identifiers for that procedure. If you do not have
any declarations, then there will not be any statements between the IS and
BEGIN statements.
Executable statements
The statements that the procedure executes when it is called. You must
have at least one executable statement after the BEGIN and before the
END or EXCEPTION keywords.
Exception handler statements (Optional)
The optional exception handlers for the procedure. If you do not explicitly
handle any exceptions, then you can leave out the EXCEPTION keyword
and simply terminate the execution section with the END keyword.

8.3 Advantages of stored procedures


Stored procedures and functions offer the following benefits.
8.3.1 Reduced network traffic
Stored procedures are stored in the database on the server. In order to
invoke a stored procedure a client has to use only the name of the stored
procedure. This results in reduced network traffic because only the name is
passed to server and not the entire PL/SQL block.

8.3.2 Better Performance


Without PL/SQL, Oracle must process SQL statements one at a time.
Programs that issue many SQL statements require multiple calls to the
database, resulting in significant network and performance overhead.

50
With PL/SQL, an entire block of statements can be sent to Oracle at one
time. This can drastically reduce network traffic between the database and
an application. PL/SQL blocks and subprograms to group SQL statements
before sending them to the database for execution. PL/SQL also has
language features to further speed up SQL statements that are issued
inside a loop.
PL/SQL stored procedures are compiled once and stored in executable
form, so procedure calls are efficient. Because stored procedures execute
in the database server, a single call over the network can start a large job.
This division of work reduces network traffic and improves response times.
Stored procedures are cached and shared among users, which lowers
memory requirements and invocation overhead.

8.3.3 Full Portability


Applications written in PL/SQL can run on any operating system and
platform where the Oracle database runs. With PL/SQL, you can write
portable program libraries and reuse them in different environments.

8.3.4 Easy Maintenance


If there is any change in the application, only the concerned stored
procedures are to be modified to incorporate the change. As all the clients
access stored procedures, they automatically use the modified definition.
You only have to change business login once in the stored procedure.
Therefore stored procedures improve the integrity and consistency of your
applications.

8.3.5 Tight Security


PL/SQL stored procedures move application code from the client to the
server, where you can protect it from tampering, hide the internal details,
and restrict who has access. For example, you can grant users access to a
procedure that updates a table, but not grant them access to the table itself

51
or to the text of the UPDATE statement. Triggers written in PL/SQL can
control or record change to data, making sure that all changes obey your
business rules.
Stored procedures help enforcement of data security. You can allow users
to access only the stored procedures and not the table that are manipulated
by stored procedures. Whenever a stored procedure runs, it runs with the
privileges of the owner and not the user running it. Because users only
have the privilege to execute the procedure and not the privileges to access
the underlying tables, it increases security.

8.4 Show Errors


During the creation of the procedure if there are any errors, Oracle displays
the message saying procedure is created but with error with the following
message:
Warning: Procedure created with compilation errors.
In order to display errors in the most recent CREATE PROCEDURE
statement, use SHOW ERRORS (or) SHOW ERR (or) SHOW ERROR
PROCEDURE PROCEDURE_NAME command.
SQL>SHOW ERR
8.5 EXECUTE command
A procedure can be executed using EXECUTE command. To execute a
procedure either you must be the owner of the procedure or you must have
EXECUTE privilege on the procedure.
The following stored procedure inserts a new record into DEPARTMENT
table with the given department number, department name and location.
Example
CREATE OR REPLACE PROCEDURE P_department (p_deptno
NUMBER, p_dname varchar2, p_loc varchar2)
IS
BEGIN
INSERT INTO department VALUES (p_deptno,p_dname,p_loc);
COMMIT;
END;
/

52
Once a stored procedure is stored in the database, it can be invoked using
EXECUTE command by using the name of the procedure.
The following example shows how to invoke DEPARTMENT procedure.
EXECUTE p_department(10,’ACCOUNTING’,’NEW YORK’);
PL/SQL procedure successfully completed.

In the above example, P_DEPARTMENT is invoked by passing 10,


ACCOUNTING and NEW YORK. It inserts a new row into DEPARTMENT
table.

8.6 Getting source code


It is possible to see the source code of stored procedures and function by
using USER_SOURCE data dictionary.
The following SELECT command will display the source code of
p_department stored procedure.

SELECT text FROM user_source WHERE name = 'P_DEPARTMENT';


Output:
TEXT
------------------------------------------------------------------------
PROCEDURE P_department (p_deptno NUMBER, p_dname varchar2,
p_loc varchar2)
IS
BEGIN
INSERT INTO department VALUES (p_deptno,p_dname,p_loc);
COMMIT;
END;
/

8.7 Privileges required


To create a stored procedure, you must have CREATE PROCEDURE
system privilege. You must also have required object privileges on the
objects that are referred in the procedure in order to successfully compile
the procedure.

53
8.8 Types of Parameters
Parameters of a procedure are of two types.
1 Formal parameters
2 Actual Parameters

8.8.1 Formal Parameters


The parameters declared in the definition of procedure are called as
FORMAL PARAMETER. They receive the values sent while calling the
procedure.

PROCEDURE P_department (p_deptno NUMBER, p_dname varchar2,


p_loc varchar2)
is
begin
…..
end;

In the above procedure p_deptno, p_dname,p_loc parameters are called as


formal parameters.

8.8.2 Actual Parameters


The values given within parentheses while calling the procedure are called
as actual Parameters.
p_department(10,’ACCOUNTING’,’NEW YORK’);
These values are copied to the corresponding formal parameters
p_deptno,p_dname and p_loc.
8.9 Passing Parameters
Positional: Lists the actual parameters in the same order as the formal
parameters.
Example: exec p_department(10,’ACCOUNTING’,’NEW YORK’);
Named: Lists the actual parameters in arbitrary order and uses the
association operator (=>) to associate a named formal parameter with its
actual parameter.

54
Example:
exec p_department(p_detno=>10, p_dname=>’ACCOUNTING’,
p_loc=>’NEW YORK’);
Combination: Lists some of the actual parameters as positional and some
as named.
Example:
exec p_department(10,p_dname=>’ACCOUNTING’,p_loc=>’NEW
YORK’);

Example
Procedure With IN Parameter
Example to insert student serial number, Name, subject1 and subject2
marks in marks table

CREATE OR REPLACE PROCEDURE p_marks(p_sno number,


p_name VARCHAR2,p_m1 NUMBER,p_m2 NUMBER)
IS
v_tot NUMBER(3);
v_grade VARCHAR(20);
v_count NUMBER(3);
xx EXCEPTION;
BEGIN
SELECT count(*) INTO v_count FROM marks WHERE rno=p_sno;
IF (v_count>=1) THEN
raise v;
ELSE
v_tot:=p_m1+p_m2;
IF(p_m1>=40 and p_m2>=40) THEN
v_grade :='pass';
ELSE
v_grade :='fail';
END IF;
END IF;
INSERT INTO sample VALUES
(p_sno,p_name,p_m1,p_m2,v_tot,v_grade);
EXCEPTION
WHEN xx THEN
DBMS_OUTPUT.PUT_LINE('sno already exists');
END ;

55
Example
CALLING PRIVATE PROCEDURE INSIDE A PROCEDURE

CREATE OR REPLACE PROCEDURE PYY


(V_NAME IN VARCHAR,V_JOB OUT VARCHAR)
IS
BEGIN
SELECT JOB INTO V_JOB FROM EMP WHERE ENAME =V_NAME;
END;
/

CREATE OR REPLACE PROCEDURE PXX1


(V_EMPNO NUMBER,V_NAME OUT VARCHAR,V_SAL OUT NUMBER)
IS
EN VARCHAR(20);
S NUMBER;
X NUMBER;
---PRIVATE PROCEDURE
PROCEDURE PRIV(V_SAL NUMBER,V_DNO OUT NUMBER) IS
BEGIN
SELECT DEPTNO INTO V_DNO FROM EMP
WHERE SAL=V_SAL;
END PRIV;
BEGIN
SELECT ENAME,SAL INTO EN,S FROM EMP
WHERE EMPNO=V_EMPNO;
PYY(EN,V_NAME);-----CALLING PUBLIC PROCEDURE
END;
/
PROCEDURE USING IN AND OUT PARAMETER
CREATE OR REPLACE PROCEDURE P5
(P_NO IN NUMBER,P_NAME OUT VARCHAR,P_JOB OUT VARCHAR)
IS
BEGIN
SELECT ENAME,JOB INTO P_NAME,P_JOB FROM EMP
WHERE EMPNO=P_NO;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('INVALID EMPNO');
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('MORE THAN ONE ROW IS THERE
IN EMP TABLE OF SAME EMPNO');
END;
/

56
--TO RUN THE ABOVE PROGRAM
VARIABLE AA VARCHAR2(20)
VARIABLE BB VARCHAR2(20)

EXEC P5(7839,:AA,:BB);

8.10 Recompiling
Stored procedures and functions are compiled at the time of creation and
stored in the compiled form. If a procedure becomes invalid afterwards, it is
to be recompiled before it is executed. Oracle implicitly compiles the
procedure when an invalid procedure is referred. However, it is possible to
explicitly recompile.
In order to recompile a stored procedure use ALTER PROCEDURE and
ALTER FUNCTION to recompile a procedure and function respectively.
ALTER PROCEDURE procedurename COMPILE;
ALTER FUNCTION functionname COMPILE;
The following sequence will illustrate the importance of recompilation.
Assume user SCOTT has created P_DEPARTMENT procedure as follows

CREATE OR REPLACE PROCEDURE P_DEPARTMENT (P_DEPTNO


NUMBER, P_DNAME VARCHAR2, P_LOC VARCHAR2)
IS
BEGIN
INSERT INTO DEPARTMENT
VALUES(P_DEPTNO,P_DNAME,P_LOC);
COMMIT;
END;
/

Since SCOTT doesn’t have INSERT privilege on department table of user


BOOK, the procedure is created but marked as invalid. You can see the
status of the procedure using the following command.
SQL>select status from user_objects
where object_name = 'DEPARTMENT';
STATUS
--------------
INVALID

57
Now, user BOOK has granted INSERT privilege on DEPARTMENT
table to SCOTT as follows:

SQL> Grant Insert on Department to Scott;

Then any subsequent reference to p_department procedure in SCOTT will


implicitly recompile the procedure. But in order to avoid extra time taken to
recompile the procedure at runtime, it can be recompiled using ALTER
PROCEDURE command as follows:

SQL> ALTER PROCEDURE p_department COMPILE;


After recompilation, the procedure will have status VALID as provide by the
following query.

SQL> select status from user_objects


where object_name = 'DEPARTMENT';
STATUS
-------
VALID

58
CHAPTER 9
9. Stored Functions
A function is a named PL/SQL Block, which is similar to a procedure. The
major difference between a procedure and a function is, a function must
always return a value, but a procedure may or may not return a value.
The General Syntax to create a function is:

CREATE [OR REPLACE] FUNCTION function_name [parameters]


RETURN return_datatype;
IS
Declaration_section
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;

Return Type:
1 The header section defines the return type of the function. The return
datatype can be any of the oracle datatype like varchar, number etc.
2 The execution and exception section both should return a value,
which is of the datatype defined in the header section.

Function mostly used for calculation purpose.

Note: Although the OUT and INOUT parameter modes can be used with
functions, it is not good programming practice to use them with functions.
However, if you need to return more than one value from a function,
consider returning the values in a composite data structure such as a
PL/SQL record or a PL/SQL table.

59
CREATE OR REPLACE FUNCTION F1(P_SAL IN NUMBER)
RETURN NUMBER
IS
TAX NUMBER(3);
BEGIN
IF P_SAL>3000 THEN
TAX:=P_SAL*.03;
ELSE
TAX:=P_SAL*.01;
END IF;
RETURN TAX;
END;
/
--To return a function value we have to use BIND variable.

9.1 How to execute a PL/SQL Function


A function can be executed in the following ways.
--Bind Variable
var xx number

--Method I
exec :xx:=f1(4000);

--Method II -- As a part of a SELECT statement

SELECT EMPNO,ENAME,SAL,F1(SAL) FROM EMP;

-- Method III

UPDATE EMP SET SAL=F1(5000)


WHERE EMPNO = 7876 ;

--Method IV

In a PL/SQL Statements like,


EXECUTE dbms_output.put_line(employer_details_func);
This line displays the value returned by the function.

60
--Method V

--Calling through procedure

CREATE OR REPLACE PROCEDURE P1(P_EMPNO NUMBER)


IS
V_SAL NUMBER(10);
P_SAL NUMBER(10);
BEGIN
SELECT SAL INTO P_SAL FROM EMP
WHERE EMPNO=P_EMPNO;
V_SAL :=F1(P_SAL);
DBMS_OUTPUT.PUT_LINE(V_SAL);
END;
/

In the example we are retrieving the ‘salary’ of employee with variable


‘p_sal’. The return type of the function is NUMBER. The function returns the
'TAX' which is of type NUMBER as the return value.

EXAMPLE
using boolean values
CREATE OR REPLACE FUNCTION FB(A VARCHAR)
RETURN BOOLEAN IS
S NUMBER;
BEGIN
SELECT SAL INTO S FROM EMP WHERE EMPNO=A;
IF (S>=3000) THEN
RETURN TRUE;
ELSE
RETURN FALSE;
END IF;
END;

DECLARE
B BOOLEAN;
BEGIN
B:=FB(&A);
IF(B=TRUE) THEN
DBMS_OUTPUT.PUT_LINE('SAL>=3000');
ELSE
DBMS_OUTPUT.PUT_LINE('SAL<=3000');
END IF;
END;

61
9.2 Calling function inside a function

CREATE OR REPLACE FUNCTION fx2(v_ename varchar)


RETURN number is
en number;
BEGIN
select sal into en from emp where ename=v_ename;
return en;
END;
/

CREATE OR REPLACE FUNCTION FX(V_EMPNO NUMBER)


RETURN VARCHAR IS
EN VARCHAR(30);
V VARCHAR(30);
BEGIN
SELECT ENAME INTO EN FROM EMP WHERE
EMPNO=V_EMPNO;
V:=FX2(EN);
RETURN V;
END;
/

62
CHAPTER 10

10. PACKAGE

10.1 Introducing to PL/SQL Package


PL/SQL package is a group of related STORED FUNCTION,
PROCEDURE, TYPES, CURSORS etc. PL/SQL package is like a library
once written stored in the Oracle database and can be used by many
applications.

10.2 The Benefits of Packages


10.2.1 Enforced Information Hiding
When you build a package, you decide which of the package elements are
public (can be referenced outside of the package) and which are private
(available only within the package itself). You also can restrict access to the
package to only the specification. In this way, you use the package to hide
the implementation details of your programs.

10.2.2 Object-Oriented Design


While PL/SQL does not yet offer full object-oriented capabilities, packages
do offer the ability to follow many object-oriented design principles. The
package gives developers very tight control over how the modules and data
structures inside the package can be accessed.

10.2.3 Top-Down Design


A package's specification can be written before its body. You can, in other
words, design the interface to the code hidden in the package (the modules,
their names, and their parameters) before you have actually implemented
the modules themselves. This feature dovetail nicely with top-down design,
in which you move from high-level requirements to functional
decompositions to module calls.

63
The big difference with the package specification is that you can compile it
even without its body.

10.2.4 Object Persistence


PL/SQL packages offer the ability to implement global data in your
application environment. Global data is information that persists across
application components; it isn't just local to the current module. If you
designed screens with SQL*Forms or Oracle Forms, you are probably
familiar with its GLOBAL variables, which allow you to pass information
between screens.

10.2.5 Performance Improvement


When an object in a package is referenced for the first time, the entire
package (already compiled and validated) is loaded into memory (the
Shared Global Area [SGA] of the RDBMS). All other package elements are
thereby made immediately available for future calls to the package. PL/SQL
does not have to keep retrieving program elements or data from disk each
time a new object is referenced.
This feature is especially important in a distributed execution environment.
You may reference packages from different databases across a local area
or even a wide area network. You want to minimize the network traffic
involved in executing your code.

10.3 A package has two parts


1. A package specification is the public interface of your applications.
The public here means the stored function, procedures, types … are
accessible by other applications.
2. A package body contains the code that implements the package
specification.

64
10.4 Creating PL/SQL Package Specification
The package specification is required when you create a new package. The
package specification lists all the objects, which are publicly accessible
from other applications. The package specification also provides the
information that developers need to know in order to use the interface. In
short, package specification is the package’s API.
It is important to note that you must compile the package specification
before package body.

Syntax

CREATE PACKAGE name AS -- specification (visible part)


-- public type and object declarations
-- subprogram specifications
END [name];

10.4.1 Package Interface


The specification holds public declarations, which are visible to your
application. The body holds implementation details and private
declarations, which are hidden from your application.
You can debug, enhance, or replace a package body without
changing the interface (package specification) to the package body.

10.5 Creating PL/SQL Package Body


The body of the package contains all the code behind the package
specification, the implementation of the modules, cursors, and other
objects. The body may also contain elements that do not appear in the
specification. These are called the private elements of the package. A
private element cannot be referenced outside of the package, since it does
not appear in the specification.

65
Syntax

CREATE PACKAGE BODY name AS -- body (hidden part)


-- private type and object declarations
-- subprogram bodies
[BEGIN
-- initialization statements]
END [name];

10.6 Scope
With packages you have three levels of scope
Declaring procedures, variables and constants in package specification,
are available to everyone, inside and outside the package.
Declaring procedures, variables and constants in package body, are
only available to program units in the package.
Declaring variables and constants in PL/SQL program unit are only
available within the program unit.

EXAMPLE
PACKAGE SPECIFICATION

CREATE OR REPLACE PACKAGE PACK1


IS
PROCEDURE P1(P_NO NUMBER,P_NAME OUT VARCHAR2,P_SAL
OUT NUMBER);
PROCEDURE P2(P_NO NUMBER,P_ROWS OUT NUMBER);
FUNCTION F1(P_NO NUMBER)
RETURN VARCHAR2;
END;
/

66
PACKAGE BODY

CREATE OR REPLACE PACKAGE BODY PACK1


IS
PROCEDURE P1(P_NO NUMBER,P_NAME OUT VARCHAR2,P_SAL
OUT NUMBER)
IS
BEGIN
SELECT ENAME,SAL INTO P_NAME,P_SAL FROM EMP
WHERE EMPNO=P_NO;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('INVALID EMPNO');
END P1;
PROCEDURE P2(P_NO NUMBER,P_ROWS OUT NUMBER)
IS
E EXCEPTION;
BEGIN
DELETE FROM EMP WHERE DEPTNO=P_NO;
P_ROWS:=SQL%ROWCOUNT;
IF SQL%NOTFOUND THEN
RAISE E ;
END IF;
COMMIT;
EXCEPTION
WHEN E THEN
DBMS_OUTPUT.PUT_LINE('INVALID DEPTNO');
END P2;
FUNCTION F1(P_NO NUMBER) RETURN VARCHAR2
IS
X VARCHAR2(20);
BEGIN
SELECT DNAME INTO X FROM DEPT
WHERE DEPTNO=P_NO;
RETURN X;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('INVALID DEPTNO');
RETURN NULL;
END F1;
BEGIN
DBMS_OUTPUT.PUT_LINE(SYSDATE||USER);
END;
/

67
10.7 Overloading concept in Oracle PL/SQL
Overloading concept means, it allows you to overload procedures or
functions in package with same name but different in data type and order of
the parameters. When you call an overload subprogram, compiler
determines which subprogram to call based on the data type which used in
subprograms. Single sub programs cannot be overloaded.

Example
--package specification

CREATE OR REPLACE PACKAGE testpack


IS
Procedure test1(p_num NUMBER, p_name VARCHAR2);
Procedure test1(p_num NUMBER, p_name VARCHAR2,p_num2
NUMBER);
END testpack;
/

--Package body

CREATE OR REPLACE PACKAGE BODY testpack


IS
PROCEDURE test1(p_num NUMBER, p_name VARCHAR2)
IS
BEGIN
DBMS_OUTPUT.put_line('Test1');
END;
PROCEDURE test1(p_num NUMBER, p_name VARCHAR2,p_num2
NUMBER)
IS
BEGIN
DBMS_OUTPUT.put_line('Test2');
END;
END testpack;
/

68
Calling a procedure from a Exec package_name.procedure_name
package (paramete_values)

Calling a function from a Select package_name.function_name from


packages dual

Remove a package Drop package package_name

Listing Package Select object_name, object_type,


last_ddl_time, timestamp,status from
user_objects where
object_name='Package_name'

List source code Select text from user_source where


name='Package_name'

Recompile a package alter package <package_name> compile


package;
alter package <package_name> compile
specification;
alter package <package_name> compile
body;

69
CHAPTER 11
11. Triggers
A trigger is a named program unit that is stored in the database and fired
(executed) in response to a specified event. It is a user defined restriction.
The specified event is associated with either a table, a view, a schema, or
the database, and it is one of the following:
1 A database manipulation (DML) statement (DELETE, INSERT, or
UPDATE)
2 A database definition (DDL) statement (CREATE, ALTER, or DROP)
3 A database operation (SERVERERROR, LOGON, LOGOFF,
STARTUP, or SHUTDOWN).

11.1 Uses of Triggers


Triggers supplement the standard capabilities of your database to provide a
highly customized database management system.
For example, you can use triggers to:
Automatically generate derived column values.
Enforce referential integrity across nodes in a distributed database.
Enforce complex business rules.
Provide transparent event logging.
Provide auditing.
Maintain synchronous table replicates
Gather statistics on table access.
Modify table data when DML statements are issued against views.
Publish information about database events, user events, and SQL
statements to subscribing applications.
Restrict DML operations against a table to those issued during
regular business hours.
Enforce security authorizations.
Prevent invalid transactions

70
11.2 Creating a Database Trigger
Syntax

CREATE [OR REPLACE] TRIGGER trigger-name


[BEFORE | AFTER]
{DELETE|INSERT|UPDATE [OF column [, column ]…}
[OR {DELETE|INSERT|UPDATE [OF column [, column]…}]...
ON table
[REFERENCING {OLD [AS] old | NEW [AS] new }]
[FOR EACH ROW]
[WHEN (condition)]
PL/SQL Block

PL/SQL Triggers Syntax Description


CREATE or REPLACE TRIGGER trigger_name: Creates a trigger with the
given name otherwise overwrites an existing trigger with the same name.
{BEFORE , AFTER }: Indicates the when should trigger get fired. BEFORE
trigger, executes before when statement execute before time or AFTER
trigger execute after when statement execute after time.
{INSERT , UPDATE , DELETE}: Determines the performing trigger event.
More than one triggering events can be used together separated by OR
keyword.
ON Table Name: Determine the perform trigger event in selected Table.
[Referencing {old AS old, new AS new}]: Reference the old and new
values of the data being changed. :old use to existing row perform and :new
use to execute new row to perform. The reference names can also be
changed from old (or new) to any other user-defined name. You cannot
reference old values when inserting a record, or new values when deleting
a record, because they do not exist.

71
for each row: Trigger must fire when each row gets Affected (Row Level
Trigger) or just once when the entire sql statement is executed(statement
level Trigger).
WHEN (condition): Valid only for row level triggers. The trigger is fired only
for rows that satisfy the condition specified.

11.3 Parts of Trigger


A trigger has three basic parts:
1. A triggering event or statement
2. A trigger restriction
3. A trigger action

11.3.1 The Triggering Event or Statement


A triggering event or statement is the SQL statement, database event, or
user event that causes a trigger to fire. A triggering event can be one or
more of the following:
An INSERT, UPDATE, or DELETE statement on a specific table (or view, in
some cases).
A CREATE, ALTER, or DROP statement on any schema object.
A database startup or instance shutdown.
A specific error message or any error message.
A user logon or logoff.

11.3.2 Trigger restriction


The trigger restriction specifies an additional condition that must be
satisfied for a row trigger to be fired. You can specify this condition with the
WHEN clause.

72
11.3.3 Trigger action
The trigger action specifies the PL/SQL block Oracle executes to fire the
trigger. Oracle evaluates the condition of the trigger restriction whenever a
triggering statement is issued. If this condition is satisfied, then Oracle fires
the trigger using the trigger action.

11.4 Types of Triggers


This section describes the different types of triggers:
1. Application Trigger or Form level Trigger
2. Database Trigger
a. DDL Event
b. DML Event

a. DDL Event
1. On Schema Level(User Event)
2. On DB Level(System Event)

b. DML Event
1. Row Triggers and Statement Triggers
2. BEFORE and AFTER Triggers
3. INSTEAD OF Triggers

11.5 Row Triggers and Statement Triggers


11.5.1 ROW Trigger: The triggers are fired for each and every record which
is inserted or updated or deleted from a table.

11.5.2 Statement Trigger: The Trigger are fired for each row of DML
operation being performed on a table. we can not access the column values
for records being inserted, updated, deleted on the table and not individual
records.

73
11.5.3 BEFORE and AFTER Triggers

Before Triggers: These triggers are fired before the triggering SQL
statement (INSERT, UPDATE, DELETE) is executed. The execution of
triggering SQL statement is stopped depending on the various conditions to
be fulfilled in BEFORE trigger.

Example
CREATE OR REPLACE TRIGGER TRIEMP
BEFORE INSERT OR UPDATE OR DELETE ON EMP
BEGIN
RAISE_APPLICATION_ERROR
(-20003,'DML OPERATION IS DENIED ON THIS TABLE');
END;

11.5.4 After Triggers: These triggers are fired after the triggering SQL
statement (INSERT, UPDATE, DELETE) is executed. The triggering SQL
statement is executed first followed by the code of trigger.

11.5.5 Combination Trigger:


Before Statement Trigger
Before Row Trigger
After Statement Trigger
After Row Trigger

74
Example
Before Row Trigger

CREATE OR REPLACE TRIGGER TRI_SAMPLE2


BEFORE INSERT OR UPDATE OR DELETE ON TB_SAMPLE
FOR EACH ROW
BEGIN
IF(INSERTING) THEN
INSERT INTO BKP_SAMPLE VALUES
(:NEW.SNO,:NEW.NAME,:OLD.NAME,CURRENT_TIMESTAMP,USER,
'INSERT');
ELSIF(UPDATING) THEN
INSERT INTO BKP_SAMPLE VALUES
(:OLD.SNO,:NEW.NAME,:OLD.NAME,CURRENT_TIMESTAMP,USER,
'UPDATE');
ELSIF(DELETING) THEN
INSERT INTO BKP_SAMPLE VALUES
(:OLD.SNO,:NEW.NAME,:OLD.NAME,CURRENT_TIMESTAMP,USER,
'DELETE');
END IF;
END;
/

11.6 Instead of triggers


Instead of triggers describe how to perform insert, update, and delete
operations against views that are too complex to support these operations
natively. Instead of triggers allow applications to use a view as the sole
interface for all SQL operations (insert, delete, update and select).

11.7 Triggers on System Events and User Events


You can use triggers to publish information about database events to
subscribers.
System events are for example database startup and shutdown, Data
Guard role transitions etc and User Events are User logon and logoff, DDL
statements(create,alter and drop) etc.,

75
11.8 Altering Triggers
If a trigger seems to be getting in the way, and you don’t want to drop it, just
disable it for a little while, you can alter it to disable it. Note that this is not the
same as dropping a trigger, after you drop a trigger, it is gone.
The general format of trigger
ALTER TRIGGER trigger_name [ENABLE|DISABLE];

If you want to disable all triggers in a table


ALTER TABLE TABLE_NAME DISABLE ALL TRIGGERS
11.9 Privileges Required to Use Triggers
To create a trigger in your schema:
You must have the CREATE TRIGGER system privilege
One of the following must be true:
You own the table specified in the triggering statement
You have the ALTER privilege for the table specified in the triggering
statement
You have the ALTER ANY TABLE system privilege
To create a trigger in another schema, or to reference a table in another
schema from a trigger in your schema:
You must have the CREATE ANY TRIGGER system privilege.
You must have the EXECUTE privilege on the referenced
subprograms or packages.

To create a trigger on the database, you must have the ADMINISTER


DATABASE TRIGGER privilege. If this privilege is later revoked, you can
drop the trigger but not alter it.
The object privileges to the schema objects referenced in the trigger body
must be granted to the trigger owner explicitly (not through a role). The
statements in the trigger body operate under the privilege domain of the
trigger owner, not the privilege domain of the user issuing the triggering
statement (this is similar to the privilege model for stored subprograms).

76
11.10 Compile a Trigger
Use the ALTER TRIGGER TRIGGER_NAME command to explicitly
recompile a trigger that is invalid.
When you issue an ALTER TRIGGER statement with the COMPILE option,
the trigger recompiles, regardless of whether it is valid or invalid.

11.11 Drop Trigger


To remove a trigger from the database, use the DROP
Syntax
DROP TRIGGER trigger_name ;

Note: All triggers on a table are dropped when the table is dropped. When a
trigger is no longer required, you can use a SQL statement in i SQL*Plus to
drop it.

11.12 Displaying trigger errors


If we get a message warning, Trigger created with complication errors. You
can check the error message with:

Show errors <trigger_name>;

You can also type, show err (show errors) to see the most recent
complication error.

77
11.13 Viewing Triggers
You can see all your user defined triggers by doing a select statement on
USER_TRIGGERS.
For example:
SELECT TRIGGER_NAME FROM USER_TRIGGERS;
This produces the names of all triggers. You can also select more columns
to get more detailed trigger information. You can do that at your own leisure,
and explore it on your own. For more details on a particular trigger:

Select * From user_triggers


Where trigger_name=’Name_of_trigger’;

11.14 Points to ponder


A trigger cannot include COMMIT, SAVEPOINT and ROLLBACK.
We can use only one trigger of a particular type.
A table can have any number of triggers.
We use correlation names :new and :old can be used to refer to data
in command line and data in table respectively.
Triggers on DDL statements
Maximum 12 triggers can create in a table.

78
LAB EXERCISES

1) Create dept table with the following fields.

Column name Data type


Deptno Number(2)
Dname Varchar2(14)
Loc Varchar2(13)

2) Create a table emp which will hold a reference to the above created table and
also have a structure as given below:

Column name Data type


Empno Number(4)
Job Varchar2(10)
Mgr Number(4)
Hiredate Date
Sal Number(7,2)
Comm Number(7,2)
Dept Number(2)

3) Write a PL/SQL block to populate the above tables.


4) Write PL/SQL block to increase the salary by 10% if the salary is > 2500 and
> 3000.
(5) Write PL/SQL block to decrease the salary by 13% if the salary is >3000 and
< 5000.
(6) Write PL/SQL block to increase the salary by 15% if the salary is > 5000.
While Loops.
(Hint: use basic loops, while loops, numeric for loops, cursor for loops.)
(7) Write PL/SQL block to insert student details into student table until the user
wishes to stop.
(8) Write PL/SQL block to insert department details into Department table until
the user wishes to stop.
(9) Write PL/SQL block to display the names of those employees getting salary >
3000.
(10) Write PL/SQL block to display the male employees details.
(11) Write PL/SQL block to display the total salary (I,e.Salary +Comm) of each
employee whose comm. Is not null.
Cursors

12) Write PL/SQL block to display the total salary (I,e .Salary + Comm.) of
each employee whose comm. Is not null until sum of total salary exceeds
25,000.
(11) Write PL/SQL block to display the employee details from the employee
table, and get the user’s choice and delete the record if the user wishes to
delete.
(12) Write PL/SQL block to insert only the odd numbers from 1 to 20 into
department table as department id and get the department name from the
user.

13) Write PL/SQL block to increase the salary by 15 % for all employees in emp
table.
14) Write PL/SQL block to display the employee details, and the number of
employees joined in each month.

Exceptions

(1) Write PL/SQL block to handle the exception no_data_found for the
question 13&14 given above.
(2) Write PL/SQL block to handle the exception dup_val_on_index by
inserting a duplicate row in the emp table.
(3) Write PL/SQL block to handle the exception value_error by inserting a
value of width greater than 20 into the department table.
(4) Write PL/SQL block with a user defined exception and raise the exception,
and handle the exception.
(5) Write PL/SQL block to handle exception, which are not handled by, using
others and display a message.

Stored Procedures
(1) Write a program to view the details of the employees who are working in
Department number 20.
(2) Write a program to accept the employee number of an employee and
Calculate the experience of the employee in months.
(3) Write a program to accept the annual income of the emp and find the
income tax
i) If the annsal > 60000 then tax is 10% of income.
ii) If the annsal > 100000 then tax is Rs 800+16% of income.
iii) If the annsal > 140000 then tax is Rs 2500+25% of income.
(4) Write a program to accept the empno and display all the details of emp. If
emp does not exist display the appreciate message.
(5) Write a program to accept a empno and display empno, name, sal, exp,
dname, grade and loc.
(6) Write a program to display department number with their total number of
employees for each department.
Stored Functions

Write a function to calculate the tax of the employees as per the given
details. If the salary is above 20000 then tax is 40%

Database Triggers.

(1) Write a database trigger before insert for each row on the course table
not allowing transactions on Sundays and Saturdays.
(2) Write a database trigger after update for each row giving the date and
the day on which the update is performed on the class table.
(3) Write a database trigger before delete for each row not allowing
deletion and giving message on the department table.
(4) Write a database trigger after delete for each row on instructor table,
which creates a new table named dump for the first delete, and inserts the
deleted row into that table.
(5) Write a database trigger before insert/delete/update for each row not
allowing any of these operations on the table student on Mondays.
Wednesdays, Sundays.
(6) Write a database trigger before insert/delete/update for each row not
allowing any of these operations on the table instructor between 6.p.m to
10 A.M.

You might also like