Documente Academic
Documente Profesional
Documente Cultură
BSNL
ORACLE RDBMS
WEEK-3
ES & IT FACULTY
COURSE CODE BRBCOIS113
BHARAT RATNA BHIMRAO AMBEDKAR
INSTITUTE OF TELECOM TRAINING,
RIDGE ROAD, JABALPUR 482 001
(ISO-9001: 2008 Certified)
BRBRAITT- June-2011
INDEX
S.No Title
Page No.
2. SQL Commands
17
64
4. Joins, Subqueries
78
90
6. Constraints
105
113
129
175
193
BRBRAITT- June-2011
Chapter 1
Overview of Oracle RDBMS
Introduction
Oracle is the relational database management system (RDBMS) sold by
Oracle Corporation. It is the most widely used database.
desgn, tel.no
Database : It is the collection of interrelated data, stored together
BRBRAITT- June-2011
User types
There are 3 types of users
Advantageous of DBMS
A DBMS provides the following Advantageous
Minimal Redundancy
Data Integrity
Minimal Redundancy
This is achieved by a process known as Normalization of Database
which is having 3 Forms
Third Normal Form : Removing the data which does not solely depend
on the key & putting is separately
BRBRAITT- June-2011
Data Integrity
The Integrity of data is ensured by various methods such as provision of
many Data types, defining of range of values, defining various Integrity
constraints like uniqueness, primary key, foreign key DBMS also protects the
data items and their association. It is having adequate protection against loss of
data due to h/w failure by BackUp & Recovery.
Characteristics of DBMS
Generally all DBMSs are having certain Characteristics in common as
follows.
Data abstraction
Data independence
Data Models
Data abstraction
It is the method of capturing data. There are 3 methods as follows.
BRBRAITT- June-2011
Data independence
It is the ability to change the scheme definition in one level w/o
affecting other levels. The different types of independence are
Data Models
Mapping of various data items that shows how they are related is
called Data Model. Data Models can be classified into
Record based logical Models : RBL models also describe the data
at conceptual and view levels. Some are
BRBRAITT- June-2011
BRBRAITT- June-2011
Hierarchical Model
Admn
Rama
SDE
15000
TVM
9000
Sita
JTO
10000
ENK
5900
SDE
TVM
15000
9000
Sita
JTO
ENK
10000
5900
I
BRBRAITT- June-2011
Relational Model
Null Rule : The RDBMS distinguishes between zero, blank and null
values
BRBRAITT- June-2011
High level insert, update and delete : The RDBMS supports insertion,
updation and deletion
BRBRAITT- June-2011
Oracle RDBMS
It is known as Oracle Server. It is a Kernel package. The Kernel is a
set of physical data files and a set of background processes which is known as
instance. When the Oracle Server is executed, it starts an instance. An
instance is a set of background processes and system global area(SGA)
which is responsible for storage, retrieval & modification of data and Control
of access of data.
The architecture of Oracle Server is explained with the help of
following diagram.
Oracle database is a combination of physical database files and
instance which is known as Oracle server. The physical database files are
stored in 1 or more Hard Disks.
The various physical files that make Oracle database are
BRBRAITT- June-2011
10
Instance
An instance is a combination of background processes & Memory
structures as shown in the diagram which will be explained under DBA.
Advantageous of Oracle
BRBRAITT- June-2011
11
Replicated Processing
High security
Client Server
A Client Server System is more structured than general distributed
computing. In `is system a client sends request to servers to execute tasks.
The tasks may be just to provide information, or to perform a complex
computation (perhaps returning information). Client and servers are
asymmetric & a server may be a client of another server. It is having the
following characteristics.
Client Server Properties
BRBRAITT- June-2011
12
Scalable
Less cost
Harder to build
Less stable
Lacking in specialists
Difficult to debug
Difficult to test
Client-server model
BRBRAITT- June-2011
13
Distributed Computing
A Distributed Computing System is a set of computers connected in
some way (serial lines, ethernet, ATM, etc). Each computer is able to
communicate with some of the others. Programs running on each computer
are able to share information and request tasks to be executed/
Oracle Server
The relational database management system (RDBMS) sold by Oracle
Corporation. Components of Oracle Server include the kernel and various
utilities for use by DBAs and database users
BRBRAITT- June-2011
14
Communication
For Communication with Oracle server Structured Query
Language(SQL) is used. SQL was developed by ANSI in 1962. SQL is a
English like language. Oracle is the first company to use SQL. With SQL what
to select, update, insert, delete data can be done. It is having the following
categories of statements.
/deleting data
DDL- Data Definition Language used for Defining structures such as
creation of table/index/sequence objects.
BRBRAITT- June-2011
15
A 4GL
Oracle Products
The oracle server comes with a set of utilities known as Oracle
products as below.
SQL * Plus
SQL Loader
SQL * Net
SQL * Plus
It is the command interpreter of Oracle Server. It Recognises SQL
commands, Carries them to Oracle server & Display the response from it. It is
having a set of commands for file manipulation, formatting
OEM
OEM is a comprehensive system management framework, built to
internet standards.
It provides administrators with a robust console, a rich set of tools,
using which DBAs Administer, diagnose, and tune multiple databases. It offers
graphical user interface.
Developer 6i
BRBRAITT- June-2011
16
Oracle Forms 6i
Oracle Reports 6i
Oracle Forms 6i
Oracle Reports 6i
SQL loader
SQL loader allows to load data stored in a variety of formats into an
oracle database such as from text files
SQL *NET
It is a protocol that supports client server computing. Using this any
client can access any server without regard to network protocols.
Oracle Precompilers
This enables to embed SQL statement in programming languages like
Ada, C, CobolIt combines the power of host languages and the flexibility &
ease of SQL.
BRBRAITT- June-2011
17
BRBRAITT- June-2011
18
Chapter-2
SQL COMMANDS
SQL, SEQUEL (Structured English Query Language), is the standard language
used to communicate with a relational database. SQL was developed by IBM
Corporation.
Types of SQL Commands
SQL commands are used to perform various functions. These functions include
building database objects, manipulating objects, populating database tables with
data, updating existing data in tables, deleting data, performing database
queries, controlling database access, and overall database administration.
The main categories are
DDL (Data Definition Language)
DML (Data Manipulation Language)
DQL (Data Query Language)
DCL (Data Control Language)
DTL (Data Transaction Language)
Defining Database Structures
DDL (Data Definition Language) statements are statements to create and
manage database objects in the database. There are three primary DDL
statements:
Manipulating Data
DML (Data Manipulation Language) commands are statements to change data
values in database tables. There are three basic DML commands:
BRBRAITT- June-2011
19
GRANT
BRBRAITT- June-2011
20
BRBRAITT- June-2011
21
FROM Table_name
[WHERE condition(s)]
[ORDERBY {column, expr}[ASC/DESC]]
Where:SELECT
DISTINCT
Suppresses duplicates.
alias
FROM table
WHERE
condition
ORDER BY
ASC
DESC
BRBRAITT- June-2011
22
Clauses are usually placed on separate lines for readability and ease of
editing.
Tabs and indents can be used to make code more readable.
An SQL command is entered at the SQL prompt, and subsequent line are
numbered. This is called the SQL buffer.
Only one statement can be current at any time within the buffer, and the statement
can be executed in a number of ways:
Guidelines
23
FROM
table_name;
The (*) in the SELECT clause tells the query to return all columns.
Example:SELECT
FROM
emp;
Example:SELECT
FROM
BRBRAITT- June-2011
24
FROM emp;
table
[WHERE Condition];
Where: condition
Comparison Operators
Comparison operators are divided in to two categories: logical and SQL. They are
used in the WHERE clause to compare one expression to another using the
following format.
Syntax:WHERE expr operator value
Comparison Operators
Comparison operators test the following conditions:
BRBRAITT- June-2011
25
Meaning
Equal to
>
Greater than
>=
<
Less than
<=
SQL Operators
There are four SQL operators that operate with all data type:
Operator
Meaning
BETWEEN
IN (list)
LIKE
Match a character
pattern
IS NULL
Is a null value
BRBRAITT- June-2011
26
Description
Represents any sequence of zero or more
characters.
Represents any single character.
BRBRAITT- June-2011
27
Meaning
AND
OR
NOT
You may find that it is easier to find the rows that do not met a condition, rather than
those that do. Use the comparison and SQL operators with a negative expression.
Negating Logical Operators
<>
Not equal to
BRBRAITT- June-2011
28
Operator
Description
NOT BETWEEN
AND
NOT IN(list)
NOT LIKE
IS NOT NULL
Rules of Precedence
You may combine AND and OR operators in the same logical expressions. The
results of all conditions are combined in the order determined by the precedence of
the connecting operators. Where operators of equal precedence are used next to
each other, they are performed from left to right.
Each AND is performed first then each OR is performed. AND has a higher
precedence than OR.
SELECT ename,sal,job
FROM emp
job= salesman;
Rules of Precedence
Order
Evaluated
Operator
All comparison operators
1
(=, <>, >, >=, <, <=, IN, LIKE, IS NULL,
BETWEEN)
2
AND
OR
BRBRAITT- June-2011
29
Multiply
/
()
Divide
Parentheses
to force
operator
precedence
BRBRAITT- June-2011
30
BRBRAITT- June-2011
31
Column Aliases
A column alias renames a heading.
When displaying the result of a query, SQL*Plus normally uses the selected
columns name as the heading. In many cases, that heading may be difficult to
understand or even meaningless. You can change a columns heading by using a
column alias.
Specify the alias after the column in the SELECT list using a space as a separator.
By default alias headings will be forced to uppercase and cannot contain blank
spaces, unless the alias is enclosed in double quotation marks ( ).
Example:SELECT ename, salary*12 AS annual_salary
FROM emp;
BRBRAITT- June-2011
32
If a row lacks a data value for a particular column, that value is said to be null,
or to contain null.
NULL is a value that is unavailable, unassigned, unknown or inapplicable.
BRBRAITT- June-2011
33
expr
FROM
table_name
where:-
ASC
DESC
Numeric values are displayed with the lowest values first, for example 1999.
Date value are displayed with the earliest value first, for example 01-jan92 before 01-jan-95
In Oracle7, null values are displayed last for ascending sequences and
first and for descending sequences.
34
SQL*Plus COMMANDS
In the previous lesson, you saw how SQL commands are executed within a product
called SQL*Plus. SQL*Plus is a SQL and PL/SQL command execution environment
with additional features.
You can use a number of SQL*Plus commands when writing even the most basic of
SQL statements. This section covers some basic SQL*Plus commands to help you
to
BRBRAITT- June-2011
35
Where: tablename
Guidelines
Description
Add a text to the end of the current line.
Changes old text to new in the current line.
Deletes text from the current line
Deletes all lines from the SQL buffer
Deletes current line
Inserts an indefinite number of lines
Inserts a line consisting of text.
Lists one lines in the SQL buffer
Lists one line (specified by n)
Lists a range of lines (m ton)
Displays and run the current SQL command in the
n
n text
0 text
buffer
Specifies the line to make the current line.
Replaces line n with text.
Inserts a line before line 1.
BRBRAITT- June-2011
36
Description
SAVE filename
GET filename
EDIT
ED[IT] filename
EXIT
Leaves SQL*Plus
Logging in to SQL*Plus
How you invoke SQL*Plus depends upon which type of operating system or
windows environment you are running.
Log in Through a Windows Environment
You double-click the SQL*Plus icon in the window manager, then enter the
username, password, and data base, if required.
BRBRAITT- June-2011
37
User name:
Password:
Host String:
Scott
*****
password
@ database
Summary
In this lesson, you have learned about retrieving information from a database table
with the SELECT statement and how to implement arithmetic and SQL operators.
You also learned the basic syntax for the SELECT statement.
Syntax:SELECT [DISTINCT] {*, column [alias]}
FROM table
[WHERE condition (s)]
[ORDER BY {column, expr} [ASC/DESC]]
Where:
BRBRAITT- June-2011
38
SELECT
DISTINCT
Suppresses duplicates.
alias
FROM table
WHERE
condition
ORDER BY
Specifies
ASC
DESC
SQL*PLUS
SQL*Plus
is
an
execution environment
you can use to send
SQL commands to the
database server and to
edit and to save SQL
commands. Commands
CREATE
ALTER
DROP
BRBRAITT- June-2011
39
After these questions are answered, the actual CREATE TABLE statement is simple
The CREATE TABLE Statement has the following general format:
Syntax:CREATE TABLE table-name
(column-descr|constraint, column-descr|constraint...);
Where
The column declaration can include optional column constraints. The declaration has
the following general format:
Syntax:column-name data-type [column-constraints]
column-name is the name of the column and must be unique among the
columns of the table.
Data-type declares the type of the column.
column-constraints is an optional list of column constraints with no
separators
BRBRAITT- June-2011
40
Guidelines
Each column has been assigned a specific data type and length.
Naming Conventions
When selecting names for objects, specifically tables and columns, the name should
reflect the data that is to be stored. For example, the name for a table pertaining to
employee information could be named EMPLOYEE_TBL. Names for columns
should follow the same logic. When storing an employee's phone number, an
obvious name for that column would be PHONE_NUMBER
BRBRAITT- June-2011
41
BRBRAITT- June-2011
42
BRBRAITT- June-2011
43
VARCHAR2(Size)
CHAR(Size)
NUMBER(p,s)
DATE
LONG
RAW(Size)
LONG RAW
BLOB
BRBRAITT- June-2011
44
BRBRAITT- June-2011
45
DROPPING TABLES
Dropping a table is actually one of the easiest things to do. When the RESTRICT
option is used and the table is referenced by a view or constraint, the DROP
statement returns an error. When the CASCADE option is used, the drop succeeds
and all referencing views and constraints are dropped. The syntax to drop a table
follows
Syntax:DROP TABLE TABLE_NAME [ RESTRICT|CASCADE ]
Eg:DROP TABLE emp_temp;
Summary
You have specifically learned about the table. The table is the simplest form of data
storage in a relational database. Tables contain groups of logical information, such
as employee, department, or salary information. A table is composed of various
columns, with each column having attributes; those attributes mainly consist of data
types and constraints, such as NOT NULL values, primary keys, foreign keys, and
unique values.
You learned the CREATE TABLE command and options, that may be available with
this command. You have also learned how to modify the structure of existing tables
using the ALTER TABLE command.
BRBRAITT- June-2011
46
Syntax:-
BRBRAITT- June-2011
47
You must include every column in the specified table in the VALUES list.
The values inserted into the table must be enclosed by quotation marks
for character and date/time data types. Quotation marks are not required
for numeric data types or NULL values using the NULL keyword.
48
BRBRAITT- June-2011
49
But instead of inserting the value NULL into the Comm column, we have inserted ''.
NULL value has been inserted by using two single quotation marks together, which
also symbolizes a NULL value (because there is nothing between them).
BRBRAITT- June-2011
50
BRBRAITT- June-2011
51
Note:The column list in the INSERT statement does not have to reflect the same order
of columns as in the definition of the associated table, but the list of values must
be in the order of the associated columns in the column list.
Inserting Data from Another Table
You can insert data into a table based on the results of a query from another table
using a combination of the INSERT statement and the SELECT statement. In the
case of combining the INSERT statement with the SELECT statement, you are able
to insert the data retrieved from a query into a table.
The syntax for inserting data from another table is
Syntax:INSERT INTO table_name [('column1', 'column2')]
SELECT ('column1', 'column2')]
FROM table_name
[WHERE condition(s)];
The following example uses a simple query to view all data in the EMP table.
SELECT * tells the database server that you want information on all columns of the
table. Because there is no WHERE clause, you will see all records in the table as
well.
Example:INSERT INTO Emp_TMP
SELECT * from EMP;
BRBRAITT- June-2011
52
BRBRAITT- June-2011
53
BRBRAITT- June-2011
54
[WHERE condition];
Note
The SET keyword is used only once for each UPDATE statement. If more than
one column is to be updated, a comma is used to separate the columns to be
updated.
If a sub query is used in a UPDATE statement, it must return exactly one row for
each row in the update table that matches the WHERE clause. If it returns multiple
rows, Oracle server will give you an error message.
BRBRAITT- June-2011
55
BRBRAITT- June-2011
56
Use the DELETE statement with no WHERE clause. (the table structure,
attributes, and indexes will also be deleted)
DELETE FROM EMP1_temp;
Use the TRUNCATE TABLE statement. (deletes only the data inside the
table)
TRUNCATE TABLE EMP_temp;
Note
i) If the WHERE clause is omitted from the DELETE statement, all rows of
data are deleted from the table. As a general rule, always use a WHERE
clause with the DELETE statement.
ii) Also, remember that the DELETE command may have a permanent
impact on the database. Ideally, it should be possible to recover
erroneously deleted data via a backup, but in some cases, it may be
difficult or even impossible to recover data. If data cannot be recovered, it
must be re-entered into the database.
Summary
You have learned the three basic commands in Data Manipulation Language (DML):
the INSERT, UPDATE, and DELETE statements. As you have seen, data
manipulation is a very powerful part of SQL, allowing the database user to populate
tables with new data, update existing data, and delete data.
A very important lesson when updating or deleting data from tables in a database is
sometimes learned when neglecting the use of the WHERE clause. Remember that
the WHERE clause places conditions on a SQL statementparticularly in the case
of UDPATE and DELETE operations, when specifying specific rows of data that will
be affected during a transaction. All target table data rows are affected if the WHERE
clause is not used, which could be disastrous to the database. Protect your data and
be cautious during data manipulation operations.
BRBRAITT- June-2011
57
Syntax:
GRANT privilege-list
ON [table_name] object-list
TO user-list
[With GRANT option]
BRBRAITT- June-2011
58
The GRANT statement grants each privilege in privilegelist for each object (table) in object-list to each user in user-list.
In general, the access privileges apply to all columns in
the table or view, but it is possible to specify a column list with the
UPDATE privilege specifier:
Statement.
The Owner has all privileges on the object and can grant
specific privileges on that object.
BRBRAITT- June-2011
59
The GRANT statement grants the user named user02 the privileges to select, insert,
update, and delete for the emp table.
.
The REVOKE Statement
Exercise
It has been decided that once records are entered into the emp table, they should
not be changed or deleted by the new database user. Revoke the UPDATE and
DELETE privileges from user02.
Example query
REVOKE update, delete ON emp FROM
user02;
60
BRBRAITT- June-2011
61
BRBRAITT- June-2011
62
COMMIT
ROLLBACK
SAVEPOINT
BRBRAITT- June-2011
63
BRBRAITT- June-2011
64
BRBRAITT- June-2011
65
In this example, you plan to delete the remaining records from the EMP_TEMP
table. You want to create a SAVEPOINT before each delete, so that you can
ROLLBACK to any SAVEPOINT at any time to return the appropriate data to its
original state:
SAVEPOINT SP1;
DELETE FROM EMP_TEMP WHERE Empno= 7521;
SAVEPOINT SP2;
DELETE FROM EMP_TEMP WHERE Empno= 7788;
SAVEPOINT SP3;
DELETE FROM EMP_TEMP WHERE Empno= 7698;
Now that the three deletions have taken place, say you have changed your mind
and decided to ROLLBACK to the SAVEPOINT that you identified as SP2.
Because SP2 was created after the first deletion, the last two deletions are
undone:
ROLLBACK TO SP2;
Notice that only the first deletion took place since you rolled back to SP2:
SELECT * FROM EMP_TMP;
Remember, the ROLLBACK command by itself will roll back to the last COMMIT
or ROLLBACK. You have not yet issued a COMMIT, so all deletions are undone,
as in the following example:
ROLLBACK ;
SELECT * FROM EMP_TMP;
66
Summary
Here You learned the preliminary concepts of transaction management through
the use of three transaction control commands: COMMIT, ROLLBACK, and
SAVEPOINT. COMMIT is used to save a transaction to the database.
ROLLBACK is used to undo a transaction that was performed. SAVEPOINT is
used to break a transaction or transactions into groups, allowing you to roll back
to specific logical points in transaction processing.
Remember that you should frequently use the COMMIT and ROLLBACK
commands when running large transaction jobs to keep space free in the
database. Also keep in mind that these transaction commands are used only with
the three DML commands (INSERT, UPDATE, and DELETE).
BRBRAITT- June-2011
67
Chapter 3
Oracle built in functions and Group functions
Overview
Data can be manipulated in queries through functions supported by SQL.
A function is a special type of predefined command set that performs some
operation and returns a single value.
SQL has a lot of built-in functions for counting and calculations.
Syntax
SELECT function (column) FROM table
Types of Functions
There are several basic types and categories of functions in SQL. The basic
types of functions are:
Scalar functions
Aggregate Functions(Group functions)
Scalar functions
Scalar functions operate against a single value, and return a single value based
on the input value.
They can be used in the SELECT clause of queries to
BRBRAITT- June-2011
68
LOWER()
Convert to lowercase
UPPER()
Convert to uppercase
INITCAP ()
CONCAT()
Concatenate values
SUBSTR()
Return substring
LENGTH
CONCAT function
Combines two string values into one
"||" is used for this operation.
Syntax:-
Example:-
Result:-
job
JONES is a CLERK
BRBRAITT- June-2011
69
INITCAP Function
Convert to initial capitalization
Syntax:-
INITCAP (expression)
Example:-
Returns a specified number of characters from the left and right of a character
expression respectively
Syntax:-
RIGHT(character_expression ,
integer_expression )
LEFT (character_expression ,
integer_expression)
Example:Here is, for example, the way to determine the names of the
employees that start and end with the same letter:
SELECT ename FROM emp WHERE
LEFT(ename, 1) = RIGHT(ename, 1)
LOWER(character_expression)
BRBRAITT- June-2011
70
Cut accordingly the leading and trailing blanks of the string expression, which is
being converted by default to the VARCHAR type.
Syntax:-
LTRIM (character_expression )
RTRIM (character_expression )
Example:-
BRBRAITT- June-2011
71
SUBSTRING function
Extract from an expression its part of a specified length, starting from a specified
initial position.
Syntax:-
Example:-
LENGTH function
Return number of characters in the string
Syntax:-
LENGTH(expression)
Example:-
Result:-
NVL function
In order to convert a null value to an actual value, use the NVL function.
Syntax:-
BRBRAITT- June-2011
72
expr 2
Is the target value for converting null.
Example:-
NVL(job,SDE)
Will substitute the value SDE for any NULL Value found in the job column
Notes: you can use the NVL function to convert any data type, but the return
value is always the same as the data type of expr 1.
Number Functions
ROUND
TRUNC
MOD
45.92
ROUND(45.923,0)
46
ROUND(45.923,-1)
50
TRUNC(45.923,2)
45.92
TRUNC(45.923)
45
BRBRAITT- June-2011
73
40
Date Functions
FROM
DUAL;
MONTHS_BETWEEN
ADD_MONTHS
NEXT_DAY
LAST_DAY
ROUND
TRUNC
ADD_MONTHS
This function adds number of months to a given date and returns a date after
those many months.
Syntax:ADD_months(date1,n)
It returns the value of argument date date1 plus n months
Example:-
BRBRAITT- June-2011
74
hiredate
Next month
17-dec-80
17-jan-81
MONTHS_BETWEEN
This function finds out the number of months passed between given two dates
Syntax:Months_between(date1,date2)
Date2>date1
Example:SELECT Months_between(22-Jan-03,02-Dec_2002) MONTHS
FROM DUAL;
Output:-
months
1.6451613
NEXT_DAY
Returns the date of a specified coming day the first weekday named by argument
CHAR that is later than the date d in the Next week
Syntax:NEXT_DAY(d,CHAR)
Example:-To get the date of next Tuesday after NOV 16,2006
SELECT NEXT_DAY(16-NOV-06,Tuesday) Next day
FROM DUAL
BRBRAITT- June-2011
75
Next day
21-Nov-06
LAST_DAY
Returns the Last day of the specified month
Syntax:LAST_DAY(Date)
Example:SELECT LAST_DAY(16-NOV-06) Last day
FROM DUAL
Output:-
Last day
30-Nov-06
BRBRAITT- June-2011
76
BRBRAITT-JUN-2011
77
AVG(DISTINCT/ ALL) N
Numeric
Numeric
Returns Average value of parameters n
Calculate average salary of all employees listed in table
emp
SELECT AVG(sal)
FROM emp;
2077.21429
SUM()
This function gives the sum of all the rows, satisfying any conditions, of the given
column or expression.
SYNTAX
Argument type
Return Value
Description
Example
SQL>
Output
BRBRAITT-JUN-2011
SUM([DISTINCT | ALL] n)
Numeric
Numeric
Returns sum of values of n .
Display total salary of all employees in table emp
SELECT SUM(sal) Total FROM emp
Total
29081
78
BRBRAITT-JUN-2011
79
BRBRAITT-JUN-2011
80
HAVING
HAVING... was added to SQL because the WHERE keyword could not be used
against aggregate functions (like SUM), and without HAVING... it would be
impossible to test for result conditions.
While WHERE clause gives predicate for filtering rows, the HAVING clause is
applied after grouping that gives a similar predicate but filtering groups by the
values of aggregate functions. This clause is nessesary for checking the values
that are obtained by means of an aggregate function not from separate rows of
record source in the FROM clause but from the groups of these rows. Therefore,
this checking is not applicable to the WHERE clause.
Syntax :SELECT column_a, SUM(column_b) FROM table
GROUP BY column_a
HAVING SUM(column_b) condition value
Example 1:-:
SELECT job ,SUM(sal) FROM EMP
GROUP BY job
HAVING SUM(sal)>10000
Example 2:-:
SELECT deptno,job ,SUM(sal) FROM EMP
GROUP BY deptno,job
HAVING job IN (CLERK,SALESMAN);
BRBRAITT-JUN-2011
81
Chapter 4
JOINS , Subqueries
Joins and Keys
Sometimes we have to select data from two or more tables to make our result
complete. We have to perform a join.
Good database design suggests that each table lists data only about a single
entity, and detailed information can be obtained in a relational database, by using
additional tables, and by using a join.
Tables in a database can be related to each other with keys. A primary key is a
column with a unique value for each row. Each primary key value must be unique
within the table. The purpose is to bind data together, across tables, without
repeating all of the data in every table.
A foreign key is a column in a table where that column is a primary key of another
table, which means that any data in a foreign key column must have
corresponding data in the other table where that column is the primary key. In
DBMS-speak, this correspondence is known as referential integrity.
In the "Employees" table below, the "Employee_ID" column is the primary key,
meaning that no two rows can have the same Employee_ID. The Employee_ID
distinguishes two persons even if they have the same name.
When you look at the example tables below, notice that:
Employees:
Employee_ID
Name
01
Anil
02
Sindhu
BRBRAITT-JUN-2011
82
03
Jaya
04
Vinod
Orders:
Prod_ID
Product
Employee_ID
234
Printer
01
657
Table
03
865
Chair
03
Name
Product
Anil
Printer
Jaya
Table
Jaya
Chair
BRBRAITT-JUN-2011
83
Name
Anil
INNER JOIN
OR we can select data from two tables with the JOIN keyword, like this:
Syntax:SELECT field1, field2, field3
FROM first_table
INNER JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield
Example:-Who has ordered a product, and what did they order?
SELECT Employees.Name, Orders.Product
FROM Employees
INNER JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID
BRBRAITT-JUN-2011
84
BRBRAITT-JUN-2011
85
Example
Who ordered a printer?
SELECT Employees.Name
FROM Employees
INNER JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID
WHERE Orders.product=Printer
BRBRAITT-JUN-2011
86
E_ID
E_Name
01
Anil
02
Sindhu
03
Jaya
04
Vinod
Employees_USA:
E_ID
E_Name
01
Sally
02
Kent
03
Jaya
04
Stephen
87
Note: This command cannot be used to list all employees in Norway and USA. In
the example above we have two employees with equal names, and only one of
them is listed. The UNION command only selects distinct values.
UNION ALL
The UNION ALL command is equal to the UNION command, except that UNION
ALL selects all values.
SQL Statement 1
UNION ALL
SQL Statement 2
Using the UNION ALL Command
BRBRAITT-JUN-2011
88
Subqueries
Objectives
During this lesson, you are presented with the concept of using subqueries to
return results from a database query more effectively.
What Is a Subquery?
A subquery is a query embedded within the WHERE clause of another query to
further restrict data returned by the query. A subquery is a query within another
query, also known as a nested query. A subquery is used to return data that will
be used in the main query as a condition to further restrict the data to be
BRBRAITT-JUN-2011
89
The subquery can be used either in the WHERE clause or the HAVING
clause of the main query.
Logical and relational operators, such as =, >, <, <>, IN, NOT IN, AND,
OR, and so on, can be used within the subquery as well to evaluate a
subquery in the WHERE or HAVING clause.
The same rules that apply to standard queries also apply to Subqueries.
Join operations, functions, conversions, and other options can be used
within a subquery.
Guidelines:
A subquery can have only one column in the SELECT clause, unless
multiple columns are in the main query for the subquery to compare its
selected columns.
Subqueries that return more than one row can only be used with multiple
value operators, such as the IN operator.
BRBRAITT-JUN-2011
90
The next query selects the deptno for a particular employee. This query is used
as the subquery in the following example.
Example:-SELECT deptno FROM emp
WHERE ename=JAMES;
The previous query is used as a subquery in the WHERE clause of the following
query. The following SQL statement returns the name and job of employees who
works in the same department as JAMES.
SELECT empno,ename,sal
FROM emp,
WHERE deptno = (SELECT deptno FROM emp
WHERE ename=JAMES);
The result of the subquery is used as the last condition of the WHERE clause
Subqueries are frequently used to place conditions on a query when the exact
conditions are unknown. When a single row subquery is used we should use a
single row comparison operator such as =, >, <, or <>,
BRBRAITT-JUN-2011
91
BRBRAITT-JUN-2011
92
Example:The following query show the details of those employees that have a salary
equal to any employee of deptno 30
SELECT * FROM emp
WHERE sal=ANY
(SELECT sal FROM emp
WHERE deptno= 30);
Or
SELECT * FROM emp
WHERE sal=SOME
(SELECT sal FROM emp
WHERE deptno= 30);
ALL Operator is similar to that with ANY, except that all values returned by the
subquery must meet the predicate "<expression> <comparison operator> V ".
Syntax:<expression> <comparsion operator> ALL (<subquery>)
BRBRAITT-JUN-2011
93
Here are the formal rules for evaluating the predicate with ANY|SOME and ALL
parameters:
If ALL or SOME parameter are given and all the comparison results of
expression value with each value returned by the subquery are equal
to TRUE, truth value is TRUE.
If the result set of the subquery does not have any rows with the ALL
parameter specified, the result is TRUE. However, if the SOME
parameter is specified, the result is equal to FALSE.
Nested Subqueries
Nesting is the act of embedding a subquery within another subquery. For
example:
Select * FROM Table_name
BRBRAITT-JUN-2011
94
BRBRAITT-JUN-2011
95
Chapter 5
Oracle Schema Objects (Views, Sequences, Indexes,
Synonyms)
Introduction
A schema is a collection of logical structures of data, or schema objects. A
schema is owned by a database user and has the same name as that user. Each
user owns a single schema. Schema objects can be created and manipulated
with SQL and include:
Tables
Views
Synonyms
Sequences
Stored Procedures
Tablespaces etc
Tables
You give each column a column name, such as ename, deptno and job a
datatype, such as VARCHAR2, DATE, or NUMBER; and a width.
BRBRAITT-JUN-2011
96
Views
Objectives
In this lesson, you will see how views can be used to present data to user in a
variety of ways. In addition, you will see how integrity constraints can be
enforced, if using a view to insert, update, or delete data.
At the end of this lesson, you should be able to
Modify a view.
Remove a view.
Overview
Present logical subset or combination of data by creating views of tables.
What is a View?
A view is a logical table based on a table or another view. A view contains no
data of its own, but is rather like a window through which data from tables can
be viewed or changed. The view is stored as a SELECT statement in the data
dictionary.
Advantages of Views
Restrict access to the database because the view can display a selective
portion of the database.
Allow user to make simple queries to retrieve the result from complicated
queries. For example, views allow user to query information from multiple
tables without knowing how to write a join statement.
BRBRAITT-JUN-2011
97
Guidelines
BRBRAITT-JUN-2011
98
The query that defines a view can contain complex SELECT syntax,
including joins, group, and sub queries.
The query that defines the view cannot contain an ORDER BY clause.
You can use the OR REPLACE option to change the definition of the
view without dropping and re-creating it, or regranting object privileges
previously granted on it.
You can Control the column names by including column aliases within
the subquery.
You can Create a complex view that contains group function to display
values from two tables.
Types of Views
There are two classifications for views: simple and complex. The basic difference
is related to the DML operations.
Simple View Compared to Complex Views
Performing DML Operation on a View
Characteristic
Simple Views
Complex Views
Number of tables
Only one
One or more
Contain functions
No
Yes
Yes
A join condition
Group functions
A GROUP BY clause
BRBRAITT-JUN-2011
99
You can add data through a view unless it contains any of the above and there
are NOTNULL columns in the base table are not selected by the view. All
required values must be present in the view. Remember that you are adding
values directly into the underlying table through the view.
100
BRBRAITT-JUN-2011
101
Simplify queries
View Options
Can be complex view based on more than one table, or contain groups or
functions
Can be read-only.
BRBRAITT-JUN-2011
102
Indexes
Overview
Indexes are created in an existing table to locate rows more quickly and
efficiently. It is possible to create an index on one or more columns of a table,
and each index is given a name. The users cannot see the indexes, they are just
used to speed up queries.
Note: Updating a table containing indexes takes more time than updating a table
without, this is because the indexes also need an update. So, it is a good idea to
create indexes only on columns that are often used for a search.
What is an index?
An index is a data base object that provides direct and fast access to row in a
table.
Indexes are logically and physically independent of the table they index. This
means that they can be create or dropped at any time and have no effect on the
base tables or other indexes.
How are Indexes created?
Two type of indexes can be created. One type is a unique index. The Oracle
Server automatically creates this index when you define a column in a table to
have a PRIMARY KEY or a UNIQUE constraint. The name of the index is the
same given to the constraint.
The other type of index a user can be create is a non-unique index. For example,
you can create a FOREIGN KEY column index for a join in a query to improve
retrieval speed.
Index Types
Type
Description
Unique
Non-unique
Single column
Concatenated or
composite
BRBRAITT-JUN-2011
103
BRBRAITT-JUN-2011
104
The table is a large and most quires are expected to retrieve more than
10-15% of the rows.
Most queries are expected to retrieve less than 10-15% of the rows.
Removing an INDEX
You cannot modify indexes.To change an index ,you must drop it and then
recreate it.
Drop Index
You can delete an existing index in a table with the DROP INDEX statement.
Syntax
BRBRAITT-JUN-2011
105
BRBRAITT-JUN-2011
106
SEQUENCES
Objectives
Many applications require the use of unique numbers as primary key values. You
can either build code into the application to handle this requirement or use a
sequence to generate numbers. This lesson covers creating and using sequence
that creates unique numbers.
At the end of this lesson, you should be able to
Create a sequence.
Use a sequence.
Remove a sequence.
Overview
A sequence generator can be used to automatically generate sequence numbers
for row in table. A sequence is a database object created by a user and can be
shared by multiple users.
A typical usage for sequence is to create a primary key value, which must be
unique for each row. The sequence is generated and incremented (or
decremented) by an internal Oracle routine. This can be a time saving object
because it can reduce the amount of application code needed to write a
sequence generating routine.
Sequence numbers are stored and generated independently of tables. Therefore,
the same sequence can be used for multiple tables.
Creating Sequence
Syntax:CREATING SEQUENCE sequence _ name [INCREMENT BY n]
[START WITH n] [{MAXALUE n /NOMAXVALUE}]
[{MINVALUE n /NOMINVALUE}]
[{CYCLE /NOCYCLE}] [{CACHE n / NOCACHE}];
BRBRAITT-JUN-2011
107
INCREMENT BY n
START WITH n
MAXVALUE n
NOMAXVALUE
MINVALUE n
NOMINVALUE
CYCLE/NONCYCLE
CACHE n/ NOCACHE
Using a Sequence
Once you create your sequence, you can use the sequence to generate
sequential numbers for use in your table. Reference the sequence values by
using the NEXTVAL and CURRVAL pseudo columns.
BRBRAITT-JUN-2011
108
BRBRAITT-JUN-2011
109
You must own or you have the ALTER privilege for the sequence in order
to modify it.
Only future sequence numbers are affected by the ALTER SEQUENCE
command.
BRBRAITT-JUN-2011
110
Removing a Sequence
To remove a sequence from the data dictionary, use the DROP SEQUENCE
command. You must be the owner of the sequence or have the DROP ANY
SEQUENCE privilege to remove it.
Syntax
DROP SEQUENCE sequence_name
Summary
The sequence generator can be used to automatically generate sequence
numbers for row in tables. This can be time saving, and reduce the amount of
application code needed.
A sequence is a database object that can be shared with other users. Information
about the sequence can be found in the USER_SEQUENCE table of the data
dictionary.
To use a sequence, reference it with either the NEXTVAL or the CURRVAL
pseudo columns.
Retrieve the next number in the sequence by referring sequence. NEXTVAL.
Return the current available number by referencing sequence. CURRVAL.
Synonyms
Synonyms are usually created so that a user can avoid having to qualify another
user's table or view to access the table or view.
What Is a Synonym?
A synonym is merely another name for a table or a view. Synonyms can be
created as PUBLIC or PRIVATE. A PUBLIC synonym can be used by any user of
the database; a PRIVATE synonym can be used only by the owner and any users
that have been granted privileges
Synonyms are of two types:Private Synonyms are the Synonyms created by a user for personal use.
BRBRAITT-JUN-2011
111
BRBRAITT-JUN-2011
112
Chapter 6
CONSTRAINTS
A constraint refers to a condition or a check that is applied to a column (field) or
set of columns in a table. The constraints applied to maintain data integrity are
also known as integrity constraints.
You can use constraints to
Prevent the deletion of a table if there are dependencies from other tables.
2. Table constraint
BRBRAITT-JUN-2011
113
BRBRAITT-JUN-2011
(ecode
number(4)
NOT NULL,
ename
char(20)
NOT NULL,
gender
char(1)
NOT NULL,
grade
char(2),
gross
number(7) ) ;
114
BRBRAITT-JUN-2011
115
FOREIGN KEY is used to define the column in the child table at the tableconstraint level.
REFERENCES identifies the table and column in the parent table.
ON DELETE CASCADE indicates that when the row in the parent table is
deleted, the dependent rows in the child table will also be deleted.
Without th ON DELETE CASCADE option, the row in the parent table cannot be
deleted if it is referenced in the child table.
Master table
CREATE TABLE dept_data
(deptno
number(2)
PRIMARY KEY,
dname
varchar2(10));
Child table
CREATE TABLE emp_data
(empno
varchar2(5)
PRIMARY KEY,
location
varchar2(3),
deptno
number(2)
REFERENCES dept_data(deptno));
5. DEFAULT Constraint
A default value can be specified for a column using the DEFAULT clause.
When a user does not enter a value for the column (having default value),
automatically the defined default value is inserted in the field.
Consider the following SQL statement.
BRBRAITT-JUN-2011
116
integer
char(20)
char(1)
char(2)
number(7)
BRBRAITT-JUN-2011
117
Syntax
AND / OR
SELECT column_name(s)
FROM table_name
WHERE condition
AND|OR condition
SELECT column_name
FROM table_name AS table_alias
BETWEEN
SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2
CREATE DATABASE
CREATE INDEX
CREATE TABLE
CREATE VIEW
BRBRAITT-JUN-2011
118
or
DELETE FROM table_name
WHERE condition
DROP DATABASE
DROP INDEX
DROP TABLE
GROUP BY
SELECT column_name1,SUM(column_name2)
FROM table_name
GROUP BY column_name1
HAVING
SELECT column_name1,SUM(column_name2)
FROM table_name
GROUP BY column_name1
HAVING SUM(column_name2) condition value
IN
SELECT column_name(s)
FROM table_name
WHERE column_name
IN (value1,value2,..)
INSERT INTO
LIKE
SELECT column_name(s)
FROM table_name
WHERE column_name
LIKE pattern
ORDER BY
SELECT column_name(s)
FROM table_name
ORDER BY column_name [ASC|DESC]
BRBRAITT-JUN-2011
119
SELECT
SELECT column_name(s)
FROM table_name
SELECT *
SELECT *
FROM table_name
SELECT DISTINCT
SELECT INTO
(used to create backup copies of
tables)
or
SELECT column_name(s)
INTO new_table_name
FROM original_table_name
UPDATE
UPDATE table_name
SET column_name=new_value
[, column_name=new_value]
WHERE column_name=some_value
WHERE
SELECT column_name(s)
FROM table_name
WHERE condition
SQL Summary
This module has taught you the standard computer language for accessing and
manipulating database systems.
You have learned how to execute queries, retrieve data, insert new records,
delete records and update records in a database with SQL.
BRBRAITT-JUN-2011
120
CHAPTER 7
PL/SQL ENGINE, BLOCKS, DATATYPES
PL/SQL first appeared in Oracle Version 6 in 1988. It was primarily
used within Oracles user interface product SQL Forms to allows for the inclusion
of complex logic within the forms. It replaced an old step method for logical
control and provided a reasonably simple programming language that resembled
ADA and C. Looking back at those days, we remember converting old Pro * C
programs into PL/SQL so that we could more easily maintain them. Actually, the
C programmer took another job, and we had lots of people who wanted to use
their new programming language knowledge. So we converted all the code in a
relatively short time frame, and here we are far ahead with some of that original
PL/SQL code still in use. We have come a long way since then. Today we use
PL/SQL to read data, to populate the database, create stored objects, and even
to display web pages. PL/SQL has certainly grown into a mature product. Oracle
has shown a strong dedication to the language, as illustrated by its use of
PL/SQL in many of its products, such as Oracle Applications. Oracle is also
using the web portion of PL/SQL quite extensively.
Have you visited
www.oracle.com lately ? If so, you have seen PL/SQL for the web in action. So
lets move on and look more closely at the PL/SQL programming language.
It is Just as important to learn PL/SQL as it is to learn SQL. So,
whether you are looking at becoming a DBA or an Oracle developer , knowledge
of PL/SQL is a skill that you must have in your database toolkit. In this session
we will discuss the following:
BRBRAITT-JUN-2011
121
Terminology
The following Terminology will arm you with the technical jargon to get through
this chapter.
BRBRAITT-JUN-2011
122
BRBRAITT-JUN-2011
123
ORACLE DATABASE
INTEGRATED SQL
INTEGRATED
ENGINE SQL
ENGINE
PL/SQL
Stored
Program
External
Program
calls
PL/SQL
PL/SQL
Engine
Engine
SQL
ENGINE
SQL
ENGINE
DATABASE
In Figure, you see at the center the oracle 9i Server, the primary engine for
the data base. It serves as the coordinator for all calls to the database.
When a call is made from a program to the server to run a PL/SQL program,
the database (Oracle) loads the compiled program into memory, and then the
PL/SQL engine and SQL engine execute the program. The PL/SQL engine
will handle the programs memory structures and logical program flow. The
SQL engine then issues data requests to the database. It is a closed system
and one that allows for very efficient programming.
PL/SQL is used in numerous Oracle products, including :
BRBRAITT-JUN-2011
124
Oracle forms
Oracle Reports
Oracle Warehouse Builder
Oracle Applications
Oracle Portal
SQL *Plus
Oracle Enterprise Manager
Oracle precompilers (such as Pro *C, Pro *COBOL, etc.)
Oracle Call Interface (OCI)
Server Manager
Oracle 9i Application Server
Java Virtual Machine (JVM)
Supported Characters
When programming in PL/SQL, you may only use characters as defined here:
BRBRAITT-JUN-2011
125
Meaning
**
*, /
Exponent
Multiplication,
division
+, - , ||
Addition, subtraction,
concatenation.
Meaning
Equal
Not equal
Greater than
Less than
Greater than or equal
Less than or equal
PL/SQL STRUCTURE
The structure used in all of PL/SQL is the foundation for all of the
language. When you master it, you will be able to move forward, but if you do
not take the time to get this first step right, your journey will be difficult. Actually,
it is easy, Lets look at the structure that all of your Pl/SQL programs will have.
BRBRAITT-JUN-2011
126
You will have areas for program parameters (used to pass values from
outside a program to the program), internal variables, the main program code
and logic, and then some ways to handle things when they go wrong.
Description
Declarative
Executable
Exception
Handling
Note:
Inclusion
BRBRAITT-JUN-2011
127
DECLARE -Optional
-Variables,constants,
cursors,user-defined exceptions
BEGIN -Mandatory
-SQL Statements
-PL/SQL control statements
EXCEPTION -Optional
-Actions to perform when errors occur.
END; - Mandatory
Every unit of PL/SQL comprises one or more blocks. These blocks can be
entirely separate or nested one within another. Therefore, one block can
represent a small part of another block, which in turn can be part of the whole
unit of code.
BRBRAITT-JUN-2011
128
Description
Anonymous Block
Stored Procedure
Function
Availability
of
for
Package
Database Trigger
Application Trigger
of
for
BRBRAITT-JUN-2011
129
Anonymous Blocks
Anonymous blocks are un-named blocks. They are declared at the
point in an application where they are to be executed and are passed to the
PL/SQL engine for execution at runtime. You can embed an anonymous block
within a precompiler program and within SQL* Plus or server Manager. Triggers
in Developer/2000 components consist of such blocks.
Subprograms
Subprograms are named Pl/SQL blocks. You can declare them either as
procedures or as functions. Procedure perform actions and functions return
values.
Developer/2000 components allow you to declare procedures and
functions as part of the application (a form or report), and call them from other
procedures, functions, and triggers.
BLOCK TYPES
Anonymous
[DECLARE]
BEGIN
--statements;
Procedure
PROCEDURE name
Function
IS
FUNCTION name
IS
BEGIN
BEGIN
--statements
--statements
RETURN value;
[EXCEPTION]
[EXCEPTION]
[EXCEPTION]
END;
END;
END;
BRBRAITT-JUN-2011
130
NOT NULL
EXPR
Guidelines
Name the identifier according to the same rules used for SQL objects
You can use naming conventions, for example v_name to represent a
variable, and c_name to represent a constant.
You have the option of assigning an initial Value to variables, unless they
are NOT NULL.
BRBRAITT-JUN-2011
131
Number
Character
date and time
Boolean
Character and number data types have subtypes that associate a base
type to a constraint. For example, INTEGER and POSITIVE are subtypes of the
NUMBER base type.
Datatype
BINARY-INTEGER
NUMBER(Precision-scale)
CHAR (Maximumlength)
LONG
VARCHAR2(maximum-length)
DATE
BOOLEAN
BRBRAITT-JUN-2011
Description
Base type for integers between
2147483647 and 2147483647.
Base type for fixed and floating point
numbers.
Base type for fixed length character data
up to 32767 bytes. If you do not specify
a maximum length, the default length is
set to 1.
Base type for variable length character
data upto 32760 bytes.
Base type for variable length character
data up to 32767 bytes.
Base type for dates and times.
Base type that stores one of three
possible values used for logical
calculations: TRUE,FALSE, or NULL.
132
CHAR(1);
BINARY_INTEGER := 0;
NUMBER(9,2) := 0;
DATE := SYSDATE + 7;
CONSTANT NUMBER(3,2) := 8.25;
BOOLEAN NOT NULL := TRUE;
Examples
1. Declare a variable to store the gender code (M or F)
V_gender
CHAR (1);
2. Declare a variable to count the iterations of a loop and intialize the variable to
0
V_count
- BINARY-INTEGER :=0;
3. Declare a variable to accumulate the total salary for a department and initialize
the variable to 0
V_total_sal
4. Declare a variable to store the ship date of an order, and initialize the variable
to one week from today.
V_order_date DATE := SYSDATE + 7;
5. Declare a constant for the tax rate, which never changes throughout the
PL/SQL block.
C_tax_rate CONSTANT NUMBER (3,2) := 8.25;
6. Declare a flag to indicate whether a piece of data is valid or invalid, and
initialize the variable to TRUE.
V_valid
BRBRAITT-JUN-2011
133
s_emp.lastname%TYPE;
s_emp.first_name%TYPE;
134
DECLARE
V_balance
NUMBER (7,2);
V_minimum_balance v_balance%TYPE := 10;
You declare records in the DECLARE section of a block, along with the
other types of variables you have seen.
Example
BRBRAITT-JUN-2011
135
DECLARE
Dept_record
Emp_record
s_dept%ROWTYPE;
s_emp%ROWTYPE;
This declaration creates a record with the same field names and field
datatypes as a row in a table. DEPT_RECORD is a record. The fields
are:
DEPT_RECORD.ID,
DEPT_RECORD.NAME
and
DEPT_RECORD.REGION_ID
Example
Store the annual salary in a SQL *Plus global variable.
:g_annual_salary := v_salary *12;
BRBRAITT-JUN-2011
136
CHAPTER 8
CONTROL STRUCTURES, EXCEPTIONS, TRIGGERS
AND CURSOR
CONTROL STRUCTURES
At the heart of any programming language are its control structures.
Since Programs are written to handle a number of different situations, the
manner in which different conditions are detected and dealt with is the biggest
part of program control. Various types of control structures are used for this
purpose, including
If logic structures
Case expressions
Looping structures
Program control is governed by the status of variables and the data that is
read from and written to the database. As an example, picture yourself going into
the drivers license office to renew your drivers license. When you enter the
officer, you are presented with a number of directional signs. One sign reads
Driver Testing ; for this, you go to the second floor. Another sign tells you that
License Renewals is one the third floor. You are here for a renewal, so you
head up to the third floor. Once you arrive in the renewal office, you are once
again faced with some new choices. Now you have to decide whether you are
going to pay by cash or credit card. Cash payments are being accepted to the
right, and credit cards are to the left. You see that you have enough cash, and
you head to the payment wicket on the right. Let us look at Table below and see
how our program control influenced your choices.
step
1
2
3
4
5
6
7
8
9
10
11
12
13
next steps
BRBRAITT-JUN-2011
137
IF Logic Structures
When you are writing computer programs, situations present themselves
in which you must test a condition. When you ask a question in your program,
you are usually presented with one of two answers; it may be true or it may be
false. Computer programs are black and white; in computer logic, there can only
be true or false answers to your questions, no maybe. PL/SQL provides you with
three distinctive if logic structures that allows you to test for true and false
conditions. In everyday life we are presented with decisions that we need to
make; the following sections will show you how to do it using PL/SQL.
IF - THEN
You use the if-then construct to test the simplest type of condition. If the
condition evaluates to true, then one or more lines of program code will be
executed. If the condition evaluates as false, then no action is taken. The
following code snippet illustrates how this is performed with a PL/SQL program.
IF I_date > 11-APR-03 then
I_salary := I_salary * 1.15;
- - Increase salary by 15%
END IF:
NOTE:
To add comments to your code, start a comment line with /* and end with
*/ or you may use the double hyphen ( - -) as we have done in the above
example.
In this case, if the value of the variable I_date is greater than 11th of
April 2003, then the salary will be increased by 15 percent . This
statement may also be restated using the following statement.
IF not (I_date <= 11 APR-03) then
I_salary := I_salary *1.15;
-- Increase salary by 15%
END IF;
Also, you nest IF _ THEN statement to increase the power
of your statements. Let us add a condition to limit who gets the raise:
BRBRAITT-JUN-2011
138
IF - THEN ELSE
The if-then-else construct is similar to the simple if-then construct. The
difference is that when the condition executes as false , the program statements
that follow the else statement are executed. The following code illulstrated this
logic within PL/SQL.
IF I_date > 11-APR-03 then
I_salary := I_salary *1.15 ;
-- Increase salary by 15%
ELSE
I_salary := I_salary *1.05 ;
--Increase salary by 5%
END IF;
In the preceding code listing, you see the condition that if the date is
greater than the 11th of april, 2003, you will get a 15 percent salary increase.
However, when the date is less than or equal to this date, you will only receive a
5 percent increase.
As with the simple if-then construct, you may nest the if-then-else
construct. Let us look at how this might appear in our PL/SQL program:
IF I_date > 11-Apr-03 then
BRBRAITT-JUN-2011
139
IF THEN - ELSIF
The final if construct that we will show you is if-then-elsif. In this case,
you provide yourself with the option to test another condition when the first
condition is evaluated as false. When you want to test for more than one
condition without using nested if statements, this is the type of statement that you
might use.
IF I_last__name = PAKMAN then
I_salary := I_salary *1.15;
-- Increase salary by 15%
ELSIF I_last_name = ASTROFF then
I_salary := I_salary *1.10;
-- Increase salary by 10%
ELSE
I_salary := I_salary *1.05;
-- Increase salary by 5%
END IF;
In the preceding statement, if your last name is Pakman, you
get a 15 percent raise; if it is Astroff, you get 10 percent; and the rest of us
get only a 5 per cent raise. There is no limit to the number of elsif
conditions that you may use within this construct. The following shows
you an example of using multiple elsif statement within the construct.
IF I_city = OTTAWA then
L_team_name := SENATORS;
ELSIF I_city = LOS ANGELS then
BRBRAITT-JUN-2011
140
CASE EXPRESSIONS
The next logical step from the if statement is the case statement. The
case statement, which was introduced with Oracle 9i, is an evolution in logical
control. It differs from the if-then-else constructs in that you now can use a simple
structure to logically select from a list of values. More important, it may be used
to set the value of a variable. Let us look at how this may be done. First, let us
look at the format:
CASE variable
WHEN expressional then value 1
WHEN expression 2 then value 2
WHEN expression 3 then value 3
WHEN expression 4 then value 4
ELSE value 5
END;
SQL>run
1 DECLARE
2 val varchar2(100) ;
3 city varchar2 (20) := TORONTO;
4 BEGIN
5 val := CASE city
6 WHEN TORONTO then RAPTORS
7 WHEN LOS ANGELS then LAKERS
8 WHEN BOSTON then CELTICS
BRBRAITT-JUN-2011
141
Although you can use the if-then-else to achieve the same purpose, the
case statement is easier to read and more efficient. Remember that once Oracle
9i reaches a value in the case statement that meets the condition, the
processing of the case statement will stop.
LOOPS
Loops are control structures that allow you to repeat a set of
commands until you decide that it is time to stop the looping.
Generally, the format that all loops take is the flowing:
LOOP
Executable statements;
END LOOP;
Each time the loop is executed, the statements within the loop are
executed, and then the program return to the top of the loop structure to do it all
over again. However, if you ever want this processing to stop, you will need to
learn about the EXIT statement.
The exist statement allows you to stop executing within a loop without a
condition. It will then pass control back to the program and will continue on after
the loop statements.
BRBRAITT-JUN-2011
142
Although you may use the exist command to do the same thing. It
is better form to use the while expression.
BRBRAITT-JUN-2011
143
So, what is important for you to note in the preceding statement? First,
you need to know that the variable I_counter will hold the value between 1 and
10. How do we know it will be between 1 and 10 ? Well, after the IN, we place
the counters range. In this case, the counter starts at I, the low bound, and
continues to 10. You should also note the two dots. (..) between the two integer
values (1 and 10). This tells Oracle 9i that you would like it to count between
these two numbers.
One more note:
DECLARE
I_counter number;
BEGIN
FOR I_counter IN REVERSE 1..5
LOOP
Dbms_output.put_line (I_counter);
END LOOP;
End;
/
5
4
3
2
1
PL/SQL procedure successfully completed.
Now you can see how easy it is to use simple loops, but loops have much
more power. Using loops like the while loop or the for loop allows you to use
variables instead of hard coded values. This gives you the greatest possible
flexibility because you can have the database or external data provide you with
the limits within your loop. Let us look at how this might work. In the following
example, we select the number of employees in our employee table, and then
show how the counter counts from 1 to the number of employees in our small
company.
BRBRAITT-JUN-2011
144
BEGIN
5
select the number of employees in the
I_emp_count variable
--
END LOOP;
11 *END;
Employee 1
Employee 2
Employee 3
Employee 4
Employee 5
Employee 6
BRBRAITT-JUN-2011
145
We have looked at a lot of structure up until now. You should know that a
PL/SQL program will always have a BEGIN and END. It may have variables ,
loops, or logic control, but your next question must be wheres the best ? What
gives PL/SQL its beef is SQL. Since you have all these CONTROL structures,
you need to use them in conjunction with information.You may want the
information so that you can create a report, update data, create new data,and
delete old data, or perform just about any other function that you can think of. It
is very important for you to see how you can integrate data into PL/SQL code.
Without data, PL/SQL is just PL.
EXCEPTIONS
INTRODUCTION
When you execute PL/SQL program, you may encounter errors, that stop
the program. Any well-written program must have the ability to handle such
errors intelligently and recover from them , if possible. PL/SQL implements error
handling via exceptions and Exception Handlers which can be associated with
oracle errors or with user defined errors. In this chapter, we wll discuss the
types of exceptions, how exceptions are raised and handled, association of
exceptions with ORACLE error and the rule of the exception propogation. It also
provides the guidelines on using exceptions.
We already know how PL/SQL is based on the ADA language. One of the
features of ADA that is incorporated into PL/SQL is the exception mechanism,
that makes your programs robust and able to deal with both unexpected and
expected errors during execution.
What kinds of error can occur in a PL/SQL Program ?
BRBRAITT-JUN-2011
146
Note that a check for errors must occur after each statement in the
program. If you forget to insert the check, the program will not properly
handle an error situation. In addition, the error handling can clutter up
the program, making it difficult to understand the programs logic.
BRBRAITT-JUN-2011
147
Note that the error handling code is separated from the programs
logic. This solves problems occurring in the previous case.
TRAPPING EXCEPTIONS:
Generally exceptions are declared in the declarative section of the block,
raised in the executable section and handled in the exception section.
PL/SQL provides a set of system defined exceptions and allows you to
add user defined exceptions.
There are 3 types of exceptions. They are as follows.
1.
BRBRAITT-JUN-2011
148
CURSOR_ALREADY_OPEN:
Raised if an open statement tries to
open a cursor that is already open. You must close a cursor before you
can reopen it. SQL CODE is set to -6511 (error is ORA-06511)
INVALID_CURSOR: Raised if you attempted to open an undeclared
cursor, or close, one that was not opened or fetch from one that was not
open, and so on. SQLCODE is set to -1001 (error is ORA-01001).
INVALID_NUMBER: Raised on a conversion error from a character string
to a number, when the character string does not contain a legitimate
number in a SQL statement. SQL CODE is set to 1722. (error is ORA01722)
LOGIN_DENIED:
Raised if user tries to logon to ORACLE with
an invalid username/ password. SQLCODE is set to -1017 (error is 0RA01017.)
DUP_VAL_ON_INDEX:
Raised if an insert or update would
have caused a duplicate value in unique database column. SQLCODE is
set to 1 (error is ORA-00001).
NO_DATA_FOUND :
Raised if a select statement returns nothing.
SQLCODE is set to- +100 (error is ORA-01403)
TOO_MANY_ROWS:
Raised when select statement that is supposed
to return just one row , returns more than one (this is also raised by a
subquery that is only supposed to return one row). SQL CODE is set to
1422 (error is ORA-01422)
NOT_LOGGED_ON:
Raised if you attempt any sort of database call
without being logged on to ORACLE. SQLCODE is set to-1012 (error is
ORA-01012.)
PROGRAM_ERROR:
Raised if PL/SQL itself has an internal problem
executing the code such as exiting a function that has no return statement.
SQLCODE is set to - 6501 (ERROR IS ORA -06501)
STORAGE _ERROR;
Raised if PL/SQL needs more memory than is
available that is run out of memory or memory is corruputed. SQLCODE
is set to 6500 (error is ORA-06500)
TIMEOUT_ON_RESOURCE:
Raised when a time out occurs while
ORACLE is waiting for a resource. This usually means an instance has
had an abnormal termination. SQLCODE is set to -51 (error is ORA00051)
TRANSACTION_BACKED_OUT: Raised when the remote part of a
transaction is rolled back due to deadlock or data might be inconsistent at
some node. SQLCODE is set to - 61 (error is ORA-00061)
VALUE_ERROR:
Raised when the value of a column of PL/SQL is
damaged by arithematic, conversion, truncation or constraint error occurs
in a procedural statement. If the error occurs in a SQL statement,
INVALID_NUMBER is raised instead. SQLCODE is set to 6502 (error is
ORA-01456)
ZERO_DIVIDE:
Raised when a statement tries to divide a number by
zero. SQLCODE is set to - 1476 (error is ORA-01476)
BRBRAITT-JUN-2011
149
non
SYNTAX:
Exception_name EXCEPTION;
2.
RAISING EXCEPTION:
When the error associated with an exception
occurs, the exception must be raised. User defined exceptions are raised
explicitly within the executable section using RAISE statement. Predefined
exceptions are raised automatically when their associated ORACLE error occurs.
For e.g. if the error ORA-01403 occurs when no rows are retrieved from the
database, the PL/SQL raises the exception NO_DATA_FOUND.
SYNTAX:
RAISE exception_name;
Where exception_name is the name of the previously defined
exception.
3.
HANDLING EXCEPTIONS:
Reference the declared exception within
the corresponding exception handling routine using WHEN CLAUSE.
WHEN exception_name THEN
Statements;
Where exception_name is the name of the exception declared in the
declarative section and raised in the exevutable section.
150
IF &&p_staffno IS NULL OR
(TO_NUMBER (&p_staffno)
NOT BETWEEN 1000 ND 9999
THEN
RAISE e_invalid_staffno;
ELSE
INSERT INTO emp_data (staffno,emp_name, deptno)
VALUES (&p_staffno, &p_name, &p_deptno);
INSERT INTO emp_sal (staffno)
VALUES (&p_staffno);
END IF;
EXCEPTION
WHEN e_invalid _staffno THEN
INSERT INTO MESSAGE
VALUES (INVALID STAFF NUMBER, Staff number: || &p_staffno ||
must be between 1001 and 9999 );
END;
/
EXPLANATION: In the above example e_invalid_staffno is defined as an
exception in the declarative section by the user. In the executable section the
verification of staff number i.e. whether it is within the range 1001 -9999 is
verified by the IF. ..END IF clause. If it is not, the exception e_invalid_staffno is
raised and control is transferred to the corresponding exception handling section
and a message is inserted into the table message.
NUMBER (2);
CHAR (4);
varchar2(25);
varchar2(5);
CHAR(3);
BRBRAITT-JUN-2011
151
BEGIN
SELECT
TO_NUMBER(staff no) -1000 as
Emp_name,desgn, hq
INTO v_sl,v_staffno, v_desgn, v_hq
FROM emp_data
WHERE staffno = ABCD;
INSERTINTO message
VALUES (to_char (v_sl) || - || v_staffno,
v_name || || desgn || - ||v_hq);
SL_NO,
staffno,
EXCEPTION
WHEN INVALID_NUMBER THEN
INSERT INTO Message
VALUES (invalid number, There is a wrong character value in the staff
number);
END;
/
Now execute the program and see the resultas follows:
SQL>SELECT *FROM MESSAGE;
OUTPUT:
INVALID NUMBER There is a wrong character value in the staff number.
Explnation:
BRBRAITT-JUN-2011
152
emp_sal.basic%TYPE;
emp_data.emp_name%TYPE;
emp_data.desgn%TYPE;
BEGIN
SELECT emp_name,desgn INTO
V_name,v_desgn
FROM emp_data
WHERE staffno = &&_staffno;
Select basic INTO v_basic
FROM emp-sal
WHERE staffno = &p_staffno;
INSERT INTO PAYBILL(Staffno,emp_name,desgn,basic)
VALUES (&p_staffno,v_name,v_desgn,v_basic);
EXCEPTION
When NO_DATA_FOUND THEN
INSERT INTO MESSAGE
VALUES (NO_DATA_FOUND,
There is no record of information for this staff no: || &p_staffno);
WHEN TOO MANY_ROWS THEN
INSERT INTO MESSAGE
VALUES (TOO_MANY_ROWS,
There are more than 1 records for this staff number : || &p_staffno);
END;
//
BRBRAITT-JUN-2011
153
EXPLATION:
When there is no record under the given staffno in
EMP_DATA table, no row is returned by the SQL statement and so
NO_DATA_FOUND exception is raised and action is taken accordingly . When
there are more than 1 record for the given staffno in EMP_SAL table, more than
one row is retrieved by the 2ndSQL statement and so TOO_MANY_ROWS
exception is raised and action is taken accordingly.
varchar2(3);
BEGIN
Tempvar := ABCD;
EXCEPTION
WHEN VALUE _ERROR THEN
INSERT INTO message
VALUES (VALUE_ERROR,
There is an error in the assignment of value to the variable);
END;
/
Example 2:
DECLARE
Tempvar
varchar2(3);
BEGIN
SELECT staffno
INTO tempvar
FROM emp_data
WHERE staffno = 1001 ;
EXCEPTION
BRBRAITT-JUN-2011
154
BRBRAITT-JUN-2011
155
OUTPUT
The ratio between maximum and minimum basic pay is x.xx (some value).
Next modify one of the basic as 0 as follows:
SQL> UPDATE emp_sal
SET basic = 0
WHERE staffno = 1001;
Again run the program and observe the result.
OUTPUT:
ZERO_DIVIDE ERROR: There is zero value in the basic pay, so when an
attempt made to divide a number by zero, the ZERO_DIVIDE exception is raised
automatically and since there was a handler in the exception section, the control
branched there and recorded the error by inserting one row in the message table.
BRBRAITT-JUN-2011
156
emp_name,
deptno)
VALUES
EXCEPTION
WHEN empty_name THEN
INSERT INTO message
Values (Blank Name,
Employees name cannot be blank);
BRBRAITT-JUN-2011
157
(error_number,
error_message,
It takes three I/P parameters: the error number (which must be between
-20001 and 20999) and the error message which is the text to be displayed and
keep_errors : a Boolean value which is optional. If keep_errors is true, the new
error is added to the list of already raised (if one exists). If it is false , which is the
default, the new error will replace the current list of errors. You get to assign both
the message number and the text that will be displayed to the user
EXAMPLE:
PROCEDURE paycalc(p_staffno IN emp_data.staffno%TYPE)
IS
Zero_pay EXCEPTION;
BEGIN
EXCEPTION
WHEN TOO_ MANY_ ROWS THEN
RAISE_APPLICATION_ERROR (-20001,
There are more than I records for this staff number : || p_staffno);
WHEN zero_pay THEN
BRBRAITT-JUN-2011
158
EXCEPTION PROPOGATION:
Exception can occur in the declarative,executable or the exception
section of a PL/SQL block. We have seen what happens when exceptions are
raised in the executable portion of the block, when there is a handler for the
exception. But what, if there is no handler, or the exception is raised from
different section of the block? The process that governs this is known as
exception propogation.
1.
If the current block has a handler for the exception, execute it and
complete the block successfully. Control then passes to the enclosing
block.
If there is no handler for the current exception, propogate the
exception by raising it in the enclosing block. Step I will then be
executed for the enclosing block.
BRBRAITT-JUN-2011
159
BEGIN
--Begin inner block. This is embedded in the outer block.
BEGIN
END;
.
BEGIN
--Begin inner block 2. This is also embedded in the
-- outer block.
--Note that this block does not
-- have a declarative part
END;
.
..
--End out block
END;
In the preceding listing, inner blocks 1 and 2 are both enclosed by the
outer block. Any unhandled exceptions in block 1 and block 2 will be propogated
to the outer block.
A procedure call will also create an enclosing block, and is
illustrated in the following example:
BEGIN
--Begin outer block.
--call a procedure. The procedure will be enclosed by the
--outer block.
F()
END;
If procedure function raises an unhandled exception, it will be
propogated to the outer block, since it encloses the procedure.
TRIGGERS
BRBRAITT-JUN-2011
160
INTRODUCTION
Like procedures, functions and packages. Triggers are named PL/SQL
blocks with declarative, executable and exception handling sections. Like
packages, Triggers must be stored in the database and cannot be local to a block
. However a procedure is executed explicitly from another block which can pass
arguments. But a trigger is executed implicitly, whenever the triggering event
happens and a trigger does not accept arguments. The act of executing a
trigger is known as firing the trigger. The triggering event is a DML (INSERT,
UPDATE, DELETE) operation on a database table.
APPLICATION OF TRIGGERS
Triggers can be used for many things, including
CREATING TRIGGERS
SYNTAX
The general syntax for creating a trigger is:
CREATE [OR REPLACE] TRIGGER trigger _name
[BEFORE | AFTER ] triggering event ON table_reference [For EACH
ROW ]
[ WHEN trigger_condition ]
trigger_body;
where
trigger_name -the name of the trigger
triggering-event The event or time when the trigger fires.
Table_reference
BRBRAITT-JUN-2011
161
BRBRAITT-JUN-2011
162
(v_statsRecord.exg_code,v_stats
END IF;
END LOOP;
END update_ES;
TRIGGER COMPONENTS
1.Trigger name
2.Triggering event
3.The body
4.When clause -optional.
BRBRAITT-JUN-2011
163
Trigger Name
Namespace: A namespace is the set of legal identifiers available for use
as the names of an object. Within one database shema ,all objects in the same
namespace must have unique name. Procedures, Packages and Tables all share
the same namespace. Hence it is illegal to give the same name to a procedure
and a table.
The namespace for triggers is different from that of the above objects (i.e.,
procedure, package and table). This means that a trigger can have same name
as a table or a procedure.
Trigger names are database identifiers and as such follows the same rules
as other identifiers.
Although it is possible to use the same name for a trigger and a table. It is
better to give each trigger a unique name that identifies its function as well as the
table at which it is defined.
Triggering event
The triggering event determines the type of the triggers.
Triggers can be defined for INSERT, UPDATE or DELETE operation.
Triggers can be fired BEFORE or AFTER the operation.
They can also be fired ROW or STATEMENT level
TABLE I
Category
Values
INSERT
Statement
DELETE
Comments
Defines which kind of DML statement
causes the trigger to fire.
UPDATE
BEFORE
Timing
AFTER
ROW
Level
STATEMENT
Fires only once either before or after the
BRBRAITT-JUN-2011
164
statement.
TABLE 2
Timing
Statement
Level
BEFORE
INSERT
UPDATE
DELETE
ROW
AFTER
STATEMENT
The values for the timing, statement and level determine the type of the trigger.
From the table 2 it can be observed that there are total of possible 12 types.
2 timings x 3 statement x 2 levels = 12 types
For example all the following are valid trigger types.
A table can have upto 12 triggers defined on it-one of each type. A table
can have more than one trigger of each type.
This means that a table can have any number of triggers.
The order in which the triggers are fired is explained later in this chapter.
A trigger can also be fired for more than one type of triggering statement.
For example, the update_ES Trigger is fired on INSERT, UPDATE and DELETE
statements.
BRBRAITT-JUN-2011
165
:new and :old (explained latter) cannot refer to a LONG or LONG RAW
column in the table for which the trigger is defined.
BRBRAITT-JUN-2011
166
END
BRBRAITT-JUN-2011
167
BRBRAITT-JUN-2011
168
Triggering
Statement
INSERT
UPDATE
DELETE
:Old
:new
Undefined-All fields
Are NULL
The Table-3 shows the value of :new and :old with reference to each
statement. In reality, :new and :old are not records. As a result, operations that
would normally be valid on records are not valid for :new and :old . For example,
i.
They cannot be assigned as entire record. Only the individual fields within
them may be assigned.
ii.
:old and :new cannot be passed to procedures or functions that take
arguments of triggering_table%ROW TYPE.
The Generate_EmpId trigger shown next uses :new. It is a BEFORE
INSERT OR UPDATE Trigger and its purpose is to fill in the ID field of staff with a
value generated from the emd_id__seq sequence.
Example:
The trigger Generate_EmpId actually modifies the value of :new.emp_id.
When the statement is actually executed, whatever values in :new will be used.
With Generate_EmpId, we can issue an INSERTstatement such as:
INSERT INTO STAFF (emp_name, desgn)
VALUES JOSE, AO);
Without generating an error. Even though we have not specified a value
for the primary key column emp_id (which is required), the trigger will supply it.
Infact, even if we do specify a value for emp_id, it will be ignored, since the
trigger changes it.
If we issue
INSERT INTO staff (emp_id,emp_name,desgn)
BRBRAITT-JUN-2011
169
In general, :new is modified only in a before row level trigger and :Old is
never modified, only read from.
The :new and :old records are only valid inside a ROW LEVEL triggers.
You will get a compile error, if you try to reference inside a STATEMENT
LEVEL trigger.
170
Behavior
TRUE, if the triggering statement is an
INSERT;FALSE otherwise.
TRUE if the triggering statement is an
UPDATE;FALSE otherwise.
TRUE if the triggering statement is a
DELETE;FALSE otherwise.
171
BRBRAITT-JUN-2011
172
Cursor
What is a Cursor ?
A cursor is a private SQL area
Every SQL statement executed by the oracle server has
an individual cursor associated with it.
Two Types of cursor:
-Implicit cursors: Declared for all DML and
PL/SQL SELECT statements.
-Explicit cursors: Declared and named by the
programmer.
The Oracle Serve uses work areas called Private SQL areas to execute
SQL statements and store processing information. PL/SQL cursors let you name
a private SQL area and access its stored information. The cursor directs all
phases of processing.
Cursor Description
Type
Implicit Declared by PL/SQL implicitly for all DML
and PL/SQL SELECT statements.
Explicit Declared and named by the programmer
and
manipulated
through
specific
statements within the blocks executable
actions.
Recall that the SELECT statement in PL/SQL must only return a single
row. PL/SQL actually attempts to fetch two rows from an implicit cursor:
one to satisfy the query and a second to see if further rows were
returned. One method to eliminate this extra fetch is to use an explicit
cursor.
Can process beyond the first row returned by the query, row by row.
Keep track of which row is currently being processed.
Allow the programmer to manually control them in the PL/SQL block.
BRBRAITT-JUN-2011
173
1.
2.
3.
4.
5.
FETC
H
OPEN
(2)
(3)
empty
(4)
CLOSE
yes
(5)
BRBRAITT-JUN-2011
174
Where:
Cursor_name
is a PL/SQL identifier.
Select_statement
is a SELECT
clause.
Note: Do not include the INTO clause within the cursor declaration because it
appears later within the FETCH statement.
cursor.
Note: If the query returns no rows when the cursor is opened, PL/SQL does not
raise an exception. However, you can test the cursor_ status after a fetch.
Opening the Cursor : Syntax
Open the cursor to execute the query and identify the active set.
OPEN cursor_name;
BRBRAITT-JUN-2011
175
Where:
cursor-name
Variable
Guidelines:
Include the same number of variables within the INTO clause of the
FETCH statement as output columns in the SELECT statement and
be sure that the data types are compatible.
Match each variable to correspond to the columns positionally.
Alternatively, define a record for the cursor and reference the record in
the FETCH INTO clause.
Test to see if the cursor contain rows. If a fetch acquires no values,
that is there are now rows left to process in the active set and no error
is recorded.
Fetching Data from the Cursor: Syntax:
Retrieving the current row values into output variables.
FETCH
cursor_name
INTO
variable1, variable2;
Include the same number of variables.
Match each variable to correspond to the columns
positionally.
Test to see if the cursor contains rows.
BRBRAITT-JUN-2011
176
cursor.
Note: Do not attempt to fetch data from a cursor once it has been closed
or the INVALID_CURSOR exception will be raised.
Closing the Cursor: Syntax
BRBRAITT-JUN-2011
Description
177
%Notfound
%FOUND
%ROWCOUNT
You can only fetch rows when the cursor is open. Determine whether the
cursor is open using the %ISOPEN cursor attribute, if necessary.
Fetch rows in a loop. Determine when to exit the loop by using cursor
attributes.
BRBRAITT-JUN-2011
178
Retrieve the first five line items for an order one by one.
cumulative total for each product to the screen.
Print the
PROCEDURE ord_process
V_ord_id IN s_item.ord_id%TYPE;
IS
V_product_id s_item.product_id%TYPE;
V_item_total NUMBER (11,2);
V_order_total NUMBER (11,2) :=0;
CURSOR item_cursor IS
SELECT product_id, price * quantity
FROM
s_item
WHERE ord_id = v_ord_id;
BEGIN
OPEN item_cursor;
LOOP
FETCH item_cursor INTO v_product_id ,
V_item_total;
EXIT WHEN item_cursor%ROWCOUNT > 5
OR item_cursor%NOTFOUND;
V_order_total := v_order_total + v_item_total;
TEXT_IO.PUT_LINE ( Product ID ||
TO_CHAR (v_product_id) ||
has a total of ||
TO CHAR(v_order_total , $999,999,999.99));
END LOOP;
CLOSE item_cursor;
COMMIT;
END ord_process;
Note: If using %ROWCOUNT, add a test for no rows in the cursor by using
the %NOTFOUND attribute because the row count is not incremented if
the fetch does not retrieve any rows.
BRBRAITT-JUN-2011
179
LOOP
FETCH item_cursor
INTO v_product_id, v_item_total;
EXIT WHEN item_cursor%ROWCOUNT > 5
OR item_cursor%NOTFOUND;
V_order_total := v_order_total + v_item_total;
.
END LOOP;
BRBRAITT-JUN-2011
180
BRBRAITT-JUN-2011
181
Cursor-name
Guidelines
Do not declare the record that controls the loop. Its scope is only in the
loop.
Test the cursor attributes during the loop, if required.
Supply the parameters for a cursor, if required, in parentheses following
the cursor name in the FOR statement.
Do not use a cursor FOR loop when the cursor operations have to be
handled manually.
BRBRAITT-JUN-2011
182
Implicit cursors are used for all DML statements and single row queries.
Explicit cursors are used for queries of zero, one, or more rows.
Cursor Attributes
Evaluates the status of the cursor by using cursor attributes.
Cursors with Parameters
Use parameter to open an explicit cursor several times in a block, returning a
different active set on each occasion.
Cursor FOR Loops
Use cursor FOR loops as a shortcut to open the cursor, fetch rows once for each
loops iteration, and automatically close the cursor after all rows are processed.
BRBRAITT-JUN-2011
183
CHAPTER 9
STORED PROCEDURES, FUNCTIONS & PACKAGES
SUBPROGRAM
Program units are named PL/SQL blocks.
categories.
Stored Subprogram
Application Subprogram
Is in the database
Is within the application.
From any database tool From
only
the
or application
application in which it
was created.
By way of database Independently of, and in
security.
addition
to,
stored
subprograms.
BRBRAITT-JUN-2011
184
Subprogram Components
HEADER -Mandatory
-subprogram
name,type,and
arguments
DECLARATIVE -Optional
- -Local identifiers
EXECUTABLE -Mandatory
- -SQL Statements
- -PL/SQL control statements
EXCEPTION HANDLING-Optional
- -Actions to perform when errors
occur
END; - Mandatory
Creating a Subprogram
Select environment
Compile code
Create Subprogram
Invoke
BRBRAITT-JUN-2011
185
If using Procedure Builder, then select either the Program Units node or
the Database Objects node and Stored Procedures Units subobject node.
2.
If using Procedure Builder, enter the syntax in the Program Unit Editor. If
using SQL*Plus, write your code in a text editor as a script file.
3.
The source code is compiled into p-code. If using Procedure Builder, click
the Compile button. If using SQL*Plus, start your file at the SQL prompt.
4.
Guidelines
STORED PROCEDURES
Create a PL/SQL procedure to store a series of actions for later
execution. The procedure can contain zero or more parameters, which
are arguments that you list when calling the procedure.
BRBRAITT-JUN-2011
186
Where:
Name
Parameter
PL/SQL_BLOCK
performed
BRBRAITT-JUN-2011
187
Procedural Parameters
Transfer values to and from the calling environment through parameters.
There are two types that you use.
parameter is used to define the values used in the executable portion of the
PL/SQL block. The actual parameter, or argument, is referenced when invoking a
subprogram.
Parameter Modes for Formal Parameters
Parameter
Mode
IN
OUT
IN OUT
Description
Default argument.
Passes a value from the calling environment into the
subprogram.
Formal parameter acts as a constant -you cannot overwrite
the value.
Actual parameter can be an expression, a constant, a literal,
or an initialized variable.
Must be specified.
Returns a value from the procedure to the calling
environment.
Formal parameter acts as an uninitialized variable.
Formal parameter cannot be assigned to another variable or
to itself.
Actual parameter must be a variable ; it cannot be a
constant or expression.
Must be specified.
Passes a value from the calling environment into the
procedure, and returns a possibly different value from the
BRBRAITT-JUN-2011
188
Example:
Update the salary of the specified employee to the specified amount through a
procedure.
BRBRAITT-JUN-2011
189
PROCEDURE change_salary
(v_emp_id IN NUMBER,
v_new_salary IN NUMBER)
- - formal parameters
IS
BEGIN - begin PL/SQL block
UPDATE s_emp
SET
salary = v_new_salary
WHERE id = v_emp_id;
COMMIT;
END change_salary;
This procedure, when invoked, will take the parameters for the employee
number and the new salary, and update the salary for that specified employee.
FUNCTION
Create a PL/SQL function to return a value to the calling environment.
You must declare the RETURN data type in the header section of the function
definition, and define the value to be returned in the PL/SQL block. You can also
declare a list of parameters to be passed into the function.
Create function Syntax:
FUNCTION name
[ (Parameter1, para2, ...) ]
RETURN datatype
IS
Pl/sql_block;
Where:
Name
Parameter
Data type
BRBRAITT-JUN-2011
190
BRBRAITT-JUN-2011
191
PACKAGES
INTRODUCTION
Packages are PL/SQL objects that group
other object such as
procedures, functions, types, variables, SQL Cursors and Exceptions as a single
unit with less restriction with respect to dependencies. This is another ADA
feature incorporated in PL/SQL . Packages also provide global variables for
PL/SQL. So packages allow multiple procedures to use the same Variables and
cursors. Procedures within packages may be available to the public in which
case they are accessible to the users of the package or they may be private, in
which case they are only accessible via commands from within the package such
as call from other procedures.
Each package has two parts: The specification and the body. Each of
them stored separately in the data dictionary. The package specification is also
known as the package header. It contains information about the objects you can
access when you use the package. However it does not contain the code for any
procedure.
CREATING PACKAGE
When creating package, the package Specification and the package body
are created separately. Thus there are two commands to use (1) CREATE
PACKAGE for package Specification, and (2)CREATE PACKAGE BODY for the
package body. Both of these commands require that you have the CREATE
PROCEDURE System Privilege. If the package is to be created in a schema
other than your own, then you must have the CREATE ANY PROCEDURE
System privilege.
The Syntax for creating package specification is:
CREATE [ or REPLACE ] package [user.] package_name
{ IS/AS }
procedure_specification |
function_specification |
variable_declaration |
exception_declaration |
cursor_declaration
type_definition
END [package_name];
BRBRAITT-JUN-2011
192
Example:
CREATE PACKAGE salary_package
As
PROCEDURE addemp (p_staffno IN emp_data.staffno%TYPE,
P_emp_name IN emp_data. Emp_name%TYPE,
P_desgn IN emp_data.desgn%TYPE, p_dob IN
Emp_data.dob%TYPE,
p_hq
IN
emp_data.Hq%TYPE,
p_deptno IN Emp_data.deptno%TYPE);
PROCEDURE salupd (p_staffno IN emp_sal.staffno%TYPE,
P_basic
IN
Emp_sal.basic%TYPE,p_gpf_sub
IN
emp_sal.gpf_sub%TYPE,p_gpf_rec
IN emp_sal.gpf_rec%TYPE,p_qtrs IN
emp_sal.qtrs%TYPE);
PROCEDURE Paybillgen;
PROCEDURE Paycalc (p_staffno IN emp_data.staffno%TYPE);
FUNCTION DA (p_basic IN emp_sal.basic%type)
RETURN number;
FUNCTION hra (p_basic IN emp_sal.basic%TYPE,
p_qtrs IN emp_sal.qtrs%TYPE)
RETURN number;
END salar_package;
BRBRAITT-JUN-2011
193
Example:
CREATE PACKAGE BODY salary_package
AS
Crtdate DATE;
Crtmonth varchar2(9);
PROCEDURE addemp (p_staffno IN
emp_data.staffno%TYPE, p_emp_name IN
emp_data.emp_name%TYPE,
p_desgn
emp_data.desgn%TYPE,
p_dob IN emp_data.dob%TYPE, p_hq
emp_data.hq%TYPE,
p_deptno IN emp_data.deptno%TYPE)
IN
IN
IS
V_deptno emp_data.deptno%TYPE;
Empty_staffno EXCEPTION;
BEGIN
IF p_staffno IS NULL
RAISE empty_staffno;
ELSE
SELECT deptno into v_deptno
FROM dept
WHERE deptno = p_deptno;
INSERT INTO emp_data
VALUES(p_staffno, p_emp_name, p_desgn, p_dob,
p_hq, p_deptno);
INSERT INTO new_emp
BRBRAITT-JUN-2011
194
BRBRAITT-JUN-2011
195
BRBRAITT-JUN-2011
196
BRBRAITT-JUN-2011
197
PACKAGE INITIALIZATION
A package body may also include code that is run every time the package
is invoked, regardless of the part of the package that is executed. In the
following e.g., SALARY_PACKAGE package body is modified to include a SQL
statement that records the current date and the current month , at the start of the
package execution. Two new variables crtdate & crtmonth also have been
declared in the package body in order to record these values. Since the 2 new
variables are declared within the package body, they are not available to the
public. Within the package body, they are separated from the procedures and
functions. The package initialization code is shown as follows:
CREATE OR REPLACE PACKAGE BODY salary_package
AS
Crtdate
DATE;
Crtmonth
varchar2(9);
BRBRAITT-JUN-2011
198
Note: The code that is to be run every time the package is executed is
stored in its own PL/SQL block at the bottom of the package body. It
does not have its own end clause; it uses the package bodys end
clause.
Every time the salary-package package is executed the crt date and crt
month variables will be populated by the query shown in the previous
listing. These 2 variables can then be used by the function &
procedures within the package ie; Addemp procedure uses this
variables for populating in the new_emp table.
DROPPING PACKAGES
Packages and its body can be dropped separately as follows:
To drop a package body, use the drop package command with the body
clause, as shown in the following listings:
DROP PACKAGE BODY salary_package;
BRBRAITT-JUN-2011
199
SALARY_PACKAGE
HEADER
SALARY_PACKAGE
BODY
The BODY of
salary_package
depends on the
emp_data, emp_sal
& Dept tables
EMP_DATA, EMP_SAL,
& DEPT
The package body depends on emp_data, emp_sl & dept tables and
package header. The package header does not depend on anything. This is the
advantage of packages. We can change the package body without having to
change the header. Therefore other objects which depend on the header wont
have to be recompiled at all , since they never get invalidated. If the header is
changed, this automatically invalidates the body, since the body depends on the
header.
We can examine the behaviour as follows:
In the previous salary_package package, we can refer it with the body and
the table emp_data.
We can query the information about the above objects as follows.
SELECT object_name, object_type,status
FROM user_objects
WHERE object_name IN (salary_package, emp_data);
OUTPUT:
OBJECT_NAME
SALARY_PACKAGE
SALARY_PACKAGE
EMP_DATA
OBJECT_TYPE
PACKAGE
PACKAGE BODY
TABLE
STATUS
VALID
VALID
VALID
200
OBJECT_TYPE
PACKAGE
PACKAGE BODY
TABLE
STATUS
VALID
VALID
VALID
OUTPUT:
OBJECT_NAME
SALARY_PACKAGE
SALARY_PACKAGE
OBJECT_TYPE
PACKAGE
PACKAGE BODY
STATUS
VALID
INVALID
BRBRAITT-JUN-2011
201
CHAPTER 10
ORACLE ARCHITECTURE AND USER MANAGEMENT
ARCHITECTURE OF THE ORACLE SERVER
The server product is simply an executable that performs important
activities when it is run. Access to the Oracle9i Database is supported by the
Oracle executable and a series of support routines and files that fall into the
categories described in the following list.
INIT.ora.
This file contains entries that determine the runtime
environment of the Oracle 9i database as it operates. The values for the
entries in this file control items such as the amount of memory allocated
to the instance and the breakdown of the structures within that memory.
Shared memory
Often referred to as RAM on the PC, this is an
amount of a computers memory that is acquired when an Oracle 9 i
database is started. This chunk of memory is acquired when the Oracle 9i
server is started and is affectionately called the SGA, or system global
area.
Database files
These fall into three categories-data files, control
files, and redo log files. The files that end in .dbf are data files, the ones in
.ctrl are control files, and .log files are online redo logs.
Support processes
These are workers that are spawned when an
Oracle 9i instance is started, and they help to facilitate access to a set of
Oracle database files
Network access
This is enabled by Oracle 9is Oracle Net product,
Its precursors were SQL*Net, delivered with versions upto and including
Oracle7, and Net8 with all releases of Oracle8.
Trace files
These are continually written to as Oracle9i operates and
are deposited in locations specified in an instances INIT.ora. They
contain primiarily two kinds of descriptive information -certain types of
Oracle errors and timestamp information related to some significant
instance activities.
Runtime libraries
These are the equivalent of PC dynamic link libraries,
containing routines and service components that allow the Oracle9i server
to operate and perform a suite of sophisticated functionally on its user
communitys behalf.
BRBRAITT-JUN-2011
202
Let us have a brief look at what goes on as the Oracle9i server operates.
BRBRAITT-JUN-2011
203
Checkpoint (ckpt)
When a check point activity begins, this process updates all the database
data files, with the details of the checkpoint. The database writer is the only
process that writes data to these database files, whereas the ckpt process
ensures the data files are in synch with one another after a checkpoint
completes. This process we call the Dispatcher -ensuring all is in synch.
Recoverer (reco)
The recoverer processs primary responsibility is to resolve failed
transactions in a distributed Oracle9i environment. This process automatically
connects to remote nodes, involved in a distributed transaction and resolves the
failed transactions, removing rows where appropriate from all nodes involved in
the failure. This recoverer process may attempt to connect to remote nodes more
than once for transaction resolution, with the delay time between consecutive
connections increasing each time.
Archiver (arc0)
The archiver process automatically saves copies of redo logs in a DBAspecified storage location, when media recovery is enabled. We discuss the
circular usage of the online redo logs and the special form of media recovery
called archivelog mode in the upcoming section Redo Logs.. This is an
optional process spawned by log_archive_start = true in the INIT.ora.
A network of background processes supports the operation of an Oracle9i
database. We feel it is relevant to the understanding of the Oracle software, and
the management of the 9i database in particular, to cover details on how the
support processes do just that -support. Let us move on to the INIT.ora, the first
piece in the Oracle9i server O/S file layer.
INIT.ora
The INIT.ora file is read when an Oracle9i instance is started .
Let us look at the type of parameters found in the INIT.ora file and a few
examples of each.
BRBRAITT-JUN-2011
204
Location Entries
The first category of parameters describes the location of one or more files
required by or written to as the instance operates. In some cases, it contains the
fully pathed location, directory, and file name, as in control_files. In other
cases, it simply contains a directory name, as in db_create_file_dest. When the
instance is started, Oracle9i verifies that the directories and files mentioned in
INIT.ora exist and can be written to and read from. If there are any problems,
Oracle9i displays one or more error messages along the lines of those shown in
the next listing.
SQL> startup
ORA-00444: background process LGWR failed while starting
SQL>
SQL> startup
ORACLE instance started.
Total System Global Area 537691548 bytes
Fixed Size
279964 bytes
Variable Size
469762048 bytes
Database Buffers
67108864 bytes
Redo Buffers
540672 bytes
ORA-00205: error in identifying controlfile, check altert log for more info
Limiting Entries
Parameters that list a number for controlling implementation of a feature of
the Oracle9i server usually fall into one of two categories:
There are some operating system -and Oracle9i -enforced minimums and
maximums that can be specified for these entries, and if they exist on your
hardware platform, you will be told when the instance is started. An occurrence
of this is shown in the next listing.
/d0/oraclehome/product/oracle9.0.1/dbs> sqlplus /nolog
SQL*Plus: Release 9.0.1.0.0. Production on Sun Jun 17 13:44:09 2009
BRBRAITT-JUN-2011
205
Feature Entries
Feature entries also fall into two categories:
Those that can only specify keywords like true, false, partial, or full. A
few parameters that fall into this category are max_dump_file_size,
oracle_trace_enabled, and row locking. Any values other than those in
the approved list for each parameter will be rejected, as shown next.
206
VARCHAR2(512)
VARCHAR2(9)
VARCHAR2(5)
VARCHAR2(9)
VARCHAR2(10)
VARCHAR2(5)
VARCHAR2(64)
VARCHAR2(255)
You may now have a preliminary knowledge of INIT.ora , what this file is all
about-
Name
Null?
STATUS
NAME
Type
VARCHAR2 (7)
VARCHAR2(513)
The startup and shutdown of the Oracle9i database uses the instance
control files for consistency and completeness checking. When we speak of
consistency, we refer to the cross-file dependencies all over the Oracle9i
database that are checked and rechecked on startup and shutdown. In this
context, completeness means a check for the presence of and accessibility to all
the files mentioned in the control files. Let us look now at the redo or transaction
logs.
BRBRAITT-JUN-2011
207
Redo Logs
The redo log files are the heart of the proprietory Oracle9iserver. Some
other vendors may have a similar facility for tracking the activity against their
database. Oracle will write to any number of redo log files that the DBA chooses
to specify. Redo logs were introduced in Oracle V6 (circa 1988), and with
Oracle7 in February 1993, redo log files were enhanced to become multimembered redo log groups. When DBA now talk about the online redo logs,
they really mean online redo log groups.
When redo log groups are created, we give them an integer number,
which becomes the group number to which they are referred by the DBA. We
then speak of redo log group 1or redo log group 2, and so on. As users interact
with the Oracle9i database, a record of their activities is written to the online redo
logs at commit or rollback time. Redo logs are a finite size, and when they fill up,
Oracle switches to another set of log files.
NOTE
Each member of the same redo log group is a mirror image of the other
members in the same group.
Oracle9i needs at least two single-membered redo log groups to operate,
though we recommend at least three two-membered redo log groups. These
must be made manually using a GUI such as OEM or SQL*Plus. When a redo
log group fills up, Oracle switches to the next available group. Before a group is
marked available, Oracle marches through each redo log group reconciling any
outstanding activities, and then marks the group able to be used the next time a
switch occurs. The question you may have already asked yourself is What if a
group has not yet been marked as reusable and its turn comes up?. Oracle9i
suspends activity against the database until the group is marked reusable, and
then operations carry on
Figure 1
illustrates this concept
Group 1
Group 2
Group 3
BRBRAITT-JUN-2011
208
Group 1
Group 2
Group 3
.
Figure -The circular re-use of the online redo log groups
Note
Online redo log file information can be viewed in the v$logfile data
dictionary view shown in the next listing.
SQL>desc v$logfile
Name
Nul?
Type
---------------------------------------------GROUP#
NUMBER
STATUS
VARCHAR2(7)
TYPE
VARCHAR2(7)
MEMBER
VARCHAR2(513)
BRBRAITT-JUN-2011
209
reco
pmo
n
smon
Dbw0
SHARED
MEMORY
( SGA)
LGWR
R
ckpt
Data
files
Arc0
Control
files
Offline
Offline
storage
Offline
storage
Online
storage
redolog
Offline
storage
When the block size keyword is used to create a table space, there must
be a corresponding parameter (in this case, db_2k_cache_size) in
INIT.ora for that sized block. If you include the block size keyword
without its corresponding size parameter, you will get error ORA_29339.
BRBRAITT-JUN-2011
210
Entity
Database
Tablespace
Data file
Is a superset of
Tablespace / data file
Datafile
Belongs to
Database
Tablespace
BRBRAITT-JUN-2011
211
Activity
Undo
1
2
Pretransaction #1
Update savings set balance
= balance + 12000 where
account = 55524;
Rollback;
Update savings set balance
= Balance + 1200
where account = 55524;
Commit;
Empty
940
Data
in Seen
memory
others
940
940
12,940
940
Empty
940
940
2,140
940
940
Empty
2,140
2140
3
4
5
by
SID 99
Other Sessions
1
940 (D)
940 (D)
2
12,940 (M)
940 (U)
3
940 (M)
940 (M)
4
2,140 ( M)
940 (U)
5
2.140 (M)
2,140 (M)
--------------------------------------------------------------------------------------------------TABLE- Who Views What Value and from Where
The m word (memory) keeps surfacing in this section. Speaking of memory, let
us move on and look at two significant areas in shared memory -the library
BRBRAITT-JUN-2011
212
BRBRAITT-JUN-2011
213
USER SESSIONS
User sessions read data from
and return data to the data cache
Data cache
SGA
Library
cache
BRBRAITT-JUN-2011
214
Any SQL statement executed against the Oracle9i database must first be
placed in the library cache and marked ready-to-execute. This library cache, is
also referred to as the shared pool.
Locks and Latches
Locks and latches are fundamental to the protection of your data and
shared memory structures. Oracle9i runs in a multi user environment, and
without these protection mechanisms, the smooth and consistent operation of the
database would be in question.
Locks
Oracle9i uses locks to ensure that different sessions are not able to
interact with the same data in use by other sessions. Interact in this context
means anything other than select. This protects the integrity of the data and is
managed automatically by Oracle9i, without need for manual intervention. Locks
are acquired as SQL statements begin their interaction with data and last for the
duration of a transaction. Transactions commonly end with a commit or
rollback, the latter restoring data to its pre-transaction state. Oracle9i uses two
locking modes:
Exclusive mode will not allow the locked resource to be shared what-soever by any concurrent sessions. This lock is acquired to modify data or
define the structures within which data resides.
Share mode allows concurrent read access to the same chunk of data,
with escalation to an exclusive mode lock when change is initiated.
Oracle 9i obtains a share mode lock on a row of data as it is accessed as
part of the result set to a query. If, and only if, that query leads to an update or
delete statement, the lock is escalated to an exclusive row lock, if the row is not
already locked in that mode. Oracle9i allows simultaneous updates to rows
sitting in the same data block. If two sessions request update access to the
same row in the same data block, they queue up and go about their business in
a serial fashion. There are two types of locks Oracle9i acquires on its data;
DML locks, or data manipulation locks, ensure data integrity in multi- user
environments for the purposes of protecting data.
DDL locks, or data definition locks, protect the structure of objects and are
acquired for data definition activities.
215
Latches
Latches are low-level mechanisms that help manage the internal
operations of the Oracle9i software. They can be thought of as a type of lock,
acquired and released in subsecond time periods . Latches are almost always
obtained when requested , but, as the activity on an Oracle9i database
increases, often queue behind one another for getting hold of precious
resources. Remember the redo logs and how transaction information is written
to these files as the database operates. A special redo copy latch ensures that
one and only one process writes to the redo logs, at a time. Obtaining a latch is
only part of the work; there is a cleanup phase that comes into play as a latch is
released.
Latches are required when working with shared memory structures in the
SGA. If working with a particular structure requires a latch and that structure is in
use, a wait situation is created. There are two types of latches:
DBA need not worry themselves about latches unless they cause
problems in their databases, if they ever do. Suffice it to say, latches are part
of the puzzle fundamental to the operation of the Oracle9i database and,
most of the time, go about their work unnoticed. They are an essential player
in the running of the instance . We find it almost ironic that the words lock and
latch both start with the same letter-/-and the words look out start with the
same letter, which is what you will do if your locks and latches lead to
significant wait situations. The hourglass displayed by the mouse cursor
when a window is busy is a familiar example of a wait situation.
We have given you a framework of how the Oracle9i database is
put together and what pieces play what role. Each component in the software
equation may not be all that important on its own; bring all of them together
and you have a powerful, robust, and fast database management system i.e.
Oracle9i.
BRBRAITT-JUN-2011
216
Account Security
In order to access data in an Oracle database, you must have
access to an account in that data base. Each account must have a
password associated with it. A database account can also be tied to
an operating system account. Passwords are set for a user when the
users account is created and may be altered after the account is
created.
A users ability to alter the account password will be limited by the
tools to which the user is granted access. The data base stores an
encrypted version of the password in a Data Dictionary table. If the
account is directly related to an OS account, it is possible to by-pass
the password check and rely on the operating system authentication
instead.
The passwords can expire and the DBA can establish the conditions
under which a password can be re-used in a database setting for
password history. You can use profiles to enforce standards for the
passwords and can automatically lock accounts, if there are multiple
consecutive failure to connect to the account.
Object Privileges
Access to objects within a database is enabled via Privileges.
These allow specific database commands to be used against specific
database objects via the Grant Command
217
Implementing Security
The security capabilities in oracle include roles, Profiles and direct
grant of privileges. The Oracle Enterprise Manager toolset provides a
security Manager tool to enable the management of user accounts,
roles, privileges and profiles.
Creating Users
When creating a user, your goal is to establish a secure, useful
account that has adequate privileges and proper default settings.
When the account is created, it will not have any capabilities and users
will not even be able to login, until that privilege is granted.
All of the necessary settings for a user account can be specified
within a single create user command. These settings include values
for all of the parameters listed.
ALTER USER
Modify the security settings for an existing database user, to change
the options associated with that user. Options that can be changed
through the Alter user command are:
Password
OS Authentication
Default tablespace
Temporary tablespace
Quota for Tablespace
Profile
Default Roles
BRBRAITT-JUN-2011
218
SYNTAX:
ALTER USER
username
IDENTIFIED
by password / externally
DEFAULT TABLESPACE tablespace_name
TEMPORARY TABLESPACE tablespace_name
QUOTA integer / unlimited ON tablespace_name
DEFAULT ROLE role_name /All except role/
None;
WHERE :
Default Role
Default Role
Default Role
Default Role
Default Role
BRBRAITT-JUN-2011
219
DBA_PROFILES
DBA_TS_QUOTAS
USER_TS_QUOTAS
Example 1: Display information about all users of the database with the
DBA_USERS data dictionary view.
SELECT * from DBA_USERS;
Example 2:Display tablespace quotas
USER_TS_QUOTAS data dictionary view.
for
the
current
user
with
the
220
Query the V$Session data dictionary view to identify the session ID and
serial number of user session.
SELECT SID, SERIAL#, username from V$session;
USER PROFILES
You can use profiles to place limits on the amount of system and
database resources available to a user and to manage password restrictions. If
no profiles are created in a database ,then the default profile, which specifies
unlimited resources for all users will be used.
Resources that can be limited via profiles
SESSIONS_PER_USER
in an instance
BRBRAITT-JUN-2011
221
Password Management
You can use profiles to manage the expiration, re-use and complexity of
passwords.
You can limit the life time of a password and lack an account whose
password in too old.
You can also force a password to be at least moderately complex and lock
an account that has repeatedly failed login attempts . If you set the
failed_ login_ attempts resource of the users profile to 5, then five
consecutive failed login attempts will be allowed for the account, the6th
will cause the account to be locked. If the correct password is supplied on
the fifth attempt, then the failed-login-attempt count is reset to O, allowing
BRBRAITT-JUN-2011
222
BRBRAITT-JUN-2011
223
PRIVILEGES
You can grant users privileges to access the database and objects
within the database and allow them specific system privileges.
Privilege Type
1.
SystemPrivileges
Object Privileges
System Privileges
Allows users to perform a particular database operation or class of
operation.
Types of system Privileges
1.
2.
224
Object Privileges
Allows users to perform a particular action on a specific table, view,
sequence or stored procedures by granting them object privileges. The type of
object privileges vary from object to object. Different object privileges allow the
use of specific SQL statements.
BRBRAITT-JUN-2011
225
Object Privilege
SELECT
Select from Object (table, view)
UPDATE
Update object (table or view)
ALTER
Alter object(table or sequence)
DELETE
Delete from object
EXECUTE
Execute object (Procedure/function)
INDEX
Create Index On Object (Tables only)
REFERENCES
Create or Alter table statement
defining a Foreign key
Integrity constraint on object (tables
only)
- You can grant object privileges to users and roles with the Grant command.
Syntax:
GRANT Object privilege / ALL [column]
ON Object TO user / Role / Public
WITH GRANT OPTION;
Where
Object Privilege
Column
- grants to al users.
- allows the grantee to grant the object
Privileges to other users/roles
BRBRAITT-JUN-2011
226
Example:
GRANT Select ON EMP TO Emi with Grant option;
Note:
Emi can grant the privilege to another user or role.
Display object privileges
Select * from DBA_TAB_PRIVS;
Helpful Data Dictionary views
DBA_TAB_PRIVS
DBA_COL_PRIVS
base.
USER_TAB_PRIVS
Grantors can revoke privilege from only those users to whom they have
granted privileges.
Example;
REVOKE SELECT ON EMP
From Emi;
ROLES
BRBRAITT-JUN-2011
227
Create Roles
Define categories of privileges for particular groups of users by
creating roles containing those privileges.
Syntax:
CREATE ROLE Role_name not identified / identified BY
password / externally;
Where
Role name
Not identified
Identified
By password
Externally
BRBRAITT-JUN-2011
228
ROLE_SYS_PRIVS
ROLE_TAB_PRIVS
ROLE_ROLE_PRIVS
SESSION_ROLES
USER_ROLE_PRIVS
DBA_ROLES
*********************
BRBRAITT-JUN-2011
229