Oracle 9i Notes
Oracle 9i Notes
Oracle 9i Notes
SL Contents Page No
1 Introduction To DBMS
2 Oracle Data Type
3 Structure Query Language (SQL)
4 Sql* Plus Editing Commands
5 Sql * Plus File Commands
6 Data Retrieval/Query Language
(Drl/Dql) (Select)
7 Data Manipulation Language (DML)
(Insert, Update, Delete, Merge)
8 Data Dictionary Language (DDL)
(Create, Alter, Drop, Truncate, Rename)
9 Data Control Language (DCL)
(Grant, Revoke)
10 Transaction Control Language (TCL)
(Commit, Rollback, Savepint)
11 Oracle Functions
12 Group By Clause
13 Integrity Constraints
14 Joins
15 Sub Queries
16 Working With Database Objects
• Views
• Sequences
• Inedexes
• Synonyms
• Cluster
17 Partitions
18 Locking Mechanism
19 More Commands In Oracle 9i
20 Pl/Sql
21 Cursor
22 Exception Handling
23 Procedures
24 Functions
25 PACKAGE And PACKAGE BODY
26 Trigger
27 File Input/Output (I/O) (Utl_File)
28 Oracle Supplied Packages
29 New SQL Function In Oracle 9i
30 Implementing Object Techniques
31 Using Lobs
32 Some Advance Fetures In Oracle 9i
33 Oracle Utilities
• Export
• Import
• Sql Loader
34 Oracle Architecture
Introduction to DBMS
Database: A Database is a collection of inter-related data from which some information can be
extract.
Database Model: The data structures and access techniques provided by a particular DBMS are
called as Data Model.
• Hierarchical
• Network
• Relational
- This model is like a hierarchical tree structure; used to construct a hierarchy of records in the
form of nodes and branches. The data elements presnt in the structure of parent/ child
relationship.
- The simple structure of a Hierarchical database became a disadvantage when the data had a
more complex structure. In an order-processing database, for example, a single order might
participate in three different parent/child relationships, linking the order to the customer who
placed it, the salesperson who took it, and the product ordered.
The Network model extended the Hierarchical model by allowing a record to participate in
multiple parent/child relationship
Network databases had their disadvantages like Hierarchical database, they where very rigid. The
set relationships and the structure of the records had to be specified in advance.
- Changing the database structure typically required rebuilding the entire database.
Relational Model
2
• Column name must be unique
• Row must be unique
• It eliminated the explicit parent/child structures from the database, and instead of
represented all data in the database as simple row/column tables of data values.
• A relational database is a database where all data visible to the user is organized strictly
as tables of data values, and where all database operations work on these tables.
The publication of the paper “A relational Model of Data for Large Shared Database” by Dr. E.F.
Codd in June 1970 in the “Communication of ACM” , set a trend for virgorous and extensive
investigation into a theoretical frame work to support further work in the area of Data Modelling.
The end result is the Relational Database Management System.
This means that the major DML commands, namely SELECT, UPDATE, DELETE and INSERT
must be available and operational on sets of rows in a relation.
Entity Integrity: No component of a primary key can have missing values or null values.
Referential Integrity: For each distinct foreign key value there must exist a matching primary
key value in the same domain.
An RDBMS product has to satisfy at least six of the 12 rules of Codd to be accepted as full
fledged RDBMS.
One to One
_____ _______
| | | |
| | -->--- /\ --<---- | |
----- \/ -------
One to many
_____ _______
| | | |
| | -->--- /\ --<<---- | |
----- \/ -------
Many to one
_____ _______
| | | |
| | -->>--- /\ --<---- | |
----- \/ -------
Many to Many
_____ _______
| | | |
| | -->>--- /\ --<<---- | |
----- \/ -------
Degree of Relationship
Normalization: It’s a process of efficiently organizing data in a database. There are two goals of
Normalization Process: eliminate redundant data (for example, storing the same data in more
than one table) and ensure data dependencies make sense (only storing related data in a table).
Both of these are worthy goals as they reduce the amount of space a database consumes and
ensure that data is logically stored.
First Normal Form (1NF) sets the very basic rules for an organized database:
- Eliminate duplicative columns from the same table.
- Create separate tables for each group of related data and identity each row with a unique
column (Primary Key)
Second Normal Form (2NF) further addresses the concept of removing duplicative data:
- Remove subsets of data that apply to multiple rows of a table and place them in separate
rows.
- Create relationships between these new tables and their predecessors through the use of
foreign keys.
Finally Forth Normal Form (4NF), also known as Boyce- Codd normal form (BCNF) has one
requirement:
- A relation is in BCNF if and only if determinant is a candidate key.
Primary key:
In a well- designed relational database every table has some column or combination of columns
whose values uniquely identify each row in the table. This column is called the primary key.
Foreign Key:
A column in one table whose value matches the primary key in some other table is called as a
foreign key.
5
Oracle DATA Type
6
16 TIMESTAMP All values of TIMESTAMP WITH TIME ZONE, with the following
(fractional_seconds_pr exceptions:
ecision) WITH LOCAL • Data is normalized to the database time zone when it is stored
TIME ZONE in the database.
• When the data is retrieved, users see the data in the session
time zone.
17 INTERVAL YEAR Stores a period of time in years and months, where year_precision is
(year_precision) TO the number of digits in the YEAR datetime field. Accepted values are 0
MONTH to 9. The default is 2.
18 INTERVAL DAY Allows time to be stored as an interval of days to hours, minutes and
(day_precision) TO second. Useful in presenting the precise difference between two date
SECOND time values
(fractional_seconds_pr
ecision)
New Datatypes in 10g
19 BINARY_FLOAT Stores a single precision 32-bit floating-point number.
20 BINARY_DOUBLE Stores a single precision 64-bit floating-point number.
SQL Language
8
SQL> select * from dept;
LOCATION_ID LOC_NAME
100 NEW YORK
200 DALLAS
300 CHICAGO
400 BOSTON
SQL> L
SQL> A , Job
SQL > L
------------------------
SQL > select * from emp ;
SQL> L
- Display all the Employees of their EMPNO, name, designation ,salary and department no from
EMP table
ARITHMETRIC EXPRESSION
Display all the Employees of their EMPNO, name, adding $1000 to everybodies salary from EMP
table with changing the salary column heading
SQL> select empno,ename,sal + 1000 "Total Salary" from emp;
SQL> select empno,ename,sal + 1000 as TotalSalary from emp;
SQL> select empno,ename,sal + 1000 TotalSalary from emp;
Concatenation Operator
- Concating employee no and name column
SQL> select empno||' '||ename from emp ;
SQL> select ename ||' having Employee Is '||empno from emp;
Duplicate Row
SQL> select distinct deptno from emp;
SQL> select distinct job from emp ;
Logical condition
SQL> select * from emp where sal > 1000 and job='SALESMAN' ;
SQL> select * from emp where sal > 1000 or job='SALESMAN' ;
SQL> select * from emp where job in ('SALESMAN','CLERK') ;
SQL> select * from emp where job not in ('SALESMAN','CLERK') ;
SQL> select empno,ename,sal from emp where ename not like 'S%' ;
SQL> select empno,ename,sal from emp where sal between 1000 and 2000 ;
SQL> select empno,ename,sal from emp where sal not between 1000 and 2000 ;
---------------------------------------------------------------------------------
Data Manipulation Language (DML) (INSERT, UPDATE, DELETE, MERGE)
10
SQL> insert into dept (deptno,dname,loc) values (50,'DDDD','dddd') ;
SQL> insert into dept (deptno,dname,loc) values (&deptno, &dname, &loc) ;
SQL> insert into dept values (50,'DDDD','dddd') ;
- Merging Rows
create table copy_emp
(EMPNO NUMBER(4),
ENAME VARCHAR2(10),
SAL NUMBER(7,2),
DEPTNO NUMBER(2)) ;
Creating a table
- To renaming a column
Alter table emp rename column ename to empname ;
Dropping a table
Truncating a Table
truncate table dept;
Renaming a table
Rename oldtablename to newtabalename;
Rename emp to emp1 ;
user1 -
-Granting the select previledge to user2
SQL> GRANT select on emp to user2
user2
User2 is viewing the user1 ‘s emp table
select * from user1.emp ;
12
user1 -
REVOKE
Using the REVOKE command, a DBA can revoke database privileges from the user(s)
user1 -
User1 is revoking the select previledge from user2 on emp table
user1 -
The ROLLABCK command is used to discard parts or all the work the user has done in the
current transaction
To undo the previos command from after the commit .
SQL> Rollback;
SQL> Savepoint a ;
SQL> Rollback to savepoint a ;
ORACLE FUNCTIONS
Oracle functions serve the purpose of manipulating data items and returning a result. Functions
are also capable of accepting user-supplied variables or constants and operating on them. Such
variables or constants are called arguments.
Oracle Function can be clubbed together depending upon whether they operate on a single row
or a group rows retrieved from a table. Accordingly, functions can be classified as follows:
13
Functions that act on a set of values are called set of values are called Group Functions. For
example, SUM, is a function, which calculates the total set of numbers. A group function returns
a single row for a group of queries rows.
Aggregate function
Numeric Functions
String Functions
Date Functions
Conversion Functions
Group By Clause
The Group By clause is used with SELECT to combine a group of rows based on the values of a
particular column or expression. Aggregate functions rea used to return summary information
for each group. The aggregate functions are applied to the individual groups.
level Command-->
15
select level, empno, ename, mgr from emp start with mgr is null
connect by prior empno=mgr Order by level;
- List the average salary for all department employing more than five people.
Note: The WHERE clause cannot be used to restrict the groups that are returned. We can only
use where to restrict individual rows.
-- List the total salary, maximum and minimum salary and the avrage salary of emplyees job
wise department no 20 and sipaly only those rows having average salary greater than 1000. The
output should be arranged in the descending order of sum(sal).
SQL> select job,sum(sal), min(sal), Max(sal), Avg(sal) from emp where deptno=20 group by job
having avg(sal) > 1000 order by sum(sal);
Order By Clause
ORDER BY Clause will arrange the final result in the order specified
Integrity Constraints
• Constraints are enforced on data being stored in a table, are called Constraints.
• Constraints super control the data being entered into a table for permanent storage.
• Constraints are preferred Rules applied on thable columns while creating or after creation
• These are automatically activated whenever DML statement is performed on a table
• Provies high security
Example
Create a table using Primary Key and Not null constraints
16
create table employee
(empno number(4),
ename varchar2(30) not null,
Job varchar2(30) unique ,
deptno number(2) not null,
constraint Emp_pk_id primary key (empno)) ;
- For foreign key , create the master table first and after that child table.
- Creating a table using foreign key, primary key, unique , check and default constraint
Note: If a user is not giving the constraint name, Oracle automatically create a constraint named
as “SYS_C0 (some number)”
JOINS
To join two tables, the retrieval criteria will typically specify the condition that a column in the
first table (which is defined as a foreign key) is equal to a column in the second table (which is
the prrimary key
Types of Joins
Oracle Proprietary Joins (8i and Prior) SQL: 1999 Complaint Joins:
- Equi join - Cross Joins
-Cartesian Joins - Natural Joins
- Non-equi join - Using Clause Joins
- Outer Join - Inner Joins
- Self Join - Full or two side outer joins
- Joins with the ON Clause
17
Equi –Joins
When two tables are joined together using equality of values in one or more columns, they make
an Equi Join.
Cartesian Joins
When no join condition clause is specified in WHERE clause, each row of one matches every row
of the other table. This results in a Cartesian product.
SQL> select * from emp, dept ;
If the number or rows in emp Table is 14 and dept table has 4 , then the total number rows
produced is 56.
Non-Equi-joins:
select e.name,e.sal,j.grade from emp e , salgrade j where e.sal between j.losal and j.hisal ;
If there are any values in one table that do not have corresponding value(s) in the other, in an
euqi join that row will not be selected. Such rows can be forcefully selected by using the outer
join symbol (+). The corresponding columns for that will have NULLs.
Self-joins
To Join a table itself means that each row of the table is combined with itself and with every
other row of the table. The self join be viwed as a join of two copies of the same table. The table is
not actually copied, but SQL performs the command as through it were.
select WORKER.ENAME, MANAGER.ENAME “Manager” from emp worker, emp manager where
worker .mgr=manager.empno ;
Cross Join
select ename,dname from emp cross join dept ;
select ename,dname from emp, dept ;
Natural Join
- The NATURAL JOINS clause is based on all columns in the two tables that have same name
18
select deptno,dname,location_id,loc_name from dept natural join locations ;
select deptno,dname,location_id,loc_name from dept natural join locations where deptno in
(10,20) ;
Inner Joins
Select e.ename,e.deptno,d.dname from emp e inner join dept d on (e.deptno=d.deptno) ;
Set Operator
Set Operators are used to combine information of similar type from one or more than one table
Data types of corresponding columns must be the same
The types of SET operators in ORACLE are:
Union: - Rows of first query plus rows of second query, less duplicate rows
union all - Rows of first query plus rows of second query, with duplicate rows
Intersection – Common rows frm all the queies
Minus – Rows unique to the first query
UNION
select * from emp union select * from emp1 ;
UNION ALL
select * from emp union all select * from emp1;
INTERSECT
select * from emp intersection select * from emp1;
19
MINUS
select * from emp minus select * from emp1;
SUB QUERIES
Sub query: A sub query is a SELECT statement is embedded in a clause of another SELECT
statement.
You can build powerful statements out of simple ones by using sub queries. They can be very
useful when need to select rows from a table with a condition that depends on the data in the
table itself:
You can place the sub query in a number of SQL clause, including
- The sub query (inner query) executes once before the main query.
- The result of the sub query is used by the main query (Outer query).
select ename,job from emp where deptno = (select deptno from emp where empno=7902) ;
select ename,sal from emp where sal > (select sal from emp where ename='SMITH') and
deptno = (select deptno from emp where ename='SMITH') ;
select ename,sal from emp where sal > (select avg(sal) from emp);
select deptno,min(sal) from emp group by deptno having min(sal) > (select min(sal) from emp
where deptno=20) ;
select e.ename,e.sal,e.deptno,b.salavg from emp e, (select deptno, avg(sal) salavg from emp
group by deptno) b where e.deptno=b.deptno and e.sal > b.salavg ;
(IN)
select ename,sal from emp where sal in (select min(sal) from emp group by sal) ;
select sal from emp where sal < all (select avg(sal) from emp ) ;
(ANY)
select ename,sal from emp where sal < any (select min(sal) from emp group by sal) ;
20
(ALL)
select empno,ename,job,sal from emp where sal < all (select sal from emp
where job='MANAGER') ;
select ename,sal from emp where sal < any (800,1600) order by sal ;
select ename,sal from emp where sal < any (1200,1600) ;
-----select ename,sal from emp where sal = any (select min(sal) from emp
group by sal) ;
select ename,sal from emp where sal < all (1000,2000,3000) ;
select empno,ename,sal from emp where any < (1200,1600);
Correlated sub queries are used for row-by-row processing. Each sub query is executed once
for every row of the outer query.
SQL> SELECT ENAME, SAL, DEPTNO FROM EMP OUTER WHERE SAL > (SELECT AVG(SAL)
FROM EMP WHERE DEPTNO=OUTER.DEPTNO ) ;
SQL> SELECT ENAME, SAL, DEPTNO FROM EMP OUTER WHERE EXISTS (SELECT * FROM
EMP WHERE DEPTNO= OUTER.DEPTNO)
SQL> SELECT ENAME, SAL, DEPTNO FROM EMP OUTER WHERE NOT EXISTS (SELECT *
FROM EMP WHERE DEPTNO= OUTER.DEPTNO);
EXISTS Operator
List all employees who have atleast one person reporting to them
SQL> Select empno,ename,job,deptno from emp e where EXISTS (select empno from emp where
emp.mgr=e.empno) ;
VIEWS
VIEWS are Database Objects whose contents are derived from another table
- A VIEW Contains no data of its own
- The command for creating VIEW is CREATE VIEW command
- The changes in the tables are automatically reflected in the VIEWS
Advantages of a VIEW
- To restrict data access
- To make complex queries easy
21
- To provide data independence
- To present different views of the same data
Simple View
Complex View
- Creating a View using Group by function
SQL> create or replace view emppview1 as select deptno, count(*) total from emp group by
deptno ;
SQL> select rownum as rank, ename,sal from (select ename,sal from emp order by sal desc)
where rownum <= 3 ;
create view vname1 as select e.ename,e.deptno,d.dname from emp e left outer join dept d on
(e.deptno=d.deptno);
22
SQL> DESC bcd
Dropping a View
SQL> Drop view viewname ;
SEQUENCES
A Sequence:
INDEXES
An Index:
- Is used by the Oracle Server to speed up the retrieval of rows by using pointer.
- Can reduce disk I/O by using a rapid path access method to locate data quickly.
Automatically:
A unique index is created automatically when you define a PRIMARY KEY or UNIQUE constraint
in a table definition.
Manually:
Users can create non-unique indexes on column to speed up access to the rows.
23
BIT MAP INDEXES
Dropping a Index
SQL> Drop Index <IndexName> ;
SYNONYMS
CLUSTER
Clustering is a method of storing tables that are intimately related and often join together into
the same area on disk. It requires at least one cluster column from each of the tables. These
must be of the same data types and size, but are not required to possess identical names. For
the tables in a cluster, rows with identical column values are kept together on disk in the same
area, the same logical block(s). This clauses improvement of performance when the cluster
columns are the columns by which the tables are generally joined.
24
PARTITIONS
----Partitioning is transparent to existing applications and standard DML statements run against
partitioned tables.
However, an application can be programmed to take advantage of partitioning by using partition-
extended table or index names in DML.
Partitioning Method
- Range partitioning
- Hash partitioning
- List partitioning
Range Partitioning
Use range partitioning to map rows to partitions based on ranges of column values.
List Partitioning
Use list partitioning when you require explicit control over how rows map to partitions. You can
specify a list of discrete values for the partitioning column in the description for each partition.
Hash Partitioning
25
Hash partitioning provides a method of evenly distributing data across a
specified number of partitions. Rows are mapped into partitions based on a hash
value of the partitioning key.
It controls the physical placement of data across a fixed number of partitions and gives
you a highly tunable method of data placement.
Truncating Partitions
alter table emp345 truncate partition p5 ;
Merging Partitions
ALTER TABLE emp345 MERGE PARTITIONS p1 , p2 into PARTITION p6 ;
Moving a Partitions
ALTER TABLE emp345 MOVE PARTITION p4 tablespace tbs4 ;
LOCKING MECHANISM
Locks :
Locks are of two types,
1. Row Level Locks
2. Table Level Locks
Note: another user cannot manipulate comm&sal all the numbers, for the rest of the entities he
can do manipulation
26
note: another user cannot manipulate all the entities of the table
Note: only manipulations r not allowed but he can retrive values (select)of the table
--> Table Level Locks: These are further classified into three caregories...
-> Share Lock : This is a sharable lock, i.e., multiple users can implement this sharable lock
on a single table at the same time.
note: the 2nd user who didn`t lock the table which is locked by the first user should wait uptill
the 1st user`s end transaction.
when it ends 2nd user can use it for manipulations, but the 1stuser need not wait for the 2nd
user`s end transaction
E.g. Lock table emp in share mode;
-> Share Update Lock: Even though this lock fall under Table Level locks, but still is used to
lock records, to use this lock first we need to lock the required records using row level lock and
then implement this lock.
-> Exclusive Lock : When a user locks a table in Exclusive mode, no other user can access
that table except the user who has locked it in Exclusive mode.
Substitution Variables
- DEFINE command
For Integer
select empno,ename from emp where empno = &empno ;
DEFINE empno=7902 ;
select empno,ename,sal,deptno from emp where empno= &empno ;
27
select empno,ename,job,&&column_name from emp order by &column_name ;
insert into (select empno,ename,job,deptno from emp where deptno=20 with check option)
values (2222,'ddddd','MANAGER',30) ;
select rownum as rank, ename,sal from (select ename,sal from emp order by sal desc) where
rownum <= 3 ;
INSERT ALL
INTO sal_history values (empno,hiredate,sal)
INTO mgr_history values (empno,mgr,sal)
select empno,hiredate,sal,mgr from emp where empno > 1000 ;
INSERT ALL
WHEN SAL > 10000 then
INTO sal_history values (empno,hiredate,sal)
WHEN MGR > 200 THEN
INTO mgr_history values (empno,mgr,sal)
select empno,hiredate,sal,mgr from emp where empno > 1000 ;
28
Pivoting Insert
INSERT ALL
INTO sales_info values (empno,week_id,sales_mon)
INTO sales_info values (empno,week_id,sales_TUE)
INTO sales_info values (empno,week_id,sales_WED)
INTO sales_info values (empno,week_id,sales_THU)
INTO sales_info values (empno,week_id,sales_FRI)
PL/SQL
Introduction to PL/SQL
PL/SQL Architecture
Benefits of PL/SQL
- PL/SQL is portable.
- You can declare variable.
- You can program with procedural language control structures.
- PL/SQL can handle errors.
- Improved Performance
Benefits of Subprogram
1. Easy Maintenance
2. Improved data security and integrity.
3. Improved performance.
4. Improved code clarity.
DECLARE (Optional)
Variables, cursor, user-defined exception
29
Begin (Mandatory)
- SQL statements
- PL/SQL statements
Exception (Optional)
Actions to perform when errors occur
End;
:= (assign operator)
DECLARE
v_hiredate date;
v_deptno number(2) := 10 ;
Naming Rules
DECLARE
memp_id number(4):= 1000 ;
begin
select empno into mempno from emp where empno=1000;
end ;
- CHAR
- VARACHAR2
- LONG
- LONG RAW
- NUMBER
- BOOLEAN
Declare
V_job Varchar(10) ;
V_orderdate date := sysdate + 7 ;
v_valid BOOLEAN NOT NULL := TRUE ;
Using %TYPE
Using %ROWTYPE
The %ROWTYPE attribute provides a record type that represents a row in a table (or view). The
record can store an entire row of data selected from the table or fetched by a cursor (declared
later). In case, variables for the entire row of a table need to be declared, then instead of
declaring them individually, the attribute %type is used
EMP_ROW_VAR EMP%ROWTYPE:
Here, the variable EMP_ROW_VAR will be a composite variable, consisting of the column names
of the table as its members. To refer to a specifiec variable, sal SAL, the following syntax will be
used:
EMP_ROW_VAR.sal := 2000 ;
30
Using BIND Variables
Print g_salary
set serveroutput on ;
Commenting Code /* */
declare
V_ename emp.empno%type ;
V_sal emp.sal%type;
v_conat varchar2(30;
begin
v_conat := V_ename || V_sal ;
end ;
Nested Block
Declare
x number;
begin
Declare
Y Number;
Begin
.........
End ;
.......
end ;
31
Operators in PL/SQL
--Logical
--Arithmetic
--Concatenation
Same as SQL
------------------------
declare
mempno emp.empno%type ;
mename emp.ename%type ;
begin
select empno,ename into mempno,mename from emp where empno=7902;
dbms_output.Put_line('The sasasasasa');
end ;
- Insert
- delete
- Update
- Merge
begin
insert into dept1 (deptno,dname,loc) values (50,'EDP','America') ;
end;
declare
V_deptno emp.deptno%type := 50 ;
begin
delete from emp where deptno= v_deptno ;
end;
-------------------------------------------------------------------------
declare
v_deptid dept1.deptno%type := 50 ;
begin
delete from dept1 where deptno=v_deptid ;
dbms_output.put_line (sql%rowcount || 'Row deleted') ;
end ;
32
Conditional and Iterative Control
IF STATEMENTS
Syntax:
IF <condition1> then
<statement1>
elsif <condition1> then
<statement1>
else
<statement1>
end if;
Example :
if v_name='KING' then
v_job := 'President' ;
elsif v_name='JONES' then
v_job := 'Manager' ;
else
v_job := 'Clerk' ;
end if ;
--------------------------------------
declare
mempno emp.empno%type:=&empno ;
msal emp.sal%type;
a varchar2(100) ;
begin
select sal into msal from emp where empno=mempno;
if msal > 100 and msal <= 2000 then
a:='Salary is between 1000 and 2000';
elsif msal > 2000 and msal <= 3000 then
a:='Salary is between 2001 and 3000';
else
a:='Salary is greater than 3000' ;
end if ;
dbms_output.put_line(a) ;
end ;
Basic Loop
The syntax is;
LOOP
<Statement>
exit [loop-label] [WHEN Condition]
end loop ;
Example:
declare
i number:=1 ;
begin
33
loop
dbms_output.put_line(i) ;
i := i+1 ;
exit when i > 10 ;
end loop;
end ;
WHILE Loop
Example
declare
i number:= 1 ;
begin
while I < 11 loop
dbms_output.put_line(i) ;
i := i+1 ;
end loop;
end ;
FOR Loop
The Syntax is :
FOR <var> IN <lower>..<upper> LOOP
<Statement>
End loop
Example
declare
i number ;
begin
for i in 1..10 loop
dbms_output.put_line(i) ;
end loop;
end ;
declare
v_grade char(1) := upper( '&V_grade') ;
v_appraisal varchar2(30) ;
begin
v_appraisal :=
CASE v_grade
WHEN 'A' then 'Execllent'
WHEN 'B' then 'Very Good'
WHEN 'C' then 'Good'
else 'No Such Grade'
end;
dbms_output.put_line ('Grade: ' ||v_grade|| ' Appraisal ' ||v_appraisal) ;
end;
declare
v_grade char(1) := upper( '&V_grade') ;
34
v_appraisal varchar2(30) ;
begin
v_appraisal :=
CASE
WHEN v_grade ='A' then 'Execllent'
WHEN v_grade ='B' then 'Very Good'
WHEN v_grade = 'C' then 'Good'
else 'No Such Grade'
end;
dbms_output.put_line ('Grade: ' ||v_grade|| ' Appraisal ' ||v_appraisal) ;
end;
declare
x number;
y number;
z number;
begin
x:=&x;
y:=&y;
z:=x+y;
if z>=50 then
goto pqr;
else
dbms_output.put_line('Wellcome');
end if;
<<pqr>>
dbms_output.put_line('fjbfbfbb');
end;
Cursor
The Oracle Engine uses a work area for its internal processing in order to execute an SQL
statement. This work area is private to SQL’s operations and called a Cursor.
35
%ISOPEN - Evaluates TRUE if the Cursor Open
%NOTFOUND - Evaluates TRUE if the most resent fetch does not return a row
%FOUND - Evaluates TRUE if the most recent fetch return a row
%ROWCOUNT - Evaluates to the total number of rows returned so far.
Examples
declare
v_empno emp.empno%type;
v_sal emp.sal%type ;
v_ename emp.ename%type ;
cursor emp_cursor is select empno,ename,sal from emp ;
begin
Open emp_cursor ;
LOOP
fetch emp_cursor into v_empno,V_ename,v_sal ;
dbms_output.put_line('The Employee No: ' ||v_empno||' and name is ' ||v_ename|| ' The salary
is' ||v_sal);
exit WHEN emp_cursor%rowcount > 10 or emp_cursor%notFOUND;
End LOOP ;
end;
declare
v_empno emp.empno%type;
v_sal emp.sal%type ;
cursor emp_cursor is select empno,sal from emp;
begin
open emp_cursor;
for i in 1..10 loop
fetch emp_cursor into v_empno,v_sal;
declare
v_empno emp.empno%type;
v_sal emp.sal%type ;
cursor c1 is select empno,sal from emp;
begin
open c1;
for i in 1..10 loop
fetch c1 into v_empno,v_sal;
exit when c1%notfound;
dbms_output.put_line (v_empno||' '||v_sal);
end loop;
end;
----------------------------------------------------------------------------
declare
mename emp.ename%type ;
msal emp.sal%type ;
mjob emp.job%type;
36
mempno emp.empno%type;
cursor c1 is select empno,ename,job,sal from emp ;
begin
open c1;
loop
fetch c1 into mempno,mename,mjob,msal;
if msal < 2000 then
update emp set sal=msal*2 where empno=mempno;
dbms_output.put_line(mempno||' '||mename||' '||msal*2||' '||mjob) ;
elsif msal between 2000 and 4000 then
update emp set sal=msal*.5 where empno=mempno;
dbms_output.put_line(mempno||' '||mename||' '||msal*.5||' '||mjob) ;
elsif msal > 4000 then
update emp set sal=msal*.2 where empno=mempno;
dbms_output.put_line(mempno||' '||mename||' '||msal*.2||' '||mjob) ;
end if ;
exit when c1%notfound ;
end loop ;
close c1 ;
end ;
FOR LOOP
Declare
cursor c1 is select empno,ename,deptno from emp;
begin
for emp_record in c1 loop
if emp_record.deptno=20 then
dbms_output.put_line('Employee No ' ||emp_record.empno ||' Name is '||
emp_record.ename);
end if;
end loop;
end;
SQL%ISOPEN - Is always false because Oracle automatically close an Implicit cursor after
executing its SQL statement
SQL%NOTFOUND - Evaluates TRUE if the DML statement was not suceesful
%FOUND - Evaluates TRUE if the DML statement was suceesful
%ROWCOUNT – Returned to the total number of rows affected by an INSERT,UPDATE, DELETE
or single row SELECT
OPEN, FETCH, CLOSE : cannot be used to maipulating the implicit cursor SQL
-Pass parameter values to a cursor when the cursor is opened and the query is executed
-Open an explicit cursor several times with a different active set each time.
Syntax
CURSOR cursor_name (parameter name data type) is select statement
Begin
Open cursor_name (parameter values)
End ;
- Paremeter data types are the same as scalar data type but do not give them sizes.
Example:
37
declare
mename emp.ename%type;
mempno emp.empno%type;
cursor emp_cursor (mdeptno number, mjob varchar2) is select empno,ename from emp where
deptno=mdeptno and job=mjob;
begin
for emp_record in emp_cursor (30,'SALESMAN')
loop
fetch emp_cursor into mempno,mename ;
dbms_output.put_line(mename||' '||mempno);
end loop ;
end;
---------------------------------
Syntax
Cursor emp_cur is select empno, ename, sal from EMP where deprno in (select deptno from dept)
Declare
Type ref_c is ref cursor return emp%rowtype;
C1 ref_c ;
Vrec emp%rowtype;
Vdno number(2) := &vdno ;
Begin
If vdno =10 then
Open c1 for select * from emp where job=’MANAGER’ ;
Elsif vdno = 20 then
Open c1 for select * from emp where job=’SALESMAN’ ;
Else
Open c1 for select * from emp where job=’CLERK’ ;
End if;
Loop
Fetch c1 into vrec ;
Exit when c1%notfound;
dbms_output.put_line(vrec.empno||’ ‘||vrec.ename) ;
38
end loop;
close c1;
end;
declare
v_empno emp.empno%type;
v_sal emp.sal%type ;
v_ename emp.ename%type ;
mdname dept.dname%type;
type r is ref cursor;
emp_cursor r;
begin
Open emp_cursor for select empno,ename,sal from emp ;
LOOP
fetch emp_cursor into v_empno,V_ename,v_sal ;
dbms_output.put_line('The Employee No: ' ||v_empno||' and name is ' ||v_ename|| ' The salary
is ' ||v_sal);
exit WHEN emp_cursor%rowcount > 10 or emp_cursor%notFOUND;
End LOOP ;
Open emp_cursor for select dname from dept ;
LOOP
fetch emp_cursor into mdname;
dbms_output.put_line('The dept name is ' ||mdname);
exit WHEN emp_cursor%rowcount > 10 or emp_cursor%notFOUND;
End LOOP ;
end;
EXCEPTION HANDLING
An Exception is an identifier in PL/SQL that is raised during execution that terminates main
body of action.
declare
x emp.sal%type;
y emp.deptno%type:=&deptno;
begin
select sal into x from emp where deptno=y;
dbms_output.put_line('sal of empno is='||x);
dbms_output.put_line('wellcome');
exception
when too_many_rows then
dbms_output.put_line('more then one error selected');
when others then
dbms_output.put_line('no record found');
end;
RAISE_APPLICATION_ERROR Procedure:
Is used to communicate a predefined exception interactively by defining a non standard error
code and error message.
1) declare
v_empno number(4):=&empno ;
begin
delete from emp where empno=v_empno ;
if SQL%NOTFOUND Then
RAISE_APPLICATION_ERROR (-20202,'wrong empno') ;
end if ;
end ;
2)
declare
x emp.sal%type;
y emp.empno%type:=&empno;
sal_exc exception ;
begin
select sal into x from emp where empno=y;
if x > 3000 then
raise sal_exc;
else
dbms_output.put_line('sal of empno is='||x);
dbms_output.put_line('wellcome');
end if;
exception
when sal_exc then
raise_application_error(-20001,'Salary is greater than 3000') ;
41
when others then
dbms_output.put_line('no data found');
end;
Non-Predefined Exception
The Pragma action word is a call to a pre-compiler, which immediately binds the numbered
exception handler to a name when encountered.
The function Exception_init() takes two parameters the first is the user defined exception name
the second of the oracle engine’s exception number. These lines will be included in the Declare
section of the PL/SQL block.
declare
e_emp_remaining EXCEPTION ;
PRAGMA EXCEPTION_INIT(e_emp_remaining,-2292) ;
begin
delete from dept1 where deptno=10 ;
commit;
exception
when e_emp_remaining then
dbms_output.put_line('canot remove dept ');
end;
------------------------------------
declare
z_divide EXCEPTION ;
PRAGMA EXCEPTION_INIT(z_divide,-1476) ;
x number:= 20 ;
y number:= 0 ;
z number;
begin
z:=x/y;
exception
when z_divide then
dbms_output.put_line('Number is divided zero ');
end;
------------------------------------
declare
t_row_many EXCEPTION ;
PRAGMA EXCEPTION_INIT(t_row_many,-1422) ;
begin
select sal into msal from emp where deptno=20;
exception
when t_row_many then
dbms_output.put_line('Too Many Rows returned ');
end;
------------------------------------
42
declare
t_row_many EXCEPTION ;
PRAGMA EXCEPTION_INIT(t_row_many,-1422) ;
msal emp.sal%type;
begin
select sal into msal from emp where deptno=20;
exception
when t_row_many then
dbms_output.put_line('Too Many Rows returned ');
end;
When an Exception occurs, we can identify the associated error code and error message by using
two functions.
SQLCODE returns number of the Oracle error for internal exception. We can pass an error
number to SQLERRM, which then return the message associated with the error number.
Declare
Err_num number ;
Err_msg Varchar2(100) ;
Begin
---------
Exception
Err_num = SQLCODE ;
Err_msg := sunstr(SQLERRM,100) ;
Insert into errors values (err_num,err_msg) ;
End ;
PROCEDURES
OUT Parameter Passes a value from the procedure to the calling environment
IN OUT Parameter Passes a value from the calling environment into the procedure and a
Possibly different value from the procedure back to the calling environment
using the same parameter.
43
IN Parameter
1)
create or replace procedure Add_proc
(a in number, b in number)
is
c number;
begin
c:= a+b ;
dbms_output.put_line('The values of c is' ||c);
end ;
2)
create or replace procedure emp_proc
(mempno in number)
is
begin
update emp set sal=sal*2 where empno=mempno;
end ;
OUT Parameter
print A
print B
print C
IN OUT Parameter
2)
create or replace procedure view_proc_emp
(mdeptno in number)
is
vename emp.ename%type;
vsal emp.sal%type ;
cursor emp_cursor is select ename,sal from emp where deptno=mdeptno ;
begin
open emp_cursor ;
loop
fetch emp_cursor into vename,vsal;
dbms_output.put_line('The employee name is' ||vename||' Salary is ' || vsal) ;
exit when emp_cursor%notfound;
end loop;
close emp_cursor ;
view_proc_dept(mdeptno);
end ;
1)
create or replace procedure view_exec_emp
(mempno in number)
is
vename emp.ename%type;
vsal emp.sal%type ;
begin
select ename,sal into vename,vsal from emp where empno=mempno;
dbms_output.put_line('The employee name is' ||vename||' Salary is ' || vsal) ;
EXCEPTION
WHEN no_data_found then
dbms_output.put_line('No such Employee number exist');
end ;
2)
create or replace procedure emp_proc
(mdeptno emp.deptno%type )
as
cursor c1 is select ename,sal,job from emp where deptno=mdeptno;
mename emp.ename%type;
msal emp.sal%type ;
mjob emp.job%type;
check_emp exception ;
begin
open c1;
45
loop
fetch c1 into mename,msal,mjob ;
if c1%rowcount < 1 then
raise check_emp ;
else
dbms_output.put_line('the employee name is '||mename||' salary is '||msal||' '||mjob) ;
end if ;
exit when c1%notfound ;
end loop ;
exception
when check_emp then
dbms_output.put_line(' the deptno not found') ;
end;
Dropping Procedure
Functions
RETURN datatype
AS|IS
PL/SQL BLOCK
1)
create or replace function tax (p_value in number)
return number is
Begin
return (p_value * 2);
end ;
2)
create or replace function total ( a number , b number )
return number
46
is
begin
return (a+b) ;
end ;
3)
Create or replace function get_sal
(mempid in emp.empno%type)
return number
IS
v_sal number;
BEGIN
select sal into v_sal from emp where empno=mempid ;
return v_sal;
end;
execution Method - 1
--------------------
select get_sal(7900) from dual ;
execution Method - 2
--------------------
Variable g_sal number
execute :g_sal := get_sal(7900)
Print :g_sal
--------------------------------
47
x number;
begin
select sal into v_sal from emp where empno=mempid ;
x := v_sal*.5 ;
return x ;
end ;
---------------------------------------------------------
create or replace function func_name
(mempno in number)
return number
is
msal emp.sal%type;
begin
select sal into msal from emp where empno=mempno ;
if msal > 0 then
return msal ;
else
return msal*2 ;
end if ;
end ;
-----------------------------------------------------------------------------------
create or replace function func_name
(mempno in number)
return boolean
is
msal emp.sal%type;
begin
select sal into msal from emp where empno=mempno ;
if msal > 0 then
return (true) ;
else
return (false) ;
end if ;
end ;
----------------
begin
if func_name(7902) then
dbms_output.put_line('right') ;
else
dbms_output.put_line('wrong') ;
end if ;
end;
-----------------------------------------------------------------------------------
48
-----------------------------------------------------------------------------------
Using Exception
Dropping a Function
Desc user_objects ;
select * from user_objects ;
desc user_source
select text from user_source where NAME='FUNC_NAME' ;
desc user_errors
select * from user_errors ;
Packages: A Package is an Oracle object, which holds other objects within it. Objects
commonly held within a package are procedures, functions, variables, constants, cursors and
exceptions.
- Specification
- Body
A Package Specification declares the types (variable of the Record type), memory variables,
constants, exceptions, cursors and subprograms that are available for use.
A Package body fully defines cursor, functions and procedure and thus implements the
specification.
49
Why Use Package
Packages offer the following advantages:
1) Packages enable the organization applications into efficient modules. Each package is easily
understood, and the interfaces between packages are simple, clear and well defined.
3) A Package's public variables and cursor persist for the duration of the session. Therefore all
cursors and procedures that execute in the environment can store them.
5) Package improves performance by loading multiple objects into memory at once. Therefore,
subsequent calls to related sub programs in the package require no I/O.
6) Package promotes code reuse through the use of libaries that contain shared procedures and
functions. Thereby reducing redundant coding.
Syntax
CREATE [Or Replace] PACKAGE package_name
IS | AS
public type and item declarations
subprogram specifications
End package_name;
1)
create or replace package emp_proc as
Procedure emp_pr (mempno number) ;
Procedure dept_pr (mdeptno number) ;
end;
50
end;
declare
begin
dbms_output.put('the emp ') ;
emp_proc.emp_pr(7369) ;
dbms_output.put('the dept ') ;
emp_proc.dept_pr(20) ;
END;
2)
exec p2.pro(45,3);
declare
x number ;
begin
x:=p2.f1(10);
dbms_output.put_line(x);
end;
1)
2)
create or replace package pack_cur
IS
cursor c1 is select empno from emp ;
cursor c2 is select dname from dept ;
procedure proc_emp ;
procedure proc_dept;
end ;
52
Declaring a Bodiless Package
A Package is an Oracle object that can hold a number of other objects like procedure and
functions. More than one procedure and function with the same name but with different
parameters can be defined within a package or within a PL/SQL declaration block.
Multiple procedures that are declared with the same name are called Overloaded Procedures.
Similarly, multiple functions that are declared with the same name are called Overloaded
Functions.
1)
create or replace package p1
as
function f1(x number) return number;
function f1(x number,y number) return number;
end;
2)
create or replace package p1
as
function f1(x number) return boolean;
function f1(x number,y number) return boolean;
end;
declare
x boolean;
begin
if p1.f1(10) then
dbms_output.put_line('true');
end if;
end;
54
declare
x boolean;
begin
if p1.f1(10) then
dbms_output.put_line('true');
else
dbms_output.put_line('false') ;
end if ;
end ;
declare
x boolean;
begin
if p1.f1(10,200) then
dbms_output.put_line('true');
end if;
end;
---------------------------------------------------------------------------------------------------------
create or replace package pack_over
as
procedure emp_proc (mempno number) ;
procedure emp_proc (mempno number, mdeptno number) ;
end ;
--------------------------------------------------------------
Trigger
A Trigger:
- Is a PL/SQL block or a PL/SQL procedure associated with a table, view, schema or the
database.
- Trigger Timing
- for table: BEFORE, AFTER
- for View: INSERT, UPDATE or DELETE
- Triggering Event: On table, View
- Trigger Type: Row or Statement
- WHEN Clause: Restricting condition
- Trigger body: PL/SQL block
BEFORE: Execute the trigger body before the triggering DML event on a table.
AFTER: Execute the trigger body after the triggering DML event on a table.
INSTEAD OF: Execute the trigger body instead of the triggering statement. This is used for views
that are not otherwise modifiable.
Triggering user events: The triggering event is an Insert, Update & Delete statement on a table.
Trigger type
Statements: The trigger body executes once for the triggering events. This is the default. A
statement trigger fires once, even if no rows are affected at all.
Row: The trigger body executes once for each row affected by the triggering events. A row trigger
is not executed if the triggering events affect no rows.
Firing Sequence
----------------
----> BEFORE statement trigger
Empno Ename Deptno
----- ------ ------ -----> BEFORE row trigger
7902 SMITH 20
7876 JONES 10 -----> AFTER row trigger
7878 SURESH 30
------------------------------------------
------------------------------------------------------------------------
create or replace trigger res_salary
before delete
on emp1
begin
RAISE_APPLICATION_ERROR (-20202,'Employee cannot delete');
end;
58
Trigger (ROW LEVEL)(Using :old qualifier)
INSTEAD OF Triggers
Use INSTEAD OF Triggers to modify data in which the DML statement has been issued against
an inherently non-updateable view. These triggers are called INSTEAD OF triggers.
----------------------------------------------
59
create table new_depts as select e.deptno,e.dname, sum(d.sal) tot_dept_sal
from emp d, dept e where d.deptno=e.deptno group by e.deptno,e.dname ;
2)
create table NEW_EMP as select empno,ename,deptno from emp ;
MANAGING TRIGGERS
60
Creating Database Triggers
- Logging on or off
These Trigger will be fired implicitely whenever user performs any DDL operations like create,
alter or dropping an object
The Syntax is :
Create or replace trigger <triggername)
Before|after DDL statement on schema
PL/SQL Block
Example
Before create
Create or replace trigger ddl_trigger
Before create on schema
begin
Raise_application_error(-20222,’U cannot create a table’)
end;
After create
Create or replace trigger ddl_trigger
after create on schema
begin
insert into audit_objects_use values (user||’ has created an object at’||
to_char(sysdate,’dd/mm/yyyy hh24:mi:ss’) ;
end;
61
INSERT INTO LOG_TRIG_TABLE (USER_ID,LOG_DATE, ACTION)
VALUES (user,sysdate,'Logging Off') ;
end;
- It is a DB Package
- Used for
- to create flat file
- to load data into Oracle DB from flat file
- It do validation also
FOPEN
FCLOSE
GET_LINE
NEW_LINE
PUT
Datatype = File_type
The DBMS_SQL package is used to write dynamic SQL in stored procedures and to parse DDL
statements. Some of the procedures and functions of the package includes:
- OPEN_CURSOR
- PARSE
- BIND_VARIABLE
- EXECUTE
- FETCH_ROWS
- CLOSE_CURSOR
63
p_rows_del := DBMS_sql.EXECUTE(cursor_name) ;
DBMS_SQL.close_cursor(cursor_name) ;
end;
SQL> print a
- Submitting jobs
- Executing jobs
- Changing execution parameters of jobs
- Remove jobs
- Suspending Jobs
COALESCE
You can also use COALESCE as a variety of the CASE expression. For example,
COALESCE (expr1, expr2)
is equivalent to:
CASE WHEN IS expr1 NOT NULL THEN expr1 ELSE expr2 END
Similarly,
is equivalent to:
CURRENT_DATE
Purpose
CURRENT_DATE returns the current date in the session time zone, in a value in the Gregorian
64
calendar of datatype DATE.
Examples
The following example illustrates that CURRENT_DATE is sensitive to the session time zone:
SESSIONTIMEZONE CURRENT_DATE
--------------- --------------------
-05:00 29-MAY-2000 13:14:03
SESSIONTIMEZONE CURRENT_DATE
--------------- --------------------
-08:00 29-MAY-2000 10:14:33
CURRENT_TIMESTAMP
Purpose
CURRENT_TIMESTAMP returns the current date and time in the session time zone, in a value of
datatype TIMESTAMP WITH TIME ZONE. The time zone offset reflects the current local time of
the SQL session. If you omit precision, then the default is 6. The difference between this function
and LOCALTIMESTAMP is that CURRENT_TIMESTAMP returns a TIMESTAMP WITH TIME ZONE
value while LOCALTIMESTAMP returns a TIMESTAMP value.
In the optional argument, precision specifies the fractional second precision of the time value
returned.
Examples
The following example illustrates that CURRENT_TIMESTAMP is sensitive to the session time
zone:
SESSIONTIMEZONE CURRENT_TIMESTAMP
--------------- ---------------------------------------------------
-05:00 04-APR-00 01.17.56.917550 PM -05:00
SESSIONTIMEZONE CURRENT_TIMESTAMP
--------------- ----------------------------------------------------
-08:00 04-APR-00 10.18.21.366065 AM -08:00
If you use the CURRENT_TIMESTAMP with a format mask, take care that the format mask
matches the
value returned by the function. For example, consider the following table:
65
CREATE TABLE current_test (col1 TIMESTAMP WITH TIME ZONE);
The following statement fails because the mask does not include the TIME ZONE portion of the
type returned by the function:
The following statement uses the correct format mask to match the return type of
CURRENT_TIMESTAMP:
EXTRACT (DATETIME)
Purpose
EXTRACT extracts and returns the value of a specified datetime field from a datetime or interval
value expression. When you extract a TIMEZONE_REGION or TIMEZONE_ABBR (abbreviation),
the value returned is a string containing the appropriate time zone name or abbreviation. When
you extract any of the other values, the value returned is in the Gregorian calendar. When
extracting from a datetime with a time zone value, the value returned is in UTC. For a listing of
time zone names and their corresponding abbreviations, query the V$TIMEZONE_NAMES
dynamic performance view.
EXTRACT(YEARFROMDATE'1998-03-07')
---------------------------------
1998
The following example selects from the sample table hr.employees all employees who were hired
after 1998:
FIRST
Purpose
FIRST and LAST are very similar functions. Both are aggregate and analytic functions that
operate on a set of values from a set of rows that rank as the FIRST or LAST with respect
to a given sorting specification. If only one row ranks as FIRST or LAST, the aggregate
operates on the set with only one element.
This function takes as an argument any numeric datatype or any nonnumeric datatype that can
be implicitly converted to a numeric datatype. The function returns the same datatype as the
numeric datatype of the argument.
66
When you need a value from the first or last row of a sorted group, but the needed value is
not the sort key, the FIRST and LAST functions eliminate the need for self joins or views
and enable better performance.
select deptno,
min(sal) KEEP (DENSE_RANK FIRST ORDER BY comm) "Worst",
MAX(sal) KEEP (DENSE_RANK LAST ORDER BY comm) "Best"
from emp
group by deptno ;
NULLIF
Purpose
NULLIF compares expr1 and expr2. If they are equal, then the function returns null. If they
are not equal, then the function returns expr1. You cannot specify the literal NULL for expr1.
If both arguments are numeric datatypes, then Oracle Database determines the argument with
the higher numeric precedence, implicitly converts the other argument to that datatype,
and returns that datatype. If the arguments are not numeric, then they must be of the same
datatype, or Oracle returns an error.
Examples
The following example selects those employees from the sample schema hr who have changed
jobs
since they were hired, as indicated by a job_id in the job_history table different from the
current job_id in the employees table:
67
Implementing Object Techniques
Object Technology:
• Object Technology is another step forward in the software enginnering life cycle that
allows us to:
- Model real Thing
- Represent real thing as objects
• Object Technology is a method of managing complexity so that we can develop solutions
that simulate real-world problems.
• Minimizing cost through reusibility
Oracle provides full support for all three different implementation – Relational, Object-
Relational, Object- Oriented Relational.
Objects reduce complexity by giving an intuitive way of representing complex data and its
relations.
Besides simplifying the interaction with data, objects may help in other ways. Examples of
benefits that come from using OO features are:
Object reuse: - If OO code is written; the chance of reusing previously written code modules is
increased. Similarly, if OO database objects are created the chances that these database objects
will be reused in increased.
Standard adherence:- If database objects are built using standards, then the chances they will
be used increase exponentially. If multiple applications or tables use the same set of database
objects, then a de facto standard for application of tables is being created.
OBJECT TYPES
Oracle supports many different types of objects. In the following sections, major
object types are described.
Abstract Data type
Abstract Data type is a datatype that consists of one or more subtypes. Rather that being
constrained to the standard Oracle data type of NUMBER, DATE, and VARCHAR2, the abstract
data type can more accurately describe data.
Creation of an Object
An abstract data type can be used to create an Object Table. In an object table, the columns of
the table map to the columns of an abstract datatype.
68
CREATE TABLE customer
(customer_id number, person person_ty)
Nested Tables
A nested table is a table within a table. A nested is a collection of rows, represented as a column
within the main table. For each record within the main table, the nested table as a column. In
one sense, it’s a way of storing a one-to-many relationship within one table.
Varying Arrays
A varying array is a set if objects, each with the same data type. The size of the array is limited
when it is created.
When a table is created with a varying array, the array is a nested table a limited set of rows
Varying Arrays, also known as VARRAYS, allows storing repeating attributes in tables.
References
Nested tables and Varying Arrays are embedded objects. They are physically embedded within
another object. Another type of object, called referenced objects, are Physically separated from
the objects that refer to them. References (also known as REFs) are essentially pointers to row
objects. A row object is different from a column object. An example of a column object would be a
varying array, it is an object that is treated as a column in a table. A row object, on the other
hand, always represents a row.
References are typically among the last OO features implemented when migrating a relational
database to an object-relational or pure OO one.
Object views
Object views allow adding OO concepts on top of existing relational tables. For example, an
abstract data type can be created based on an existing table definition. Thus, object views give
the benefits of relational table storage and OO structures. Object views allow the development of
OO features within a relational database, a kind of bridge between the relational and OO worlds.
VARIABLE ARRAYS
A varying array allows the storing of repeated attributes of a record in a single row. Varying
arrays are collectors that allow repetition of only those column values that change, potentially
saving storage space. Varying arrays can be used to accurately represent one –to –many
relationships where the maximum number of elements on the many side of the relationship is
known and where the order of these elements is important.
This statement creates a varray type called company_address_typ, which can hold a maximum of
3 elements of data type varchar2(1000), i.e. 3 entries per record, each storing address
information for the company.
Now that the varying array company_address_ty is created, this can be used as a part of the
creation of either a table or an abstract datatype
ORCLE stores the varying array data internally using the RAW datatype.
Reference object
The referencing object (REFs data type) is something that is new to ORACLE 8i. This data type
acts as a pointer to an object. A REF can also be used in a manner similar to a foreign key in a
RDBMS. A REF is used primarily to store an object identifier, and to allow the user to select that
object.
REF’s establish relationship between two-object tables, much the same way as a primary-
key/foreign-key relationship in relational tables. Relational tables however, have difficulty, if
more than one table is needed in a primary-key/foreign-key relationship related to a single table.
For example, an address table, that stores addresses from several entities. The use of REFs
eliminates this problem, because an unscoped REF can refer to any accessible object table.
A scope clause in a definition forces a set of REFs for a given column to be confined to a single
object table. There can be only one REF clause for a given REF column. REF scope can be set at
either the column or table level.
REF values can be stored with or without a ROWID. Storing a REF with a ROWID seeds de-
referencing operation, but takes more space. If with ROWID is not specified with the REF clause,
the default is to not store ROWIDs with the REF values. SCOPE clauses prevent dangling
references, as they will not allow REF values unless the corresponding entries in the SCOPE
table is present.
REF columns can be added to nested tables with the ALTER TABLE command.
A call to a REF returns the OID of the object instance. An OID is a 128 bytes base –64 number,
which is not very useful except as handle to the object instance. To get the value stored in the
instance that is referred to by a REF, the DEREF routine is used. DEREF returns values in the
object instance referenced by a specific REF value.
70
Some advance features in Oracle 9i
MATERIALIZED VIEW
A materialized view is a database object that contains the results of a query. The FROM clause
of the query can name tables, views, and other materialized views. Collectively these objects
are called master tables (a replication term) or detail tables (a data warehousing term).
This reference uses "master tables" for consistency. The databases containing the master
tables are called the master databases
FLASHBACK TABLE
Purpose
Use the FLASHBACK TABLE statement to restore an earlier state of a table in the event of
human or application error. The time in the past to which the table can be flashed back is
dependent on the amount of undo data in the system. Also, Oracle Database cannot restore a
table to an earlier state across any DDL operations that change the structure of the table.
Oracle Utilities
Export
• A backup utility provided by Oracle
• Writes data from an Oracle database into Oracle binary-format files
• Exported data can only be read by the “Import” utility
• A User must have connect or DBA privilege to export table
• Exprt Modes:
o Table: The names of the tables to be exported need to be specified
o User: All objects belonging to the user are exported
o Database: All database objects are exported
• The command used is : exp
Import
• Is used for importing data exported using the exp command into the Oracle database
Importing tables
C:\> Imp username/passward file=filename.dmp log=filename.log Tables=(tablename,tablename)
71
Importing User
C:\> Imp system/manager file=filename.dmp log=filename.log fromuser = username
touser=username
Sql Loader
• This tool is used to move data from a Non-Oracle standard source into the Oracle
Database
• Load data into multiple datafiles
Oracle Architecture
In Every Oracle Server consists of an Oracle Instance and Database .
An Oracle Instance is the combination of System Global Area(SGA) and the Background Process.
Mandatory are
1) Process Monitor (PMON)
2) System Monitor (SMON)
3) Database Writer (DBWR)
4) Log Writer (LGWR)
72
5) Checkpoint (CKPT)
Optional are
1) Oracle Parallel Query Option (OPQO)
2) Multi DBWR
3) Archiver (ARCH)
4) Recoverer (Reco)
Data file:
- The actual data stores in the data file. The file size should be in MBs or GBs or may be TBs.
- One data file belongs only one Tablespace.
Control File:
It Stores the crushial information about the database like
- No of data files
- Name of each data files
- Location of each data files
- Database original creation date
Parameter File:
While datatabase is starting, first it reads from the parameter file, what parameter u have set in
the database. There must be atleast some parameter require to start.
Such as :
Database Name
Control File Location
Whether Rollback Segmnet or Undo Management
Background/User/Core Dump Location etc..
Password File:
Password file is required to connect database remotely from one serever to another server.
The Shared System Global Area (SGA) contains user data and control information for a single
Oracle Instance. Its contents is visible/accessible to several user applications and system
processes.
This area saves the re-reading of data from the Dictionary Table on a hard disk referenced while
parsing SQL statements. It contains information such as segment information, security and
access privileges, and available free storage space. It contains information such as user account
data, datafile names, segment names, extent locations, table descriptions, and Privileges.
Library Cache
The Library Cache contains both shared and private SQL areas. The v$librarycache view lists
performance information for each type of object in the library cache.
A private SQL area is created for each transaction initiated. It contains session-specific
information, such as bind variables, environment and session parameters, runtime stacks and
buffers, and so on. Each private area is deallocated after the cursor to the session is closed. The
number of private SQL areas a user session can have open at one time is limited by the value of
the OPEN_CURSORS init.ora parameter.
Within the private SQL area of the library cache, the persistent area contains information that is
valid and applicable through multiple executions of the SQL statement. The runtime area
contains data that is used only while the SQL statement is being executed.
To improver Oracle performance, Oracle uses a Shared SQL area to save in cache the
intermediate results from SQL commands previously returned. So before performing a hard disk
operation, Oracle can service identical requests simply by retrieving them from its cached
memory for reuse. Specifically, the shared area contains the parse tree and execution path for
SQL statements. It also contains headers of PL/SQL packages and procedures that have been
executed.
The data block buffer stores the most recently queried data from the database. This is done for
efficiency -- to avoid time-consuming hard disk operations. Its size is controlled by the variable
DB_BLOCK_BUFFERS parameter, which has a value calculated from the size of about 1 to 2
percent of the database. This space is managed by latching and writing the Least Recently Used
(LRU) block to hard disk.
74
The v$sqlarea view displays the text of SQL statements in the shared SQL area, plus the number
of users accessing the statements, disk blocks and memory blocks accessed while executing the
statement, and other information.
The redo log buffer is used to store redo information in memory before it is flushed to the Online
Redo Log Files. Its size is initialized according to the LOG_BUFFER (bytes) parameter. The
number of redo log space requests can be monitored using the v$sysstat view.
Large Pool
Introduced with Oracle 8 to store user session global area infor and for parallel
processing/recovery.
The System monitor performs automatic crash recovery on the Oracle instance in the
event it fails. If the command shutdown abort is issued by the user, Oracle doesn't have
time to write modified database changes from the System Global Area (SGA) down to disk.
It wakes itself up routinely to clean up free space in datafiles (much like a defragmenter
for hard drives). It looks for free spaces and organizes them into contiguous areas.
The Process monitor performs recovery (such as releasing locks failed processes held on
resources). PMON analyzes user processes that access the database, performs "garbage
collection", and restarts failed processes in the database. It releases locks held by
processes which failed before they released memory allocations.
The Database Writer (DBWR) writes and retrieves blocks from datafiles through the buffer
cache. Some suggest using the DB_WRITERS parameter to define as many DBWR
processes as there are physical disks used to store data files.
The Log Writer writes and retrieves its blocks from datafiles through the Redo Log
Buffer.
75
5. Checkpoint Process (CKPT)
The checkpoint (CKPT) process frees up limited memory space and ensures instance
recovery. It is a background process that monitors the number of dirty buffers that have
not been written to disk. Depending on the LOG_CHECKPOINT_INTERVAL parameter, it
also gives the DBWR a wakeup call to write dirty buffer to disk. At a specified time, it
updates all the data and control files with the new log file control number. This process is
optionally enabled if parameter CHECKPOINT_PROCESS contains a TRUE value.
Redo log files are achived to tape or other media by the ARCH background process. In Oracle 8i,
the DBWR_IO_SLAVES parameter defines the number of I/O slaves to improve performance. The
v$archive view provides information on the archived logs written by ARCn (ARCH pre Oracle8i).
Alert Logs
Database start-ups and other commands and responses to commands to a database are stored
in an Alert Log.
User trace Database trace start-up and other commands and responses to commands to a
database are stored in an Alert Log.
The full online redo logs are copied to the archived redo log files by this process. If the database
is operating in archivelog mode AND the ARCHIVE_LOG_START parameter in the init.ora file is
not set to TRUE, the database will hang.
76