Professional Documents
Culture Documents
1 Introduction to databases 1
3 SQL Functions 19
5 Constraints 36
9 Manipulating Data 66
Example Table
The table EMP is used to store information about employees:
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
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
-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
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
-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
-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
-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
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.
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:
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;
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
Figure 2.1
- 11 -
Syntax:
SELECT column_list FROM table_name WHERE condition operator value.
SQL> SELECT ename, salary FROM emp WHERE salary <= 3000;
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
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;
- 13 -
B) Comparison operators
Comparison operators are used to compare one value or expression to
another
[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.
Find the employees details who are having an E anywhere in their name.
Find the employees details who are having an E as the second character in
their name.
- 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 (||).
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;
Examples:
SQL> SELECT ename, deptno, sal FROM emp
ORDER BY deptno, sal;
- 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.
- 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
- 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
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
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';
- 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.
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.
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)
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
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
- 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
- 31 -
CHAPTER 4
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');
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');
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.
- 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
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,
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;
- 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);
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);
Example 1: No Action
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 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);
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.
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;
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
Example tables
EMPLOYEES
Table 6.1
- 43 -
DEPARTMENTS
Table 6.2
Example:
SQL> SELECT employee_id, last_name, department_id, department_name
FROM employees, 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.
Output:
Table 6.3
- 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.
Example:
SQL> SELECT department_id, department_name, location_id, city
FROM departments NATURAL JOIN locations;
Example:
SQL> SELECT e.employee_id, e.last_name,d.location_id, department_id
FROM employees e JOIN departments d
USING (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.
- 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.
- 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.
- 50 -
Example
DEPARTMENTS
Table 6.9
EMPLOYEES
Table 6.10
Ps: There are no employees in department no 190.
- 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
- 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.
Table 7.1
Create the table DEPT.
SQL> CREATE TABLE dept
(deptno NUMBER(2),
dname VARCHAR2(14),
loc VARCHAR2(13),
create_date DATE);
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
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;
Syntax:
SQL> TRUNCATE TABLE table_name;
Example:
SQL> TRUNCATE TABLE employees;
Exercises
1. Create the following tables with suitable datatypes for columns
- 57 -
CHAPTER 8
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.
- 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.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.
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.
To view the details about the views which are created in your schema.
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.
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.
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.
If the table is dropped all the corresponding indexes for that table will be
automatically dropped.
- 62 -
8.4 SEQUENCES
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
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.
- 64 -
8.5 SYNONYMS
Syntax:
Example:
Drop a synonym:
SQL> DROP SYNONYM empys;
- 65 -
CHAPTER 9
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.
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');
• 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;
- 68 -
CHAPTER 10
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.
10.2 COMMIT
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);
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:
- 71 -
CHAPTER 11
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.
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.
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:
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.
Now the user Robert can grant the create table privilege to others.
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:
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
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.
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:
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:
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.
After creating the role grant the necessary privileges to the role.
All the privileges that were granted to the role will be automatically granted to the
user or role.
- 76 -
Note:
Role can be granted to users or other roles. But it cannot be granted to itself.
Table 11.1
After creating the user grant the necessary privileges to the user.
SQL> password
Type the old password then the new password and confirm it.
- 78 -
Lab 1: The ORACLE interfaces
Exercise 1:
Department_Id varchar2(20)
Department_Name varchar2(25)
Course_Name varchar2(5)
Department_Id varchar2(20)
Title char(60)
Description varchar2(200)
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.
iii) Alter the Student Grade Table to make the following changes:
i) Insert 10 records in the above tables as per the hints given below
ii) Save the changes
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
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
1 Introduction 1
4 Control Structures 17
5 Cursor 23
7 Exceptions 36
8 Stored Procedure 48
9 Stored Function 59
10 Package 63
11 Triggers 70
CHAPTER 1
1. INTRODUCTION TO PLSQL
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.
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
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
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
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.
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
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
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
1 PL/SQL 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.
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;
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.
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.
13
Example
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.
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
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
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;
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;
IF <condition-1> THEN
<Statements>;
ELSE
IF <condition-2> THEN
<Statements>;
ELSE
<Statements>;
END IF;
END IF;
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;
/
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.
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;
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
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.
23
Example
Consider the emp table, update employee 'Bhavesh' department to 'web
developer'.
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
Figure 6.1
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
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;
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;
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.
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;
/
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;
30
Syntax
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;
31
Syntax
1. Explicit locking lets you deny access for the duration of a transaction.
2. Lock the rows before the update or delete.
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;
14 rows updated
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;
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
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.
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
Syntax
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.
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.
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;
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.
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;
/
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;
2. Use the RAISE statement to raise the exception explicitly within the
executable section.
Syntax
RAISE exception_name;
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);
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.
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.
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.
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.
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.
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.
53
8.8 Types of Parameters
Parameters of a procedure are of two types.
1 Formal parameters
2 Actual Parameters
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
55
Example
CALLING PRIVATE PROCEDURE INSIDE A PROCEDURE
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
57
Now, user BOOK has granted INSERT privilege on DEPARTMENT
table to SCOTT as follows:
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:
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.
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.
--Method I
exec :xx:=f1(4000);
-- Method III
--Method IV
60
--Method V
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
62
CHAPTER 10
10. PACKAGE
63
The big difference with the package specification is that you can compile it
even without its body.
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
65
Syntax
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
66
PACKAGE BODY
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
--Package body
68
Calling a procedure from a Exec package_name.procedure_name
package (paramete_values)
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).
70
11.2 Creating a Database Trigger
Syntax
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.
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.
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.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.
74
Example
Before Row Trigger
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];
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.
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.
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:
78
LAB EXERCISES
2) Create a table emp which will hold a reference to the above created table and
also have a structure as given below:
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.