Download - Free Documents

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Relational algebra wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Database wikipedia , lookup

Oracle Database wikipedia , lookup

Ingres (database) wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Functional Database Model wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Clusterpoint wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Join (SQL) wikipedia , lookup

SQL wikipedia , lookup

Relational model wikipedia , lookup

PL/SQL wikipedia , lookup

Database model wikipedia , lookup

Transcript
i
SL
Contents
Introduction To DBMS Oracle Data Type Structure Query Language SQL Sql Plus Editing
Commands Sql Plus File Commands Data Retrieval/Query Language Drl/Dql Select Data
Manipulation Language DML Insert, Update, Delete, Merge Data Dictionary Language DDL
Create, Alter, Drop, Truncate, Rename Data Control Language DCL Grant, Revoke
Transaction Control Language TCL Commit, Rollback, Savepint Oracle Functions Group By
Clause Integrity Constraints Joins Sub Queries Working With Database Objects Views
Sequences Inedexes Synonyms Cluster Partitions Locking Mechanism More Commands In
Oracle i Pl/Sql Cursor Exception Handling Procedures Functions PACKAGE And PACKAGE
BODY Trigger File Input/Output I/O UtlFile Oracle Supplied Packages New SQL Function In
Oracle i Implementing Object Techniques Using Lobs Some Advance Fetures In Oracle i
Oracle Utilities Export Import Sql Loader Oracle Architecture
Page No
Introduction to DBMS Database A Database is a collection of interrelated data from which
some information can be extract. Database Management System DBMS Database
Management Systems organize and structure data so that it can be retrieved and
manipulating by users and application programmer. Database Model The data structures and
access techniques provided by a particular DBMS are called as Data Model. Hierarchical
Network Relational Hierarchical data model 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. Every child has one parent. You
can see only one record at a time. Retrieving the data in a Hierarchical database thus
required navigating through the records, Moving up, down, sideways one record at a time.
Example Windows Explorer Developed By IBM Named as Information Management System
IMS in The Drawback of Hierarchical data model It cannot handle a large data Its not support
many to many to relation Network data model The simple structure of a Hierarchical
database became a disadvantage when the data had a more complex structure. In an
orderprocessing 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. The Drawback of Network
data model Changing the database structure typically required rebuilding the entire
database. Relational Model Data is organized in terms of rows and columns in a table
knowns as relations The position of a row in a table is of no importance. The intersection of
row and column must give a single value and not a set of values.
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 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.
The Rules for an RDBMS Codd s Rule
Rule The information Rule All Information is explicitly and logically represented in exactly one
way i.e by data values in tables. Rule The rule of guaranteed access Every item of data must
be logically addressable by resorting to a combination of a Table name, Primary key and
column name. Rule The systematic treatment of null value This rule states that support for
null values must be consistent throughout the DBMS, and independent of the data type of the
field. Rule The Database Description Rule A description of the database is held and
maintained using the same logical structures used to define the data. This allows users to
query such information in the same way and using the same language, as they would do for
any other data in the database. Rule Comprehensive sublanguage Rule There must be at
least one language whose statements can be expressed as character strings confirming to
some welldefined syntax, which is comprehensive in supporting the following Data definition,
view Definition, Data Manipulation Integrity Constraints Authorization Transaction Boundaries
All the above topics are manageable through Structural Query Language SQL statement.
Rule The viewupdating Rule All views that are theoretically updateable are also updated by
the system. A view is a table is nonexistent in its own right, but instead derived from one or
more base tables. Rule The High Level Insert, Update and Delete Rule The capability to
handling a base relation, or infact a derived relation, as a single operand must hold good for
all retrieve, update, delete and insert activity. 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. Rule The physical independence Rule
Rule Integrity independence Rule All integrity constraint defined for a database must be
definable in the language and stored in the database as data in tables.The user access to
the database remains logically consistent even if the storage representation is changed./ lt.
setatatime. Rule NonSubversion Rule If an RDBMS supports a lower level language that
permits for example. / Degree of Relationship . / Many to one gtgt. then this language must
not be able to bypass any integrity rules or constraints defined in the higher level./ ltlt. The
following integrity rules should apply every relational database Entity Integrity No component
of a primary key can have missing values or null values. relational language. Entity
Relationship Diagram ER Diagram logical database design through the papers One to One
gt./ lt. that are theoretically permitted. Referential Integrity For each distinct foreign key value
there must exist a matching primary key value in the same domain. are made to the base
tables. Rule The logical data independence Rule Application programs and terminal activities
must remain logically unimpaired whenever information preserving changes of any kind. Rule
Distribution Rule A RDBMS must have distribution independence. rowatatime processing. /
Many to Many gtgt./ ltlt. Application running on a nondistributed database must remain
logically unimpaired if that data becomes distributed in the context of a distributed relational
database. An RDBMS product has to satisfy at least six of the rules of Codd to be accepted
as full fledged RDBMS. / One to many gt.
many Teacher Many to one M . .Create separate tables for each group of related data and
identity each row with a unique column Primary Key Second Normal Form NF further
addresses the concept of removing duplicative data .One to one. Primary key In a well. an
OORDBMS is oriented towards operations on single objects. concurrencey control and
recovery.Removes columns that are not dependant upon the primary key.Remove subsets of
data that apply to multiple rows of a table and place them in separate rows. An OORDBMS
permits these objects to be shared among different applications by provididng necessary
DBMS functions such as indexing. each table possessing a set of one or more columns.
RDBMSs are very inefficient in their performance with single objects. Third Normal Form NF
goes one large step further .oriented databse thus stores persistent objects permanaetly on
secondary storage. Both of these are worthy goals as they reduce the amount of space a
database consumes and ensure that data is logically stored. . There are two goals of
Normalization Process eliminate redundant data for example.Many Courses . It tries to
collate the persistence of a DBMS with the expressiveness of an objectoriented programming
language.A relation is in BCNF if and only if determinant is a candidate key. Finally Forth
Normal Form NF. Morever. An Object. Relational Database Management System RDBMS A
Relational Database Management System RDBMS is an information system that presents
information as rows contained in a collection of tables. ObjectOriented Relational Database
Management System OORDBMS An ObjectOriented Relational Database Management
System OORDBMS integrates a DBMS with the concepts of objectoriented
programming.One HOD .designed relational database every table has some column or
combination of columns whose values uniquely identify each row in the table.Create
relationships between these new tables and their predecessors through the use of foreign
keys. The main advantage of using object orriented concepts to design is that databse is that
such a databse is fully compatible with object oriented applications and systems.one HOD
One to many M .Many teachers . storing the same data in more than one table and ensure
data dependencies make sense only storing related data in a table.one department
.Eliminate duplicative columns from the same table. . also known as Boyce.Codd normal
form BCNF has one requirement . Description of Normalization Forms First Normal Form NF
sets the very basic rules for an organized database .Many students Normalization Its a
process of efficiently organizing data in a database.HOD Many to Many MN . This column is
called the primary key. Foreign Key .
NCLOB . You must specify size for a RAW value. The precision p can range from to .Stores
national character set data. Maximum size is determined by the national character set
definition. Stores integer numbers. Maximum size is gigabytes . fractionalsecondsp
fractionalsecondsprecision is the number of digits in the fractional recision part of the
SECOND datetime field. fractionalsecondsp where fractionalsecondsprecision is the number
of digits in the recision WITH TIME fractional part of the SECOND datetime field. Maximum
size is bytes or characters. A character large object containing singlebyte or multibyte
characters. Maximum size is gigabytes. Variablelength character string having maximum
length size bytes or characters. Valid date range from January . Raw binary data of variable
length up to gigabytes. with an upper limit of bytes.I Data Type CHAR NCHAR Description
Fixedlength character data of length size bytes. database block size. VARCHAR
NVARCHAR NUMBER p. Default and minimum size is character. AD. Maximum size is
gigabytes . TIMESTAMP All values of TIMESTAMP as well as time zone displacement value.
Raw binary data of length size bytes. documents or arrays of binary data. An Integer number
does not contains a floating point. Maximum size is bytes. Number having precision p and
scale s. both using the database character set. Variablelength character string having
maximum length size characters. sound. Character data of variable length up to gigabytes.
Oracle DATA Type S. database block size. BC to December . Both fixedwidth and
variablewidth character sets are supported. Contains a locator to a large binary file stored
outside the database. The scale s can range from to .s INTEGER DATE LONG BLOB
CLOB/NCLOB RAW size LONG RAW BFILE New Data Type in Oracle i TIMESTAMP Allow
the time to be stored as a data with fraction of seconds. Enables byte stream I/O access to
external LOBs residing on the database server. LONG RAW Can be used to stores graph.
Fixedlength character data of length size characters. Maximum size is bytes or characters.
with an upper limit of bytes.A column in one table whose value matches the primary key in
some other table is called as a foreign key. A binary large object. ZONE . Maximum size is
determined by the national character set definition. or bytes.
SQLgt select from emp . SQLgt insert into emp values . SQLgt insert into emp values .
SQLgt select from emp . AM SQLgt create table emp empno number.. startdate timestamp
with time zone .. When the data is retrieved. AM SQLgt create table emp empno number.
INTERVAL DAY Allows time to be stored as an interval of days to hours. SQLgt select
tocharsysdateloanduration. startdate timestamp . minutes dayprecision TO and second.
SQLgt insert into emp values . dayduarion interval day to second .Nov AM . where
yearprecision is yearprecision TO the number of digits in the YEAR datetime field.. Accepted
values are MONTH to . INTERVAL YEAR Stores a period of time in years and months.
SYSDATED NOV timestamp with time zone TIMESTAMP fractionals econdspreci sion WITH
LOCAL TIME ZONE INTERVAL YEAR TO MONTH INTERVAL DAY TO SECOND . SQLgt
insert into emp values .interval month .interval day . EMPNO STARTDATE NOV .. AM SQLgt
create table emp empno number. SQLgt select sysdatedayduarion from emp . SQLgt insert
into emp values . Stores a single precision bit floatingpoint number. TIMESTAMP All values
of TIMESTAMP WITH TIME ZONE.. The default is .. loanduration interval year to Month
.ddmonyyyy from emp . with the following fractionalsecondsp exceptions recision WITH
LOCAL Data is normalized to the database time zone when it is TIME ZONE stored in the
database. Useful in presenting the precise difference between two SECOND date time
values fractionalsecondsp recision New Datatypes in g BINARYFLOAT BINARYDOUBLE
Stores a single precision bit floatingpoint number. orderdate timestamp with local time zone
.nov AM . Example of The New data Type In Oracle i TIMESTAMP SQLgt create table emp
empno number. EMPNO ORDERDATE NOV .may . users see the data in the session time
zone. EMPNO STARTDATE MAY . TOCHARSYS may SQLgt create table emp empno
number. SQLgt select from emp .
and the SQL language compiler automatically generates a procedure to navigate the
database and perform the desired task SQL Language SELECT INSERT. TRUNCATE
COMMIT. ALTER. MERGE CREATE. DROP. . DELETE. RENAME. UPDATE.
nonprocedural language .SQL is a database access.Keyword cannot be abbreviated .
NUMBER Describe Dept DEPTNO NUMBER DNAME VARCHAR LOCATIONID NUMBER
Describe Locations LOCATIONID LOCNAME NUMBER VARCHAR SQLgt select from emp .
SAVEPOINT GRANT. ROLLBACK. EMPNO ENAME SMITH ALLEN WARD JONES
MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS suresh FORD MILLER JOB
CLERK SALESMAN SALESMAN MANAGER SALESMAN MANAGER MANAGER
ANALYST PRESIDENT SALESMAN CLERK DBA ANALYST CLERK MGR HIREDATE DEC
FEB FEB APR SEP MAY JUN APR NOV SEP MAY DEC DEC JAN SAL COMM DEPTNO
SQLgt select from dept.ANSI Standard .Structure Query Language SQL . NUMBER.Users
describe in SQL what they want done. REVOKE Data retrieval Language Data Manipulation
Language Data Definition Language Transaction Control Data Control Language To open
the isqlplus http//localhost/isqlplus Describe EMP EMPNO ENAME JOB MGR HIREDATE
SAL COMM DEPTNO NUMBER VARCHAR VARCHAR NUMBER DATE NUMBER.
SQL PLUS File Commands SQL gt SAVE filename SQLgt save csureshss.DEPTNO
DNAME ACCOUNTING RESEARCH SALES LOCATIONID OPERATIONS SQLgt select
from locations.sql replace SQL gt GET filename SQL gt START filename SQL gt filename
SQL gt edit filename SQL gt Spool on . job from emp . LOCATIONID SQL PLUS EDITING
COMMANDS SQLgt L SQLgt select empno from emp . SQLgt A . SQL gt select from emp .
Job SQL gt L SQLgt select empno . SQL gt EXIT Data Retrieval/Query Language DRL/DQL
SELECT General SQL Commands . SQL gt c/emp/dept SQLgt L LOCNAME NEW YORK
DALLAS CHICAGO BOSTON SQL gt select from dept . SQL gt Spool filename SQL gt Spool
off .
sal gt or jobSALESMAN . SQLgt select empno.ename. SQLgt select empno. SQLgt select
empno. job in SALESMAN.DDDD. SQLgt select empno. job not in SALESMAN. SQLgt select
empno.Display all the Employees of their EMPNO.ename.sal from emp where sal lt .
.ename.sal from emp where sal gt . .sal from emp where ename like S .sal from emp where
sal gt .ename.ename. Duplicate Row SQLgt select distinct deptno from emp.sal from emp
where ename not like S .ANALYST. SQLgt select empno. Logical condition SQLgt select
from SQLgt select from SQLgt select from SQLgt select from emp emp emp emp where
where where where sal gt and jobSALESMAN .Concating employee no and name column
SQLgt select empno ename from emp .JOB. SQLgt select empno. quotTotal Salaryquot from
emp.ename. SQLgt select from emp where sal any select sal from emp where deptno .
adding to everybodies salary from EMP table with changing the salary column heading
SQLgt select empno.sal from emp where sal .ename. SQLgt select empno. SQLgt select
distinct job from emp .sal from emp where job in CLERK. Data Manipulation Language DML
INSERT..sal from emp where deptno in . SQLgt select empno.sal as TotalSalary from emp.
designation . SQLgt select empno.sal quotTotal Salaryquot from emp.ename.CLERK .Putting
in place of null values SQLgt select empno.salary and department no from EMP table SQLgt
select EMPNO. Other Comparison Condition SQLgt select from emp where comm is null and
mgr is null .sal from emp where deptno not in .loc values .dname.ename. SQLgt select
empno.sal TotalSalary from emp.ename.ename. Concatenation Operator . sal
nvlcomm.Inserting rows to dept table SQLgt insert into dept deptno. name. DELETE. . SQLgt
select empno.Display all the rows and columns in EMP table SQLgt Select from emp
.DEPTNO from emp .. SQLgt select empno.ename.sal from emp where sal between and .
MERGE . Limiting the Row Selected by comparison condition SQLgt select from emp where
empno. UPDATE.ename. name.ANALYST.sal from emp where sal not between and
.ename.ename. ARITHMETRIC EXPRESSION Display all the Employees of their
EMPNO.ename.sal.ENAME.SAL. SQLgt select ename having Employee Is empno from
emp.dddd .sal from emp where job not in CLERK. .CLERK . SQLgt select empno.
deptno WHEN NOT MATCHED THEN INSERT VALUES e. ampdname. Copy the record
from dept to dept table SQLgt insert into dept select from dept . SQLgt update emp set sal
sal where deptno in select deptno from emp where deptno .loc values ampdeptno.ename .e.
Rename alter table student add address varchar . . Delete the rows from emp table whose
depart no is SQLgt delete from emp where deptno . . . TRUNCATE. ENAME VARCHAR. c.
SQLgt insert into dept select from dept where deptno .empno. ename varchar. Delete with
subqury SQLgt delete from emp where deptno in select deptno from emp where deptno .sal
e. RENAME Creating a table create table Employee empno number.Merging Rows create
table copyemp EMPNO NUMBER. SQLgt update emp set salsal where deptno and sal gt .e.
sname varchar. fname varchar . Branch varchar.dddd .ename. alter table stdeunt add
address varchar. Or SQLgt delete emp. DOB date.. amploc .ename e. . c.deptno. Modify.
DATA DICTIONARY LANGUAGE DDL CREATE.empno e. Merge into copyemp c using emp
e on c. sal number.deptno e. Updating/Changing the existing employees information SQLgt
update emp set salsal .SQLgt insert into dept deptno. DEPTNO NUMBER .dname. Drop.
Altering a table by using Add. SAL NUMBER.e.DDDD.empno WHEN MATCHED THEN
UPDATE SET C.Deleting all rows from emp table SQLgt delete from emp .create a create
table student rollno number. . SQLgt insert into dept values . ALTER.sal. DROP.sal.
Drop table emp . . Dropping a table Drop table tablename . .A user can grant access to his
database objects to other users user Granting the select previledge to user SQLgt GRANT
select on emp to user user User is viewing the user s emp table select from user. . open the
screen simultaneously.To seeting the Unused columns SAL in EMP table Alter table emp set
UNUSED COLUMN Sal. Rename emp to emp . . branch . resource to user . resource to user
. Renaming a table Rename oldtablename to newtabalename. REVOKE Database Security
and Previleges Create users. Grant Connect.emp . Create user user identified by user .To
renaming a column Alter table emp rename column ename to empname .To drop multiple
columns at a time is Alter table student drop FNAME. user .The Grant command is used to
grant access to the database . Alter user user identified by user . The synatx for creating a
user SQLgt SQLgt SQLgt SQLgt SQLgt SQLgt Create user user identified by user Alter user
user identified by user .Dropping a column in student table alter table student drop column
address . address varchar . Grant Connect. The Grant Command . . Truncating a Table
truncate table dept.alter table student modify address varchar. DATA CONTROL
LANGUAGE DCL GRANT.Dropping the unused columnfrom the EMPtable Alter table emp
DROP UNUSED COLUMNS. DROP table tname .
SQLgt Rollback. Savepint The COMMIT Command The commit command is used to make
changes to data DML permanently SQLgt Commit. The SAVEPOINT Command Savepoints
statements are used to discard or commit all the changes upto a point SQLgt Savepoint a . in
suresh grant create table to user .emp set enameffff where empno .update on emp from
suresh with grant option .update user. Accordingly. functions can be classified as follows
Group Functions aggregate function .update user. Like functionname arguments.emp .
REVOKE Using the REVOKE command. Such variables or constants are called arguments..
Rollback.select from user. arguments. ORACLE FUNCTIONS Oracle functions serve the
purpose of manipulating data items and returning a result.. Oracle Function can be clubbed
together depending upon whether they operate on a single row or a group rows retrieved
from a table. SQLgt Rollback to savepoint a .emp set enameffff where empno .
TRANSACTION CONTROL LANGUAGE TCL Commit. revoke select. user revoke update on
emp from user user . DBA can give Grant create table. Functions are also capable of
accepting usersupplied variables or constants and operating on them.GRANT update on
emp to user user . create session to suresh with admin option. The ROLLBACK Command
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 . a DBA can revoke
database privileges from the users user User is revoking the select previledge from user on
emp table Revoke select on emp from user user .
World from dual . nextdayhiredate. String Functions select select select select select select
select select select select select select select select select select select select
lengthSURESH from dual . Date Functions select empno. For example.DDD.. concatempno.
from emp ..ename from emp . Select avgsal from emp .hiredate from emp . lowerename from
emp . from emp . from dual . A group function returns a single row for a group of queries
rows. lpadsal. SUM. Aggregate function Select maxsal from emp ...A from emp . A single row
function returns one result for every row of a queried table or view. dumpabc. asciis. select
empno.FRIDAY from emp ..w from dual .addmonthshiredate. from emp.lastdayhiredate from
emp .addmonthshiredate. upperename from emp .monthsbetweensysdate. is a
function.nextdayhiredate.hiredate. Select sumsal from emp .hiredate.instrename. from dual .
Scalar Functions Single Row Functions Functions that act on only one value at a time are
called Scalar Functions.hiredate. from emp .monthsbetweensysdate.. which calculates the
length of one particular string value. substrename. select empno. initcapename from emp .
ename from emp where rowidCHARTOROWIDAAAHCAABAAAPAAAAK . chr from
dual.CCCC from dual . power.asciiS from dual . lastdayhiredate from emp . round. ename.
select empno.hiredate. rpadsal. USING CASE Expression . instrhelloworld. from dual . from
dual .FRIDAY. Select minsal from emp . chrchrCHR from dual. which calculates the total set
of numbers.hiredate. trunc. LENGTH. sqrt from dual . is a function. Numeric Functions select
select select select select abs from dual . concatHello.hiredate. select empno. lowerSql
Cousre from dual .Functions that act on a set of values are called set of values are called
Group Functions. select count from emp . For example. greatestASSASA.
select deptno. SALESMAN . case job when SALESMAN then sal when CLERK then sal
when PRESIDENT then sal when MANAGER then sal else sal end quotRevised Salaryquot
from emp . sal. select upperrtrimename working as a upperrtrimjob from emp .job. sal
quotRevised Salaryquot from emp.job.job.select ename.sumsal from emp group by
cubedeptno. sal. SELECT TOCHARsysdate.count from emp group by deptno . select
empno. sal. MANAGER. select deptno.ename.job .upperename from emp .sumsal from emp
group by rollupdeptno.DDMONYYYY HHMISS from dual .job . select deptno. select
lowerename. PRESIDENT .mgr. USING DECODE Function select ename. decode job. mgr
from emp start with mgr is null .job. . sal.sal.dd/mm/yyyy from dual . uid from dual. .job. The
aggregate functions are applied to the individual groups. 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. select tonumber from dual . maxsal from emp group by
deptno.mgr.job .job . level Commandgt select level. ename.mm/dd/yyyy from dual . select
tonumber from dual .ddmmyyyy from dual . rank over partition by deptno. maxsal from emp
group by deptno.job order by deptno. empno.job .sal.deptno. select todate. Aggregate
functions rea used to return summary information for each group. Conversion Functions
TODATE Converts character field to a date type TOCHAR date type to character type
TOCHAR number type to character TONUMBER Converts character to a number data type
select todate//. select deptno. job order by sal desc quotRquot from emp.maxsal from emp
group by deptno .List the department no and number of employees in each department no
SQLgt select deptno. maxsal from emp group by deptno. select deptno.job.List the
department no and maxumim salary of employees in each department no select deptno.
select tocharsysdate. select user. CLERK .
Order By Clause ORDER BY Clause will arrange the final result in the order specified select
select select select empno. SQLgt select job..sal empno. Referential Constraint Used bind
relation between tables NOT NULL Prevent a column from accepting NULL values UNIQUE
Ensures uniqueness of the values in a column PRIMARY KEY Same as UNIQUE. maximum
and minimum salary and the avrage salary of emplyees job wise department no and sipaly
only those rows having average salary greater than . restrict the groups that you return on
the basis of aggregate functions. The output should be arranged in the descending order of
sumsal. We can only use where to restrict individual rows. . Constraints super control the
data being entered into a table for permanent storage. Not null .sal empno. but only one
column per table is allowed CHECK Controls the value of a columns being inserted
DEFAULT Assigns a default value for the columns. at the time of insertion when no value is
given for that column REFERENCES Assigns a Foreign Key constraint to maintain
Referential Integrity ON DELETE CASCADE Using this option whenever a parent row is
deleted then all the corresponding child rows are deleted from the details Tbale. Unique
.Check.ename.ename.Check for conditional rules ex. The Having Clause HAVING clause is
used to specify which group are to be displayed. . maxsal from emp group by deptno having
countgt Note The WHERE clause cannot be used to restrict the groups that are returned.
that is. minsal. Domain Constraint . . This option is always used with foreing key.ename.
ename desc.ename. select deptno. Integrity Constraints Constraints are enforced on data
being stored in a table. ename desc.connect by prior empnomgr Order by level. Example
Create a table using Primary Key and Not null constraints . empno asc.sumsal. List the
average salary for all department employing more than five people.check for uniqueness of
data ex. Avgsal from emp where deptno group by job having avgsal gt order by sumsal.sal
from from from from emp emp emp emp order order order order by by by by ename asc
.primary key.sal empno. are called Constraints. Maxsal.List the total salary.Entity Integraty .
Constraints are preferred Rules applied on table columns while creating or after creation
These are automatically activated whenever DML statement is performed on a table Provies
high security Integrity Constraints are three types .
To join two tables.Equi join Cartesian Joins . on delete Note If a user is not giving the
constraint name. alter table employee add constraint Deptpk primary key deptno . 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 i and Prior . unique .Outer Join . Job varchar unique .
. constraint Emppkid primary key empno . Oracle automatically create a constraint named as
SYSC some number Dropping the Primary key constraint SQLgt alter table employee drop
primary key . ename varchar not null. from userconstraints where JOINS Joins. create table
department deptno number primary key .Using Clause Joins . ename varchar not null. check
and default constraint create table employee empno number primary key. DOJ date default
sysdate. constraint EmpNOfk foreign key deptno references departmentdeptno cascade .
dname varchar not null.Full or two side outer joins . the information from any number of
tables can be accessed. deptno number . or alter table employee drop constraint
constraintname. .For foreign key .Cross Joins .Inner Joins . deptno number not null.Natural
Joins . check sal gt . primary key. To see details about the infomration of constraints SQLgt
desc userconstraints SQLgt select constraintname. create the master table first and after that
child table.constrainttype tableNameTABLENAME . Job varchar unique .Nonequi join
.Creating a table using foreign key.create table employee empno number. location varchar
.Self Join SQL Complaint Joins . sal number.
empno. dept where emp. This is also called as Simple Joins or Inner Joins . Using Table
Aliases select e.deptnod. Locations l where e. each row of one matches every row of the
other table.e.deptno . dept where emp.ename. they make an Equi Join.sal. select
ename.dept. Cartesian Joins When no join condition clause is specified in WHERE
clause.dname from emp.emp.ename. but SQL performs the command as through it
were.empno.ename.d.deptnodept.dname.deptno . in an euqi join that row will not be
selected.empno. dept where Using AND Operator select emp.dname from emp. The
corresponding columns for that will have NULLs.locationid . SQLgt select from emp. select
WORKER.emp.deptno dept. This results in a Cartesian product.ename.sal between j.dname
from emp.locationidl.deptno . dept d.dname from emp e.dname emp.dept. dept where
emp.deptno and d. The self join be viwed as a join of two copies of the same table. then the
total number rows produced is .empno .. .empno. If the number or rows in emp Table is and
dept table has . l.deptno dept.empno.dept. from emp. NonEquijoins select e.ENAME
Manager from emp worker.Joins with the ON Clause Equi Joins When two tables are joined
together using equality of values in one or more columns.deptno .ENAME.dname from emp.
select emp.mgrmanager.name.deptno .losal and j.locName from emp e.e.hisal . select
emp.deptnodept. emp manager where worker .deptno and e.dept.dname from emp cross join
dept . Joining More Than two Tables select e.ename. Selfjoins 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
table is not actually copied.d. salgrade j where e.empno.Primary Key and Foreign Key select
emp.ename.e. dept . dept d where e. MANAGER. dept .j.deptno and emp.emp.deptnod.
Using operator Outerjoins If there are any values in one table that do not have corresponding
values in the other. Cross Join select ename.grade from emp e .emp. Such rows can be
forcefully selected by using the outer join symbol .
d.deptno .The join condition for the NATURAL JOIN is basically an equijoin of all columns
with the same name.empno.locationid.Rows of first query plus rows of second query.l. earlier
select emp. m.locationidl.deptno .dname.locationid .deptno. dept where dept.dname.ename
from emp e Join emp m on e. Creating Joins with the USING Clause .deptno .mgr . with
duplicate rows Intersection Common rows frm all the queies Minus Rows unique to the first
query UNION select from emp union select from emp .ename. Left Outer Joins Select e.
.empno.dname from emp.d.deptnod.locname from emp e join dept d ON e.same as equi
joins Creating Joins with the ON Clause . select deptno.e. Right Outer Joins select
e.empno.locationid.dept. less duplicate rows union all .deptnod.dname from emp e inner join
dept d on e.d.dname.dname from emp e right outer join dept d on e.empnom.emp.deptno
.ename.dname from emp.deptno.The NATURAL JOINS clause is based on all columns in
the two tables that have same name select deptno.dept.ename. Inner Joins Select e.deptno
emp.deptnod.ename.locname .e.dname from locations l join dept d using locationid where
locationid .Do not use a table name ot alias in the referenced columns .ename.dname from
emp e left outer join dept d on e.deptnod.d. select e. Creating ThreeWay Joins with the ON
Clause select e.ename.deptno from emp e join dept d ON e.e.locname from dept natural join
locations where deptno in .emp.e.deptnod. select e.Rows of first query plus rows of second
query.deptno emp. Full Outer Joins select e.empno.Natural Join .The natural join and using
Clauses are mutually exclusive select l. dept where dept. d.ename.ename. you can not write
l.deptno .deptno.d. . 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 .deptno .locationid .deptno.locname
from dept natural join locations . earlier select emp.ename.e.deptno join locations L ON
d.dname from emp e full outer join dept d on e.e.deptnod.deptno .e.
avgsal salavg from emp group by deptno b where e.salavg from emp e.sal from emp where
sal in select minsal from emp group by sal . . Using Sub Query in the From Clause select
e.sal from emp where sal gt select sal from emp where enameSMITH and deptno select
deptno from emp where enameSMITH . MINUS select from emp minus select from emp.
Using Group Function in a Subquery select ename.e. You can build powerful statements out
of simple ones by using sub queries.sal from emp where sal gt select avgsal from emp.The
sub query inner query executes once before the main query. 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. ANY. SUB QUERIES Sub query A
sub query is a SELECT statement is embedded in a clause of another SELECT
statement.The FROM Clause .Equal to any members in the list ANY .deptno and e.The
WHERE Clause .salavg . lt. including .deptno.b. select deptno. select ename.minsal from
emp group by deptno having minsal gt select minsal from emp where deptno . . Comparison
conditions falls into two classes Single row Operators lt.sal gt b.Compare Value to every
value returned by the subquery IN select ename.job from emp where deptno select deptno
from emp where empno . select sal from emp where sal lt all select avgsal from emp . ltgt
Multiple row operators IN. .deptnob.sal. ALL Single Row Sub Queries select ename. gt.
Having Clause with Sub queries select deptno.The HAVING Clause .The result of the sub
query is used by the main query Outer query.UNION ALL select from emp union all select
from emp.ename. Multiple Row Sub Queries IN . INTERSECT select from emp intersection
select from emp.Compare Value to each value returned by the subquery ALL .e. gt.
select ename. .DEPTNO SQLgt SELECT ENAME. ALL select empno.sal from emp where
sal any select minsal from emp group by sal .job.sal from emp where any lt . Each sub query
is executed once for every row of the outer query. .ename.deptno from emp e where EXISTS
select empno from emp where emp.The command for creating VIEW is CREATE VIEW
command . SAL.empno . select empno.DEPTNO. List all employees who have atleast one
person reporting to them SQLgt Select empno. select ename.sal from emp where sal lt any ..
select ename.A VIEW Contains no data of its own .The changes in the tables are
automatically reflected in the VIEWS A VIEW is like a windows through which data can
viewed or changed.ENAME.. WORKING WITH DATABASE OBJECTS VIEWS VIEWS are
Database Objects whose contents are derived from another table .job from emp e where
NOT EXISTS select mgr from emp where mgre. select ename.sal from emp where sal lt all .
SQLgt select ename. if the subquery produces any opuput and False. SQLgt SELECT
ENAME.DEPTNO SELECT DEPTNO FROM DEPT WHERE DEPTNOA. if the subquery
does not produce any output. order by sal . EXISTS Operator This operator is used to check
for the existence of values This operator produces a Boolean result It takes a subquery as an
argument and evaluates it to True.sal from emp where sal lt all select sal from emp where
jobMANAGER .sal from emp where sal lt any select minsal from emp group by sal .
DEPTNO FROM EMP OUTER WHERE EXISTS SELECT FROM EMP WHERE DEPTNO
OUTER. SAL.DEPTNO .ename. DEPTNO FROM EMP OUTER WHERE SAL gt SELECT
AVGSAL FROM EMP WHERE DEPTNOOUTER. SAL.DEPTNO.DEPTNO FROM EMP A
WHERE A. SQLgt SELECT ENAME. List the employees details who do not manage any
one. .job..mgre.empno . Correlated Sub Query Correlated sub queries are used for rowbyrow
processing.sal from emp where sal lt any . DEPTNO FROM EMP OUTER WHERE NOT
EXISTS SELECT FROM EMP WHERE DEPTNO OUTER.ename.ANY select ename.
SELECT EMPNO.
create view EmpView as select empno. and then create a table sqlgt create force view bcd
as select from blank . SQLgt select rownum as rank.sal from emp order by sal desc where
rownum lt .Can perform DML operations through the view A Complex view is one that
.deptno from emp where deptno with read only .Derives data from many tables .deptno from
emp . ename.deptno.Derives data from only one table . Complex View . SQLgtupdate vname
set enameFFFF where empno .To present different views of the same data A Simple View is
one that .dname from emp e left outer join dept d on e. . .deptnod.To make complex queries
easy .deptno from emp . Update and Delete statement in a Simple View SQLgtinsert into
vname empno.XYZ.deptno values .Advantages of a VIEW . Views with Read Only create
view vname as select empno. count total from emp group by deptno .ename. VIEWS with
Check Option create view vname as select empno.Contains funcions or groups of data . alter
view vname as select empno. create view vname as select e.Creating a view with out the
table existing Create a view first.Creating a View using Group by function SQLgt create or
replace view emppview as select deptno.fffff.deptno from emp where deptno with check
option .deptno. select from EmpView .ename. Drop view EMPPVIEW . . insert into vname
values .ename.Does not always allow DML opearations through the view Simple View SQLgt
SQLgt SQLgt SQLgt create view vname as select empno.e.To restrict data access . Insert.
SQLgtdelete from vname where empno .ename.sal from emp where empno ..d. SQLgt
Create table blank a number .sal.ename. Creating a Force view .ename.sal.ename.To
provide data independence .sal from select ename.Contains no functions or groups of data .
Oracle Database supports several types of index Normal indexes. SEQUENCES A
Sequence Automatically generates unique numbers Is a sharable object Is typically used to
create a primary key value Replaces application code Speeds up effeciency of accessing
sequence values when cached in memory SQLgt create sequence Deptseq increment by
start with MAXVALUE . . Domain indexes. usersequences . SQLgt select Deptseq . .
Automatically A unique index is created automatically when you define a PRIMARY KEY or
UNIQUE constraint in a table definition. which are instances of an applicationspecific index of
type indextype SQLgt CREATE INDEX EMPIDX on emp empno . select from bcd .nextval
from dual . Oracle Database creates Btree indexes. which store rowids associated with a key
value as a bitmap Partitioned indexes. They enable you to construct queries that evaluate
the value returned by an expression. which in turn may include builtin or userdefined
functions. SQLgt select sequencename. Bitmap indexes. which consist of partitions
containing an entry for each value that appears in the indexed columns of the table
Functionbased indexes. lastnumber from INDEXES An Index . SQLgt Drop sequence
Deptseq .Is used by the Oracle Server to speed up the retrieval of rows by using
pointer.currval from dual . insert into blank values . Manually Users can create nonunique
indexes on column to speed up access to the rows. By default. which are based on
expressions.minvalues.Can reduce disk I/O by using a rapid path access method to locate
data quickly. SQLgt select Deptseq . incrementby. insert into blank values . SQLgt DESC bcd
Dropping a View SQLgt Drop view viewname .SQLgt SQLgt SQLgt SQLgt insert into blank
values .maxvalue.
SQLgt create table empaddress empno number primary key. SQLgt create cluster empadd
empno number . CLUSTER Clustering is a method of storing tables that are intimately
related and often join together into the same area on disk. address varchar cluster empadd
empno . Delete the cluster item . SQLgt create table empaddress empno number primary
key. SQLgt Drop Index Upperdeptidx . the same logical blocks. SQLgt DROP synonym dept.
address varchar cluster empadd empno . SQLgt create table emp empno number primary
key. SYNONYMS Simplify access to objects by creating a synonym. SQLgt select from
dept.BASED INDEXES .FUNCTION . BIT MAP INDEXES SQLgt CREATE BIT MAP INDEX
EMPIDX on empsex .Shorten lengthy object names SQLgt Create synonym dept for scott.
Dropping a Index SQLgt Drop Index ltIndexNamegt . This clauses improvement of
performance when the cluster columns are the columns by which the tables are generally
joined. ename varchar. SQLgt drop cluster empadd including tables . SQLgt create index
empaddress on cluster empadd .Ease referring to a table owned by another user . but are
not required to possess identical names. For the tables in a cluster. These must be of the
same data types and size. rows with identical column values are kept together on disk in the
same area.A functionbased index is an index based on expressions. address varchar cluster
empadd empno .dept. SQLgt Create Index Upperdeptidx on dept upperdeptno . It requires at
least one cluster column from each of the tables. .
Partitioning Method There are several partitioning methods offered by Oracle Database .
deptno number Partition by range deptno Partition p values less than tablespace tbs. ename
varchar.Range partitioning . VM. PARTITION q VALUES AZ. NJ tablespace tbs. an
application can be programmed to take advantage of partitioning by using partitionextended
table or index names in DML. . Partition p values less than tablespace tbs. deptname
varchar. You can specify a list of discrete values for the partitioning column in the description
for each partition. PARTITION q VALUES NY.SQLgt drop index empaddress . GA
tablespace tbs. SQLgt create table emp empno number primary key.. SQLgt CREATE
TABLE Deptpart deptno number. and performance Partitioning is transparent to existing
applications and standard DML statements run against partitioned tables. PARTITIONS
Storing partitions in separate tablespace enables you to Reduce the possibility of data
corruption in multiple partitions Back up and recover each partition independently Improve
manageability.Hash partitioning . Partition p values less than tablespace tbs. availability. WA
tablespace tbs. However. NM tablespace tbs. sal number.List partitioning Range Partitioning
Use range partitioning to map rows to partitions based on ranges of column values. state
varchar PARTITION BY LIST state PARTITION q VALUES OR. PARTITION q VALUES FL.
UT. Partition p values less than tablespace tbs List Partitioning Use list partitioning when you
require explicit control over how rows map to partitions.
p into PARTITION p . for the purpose of updations. partition h ta blespace ts. . month.
Truncating Partitions alter table emp truncate partition p . Dropping a Table Partition Alter
table emp drop partition p. partition h tablespace ts. It controls the physical placement of data
across a fixed number of partitions and gives you a highly tunable method of data placement.
Table Level Locks gt Row Level Locks This lock is used to lock either a single or group of
records. Ex Select from emp where empno for update of comm. month number.for the rest of
the numbers amp entities he can do manipulation Ex Select from emp for update of comm.
Coalescing a Partitioned Table ALTER TABLE emp COALESCE PARTITION. Renaming a
Table Partition ALTER TABLE emp rename PARTITION p to p . Moving a Partitions ALTER
TABLE emp MOVE PARTITION p tablespace tbs .sal. Row Level Locks . year partition h
tablespace ts. year number partition by hash day. Adding a Partition to a Partitioned Table
alter table emp add partition p values less than tablespace tbs . sal. Merging Partitions
ALTER TABLE emp MERGE PARTITIONS p . To Create HASH Partition SQLgt create table
purchases invno number . A Row Level Lock is implemented with in a select query using
quotfor update of quot clause. LOCKING MECHANISM Locks Locks are of two types.
partitionname from tablenameempsubtemplate order by tablespacename. Hash Partitioning
dbatabsubpartitions where 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. note another user cannot manipulate commampsal of .SQLgt
select tablespacename. day number.
E. gt Exclusive Lock When a user locks a table in Exclusive mode.g.job. no other user can
access that table except the user who has locked it in Exclusive mode. but still is used to lock
records.Single ampersand amp . Using DEFINE Command .. E.DEFINE command Using the
amp Substitution Variable For Integer select empno.ename from emp where job ampjob . to
use this lock first we need to lock the required records using row level lock and then
implement this lock. when it ends nd user can use it for manipulations. Lock table emp in
share update mode. but the stuser need not wait for the nd users end transaction E. Lock
table emp in Exclusive Mode. Expressions and Text select empno. gt Share Update Lock
Even though this lock fall under Table Level locks. note another user cannot manipulate all
the entities of the table Note only manipulations r not allowed but he can retrive values
selectof the table gt Table Level Locks These are further classified into three caregories. For
Character or date select empno.Note another user cannot manipulate commampsal all the
numbers.e.Double ampersand ampamp . More Commands In Oracle i Substitution Variables
Temporarily Store Values .g. Specifying Column Names. for the rest of the entities he can do
manipulation Ex Select from EMP for update. multiple users can implement this sharable lock
on a single table at the same time.ename. i.ampcolumnname from emp where ampcondition
order by ampOrdercolumn .g. note the nd user who didnt lock the table which is locked by
the first user should wait uptill the st users end transaction. gt Share Lock gt Share Update
Lock gt Exclusive Lock gt Share Lock This is a sharable lock..ename from emp where empno
ampempno . Lock table emp in share mode..
MANAGER.job. .ddddd.job.sal.sal from select ename.ename.MANAGER. .mgr from emp
where empno gt .N Analysis select rownum as rank.sal.sal INTO mgrhistory values
empno.sal.deptno from emp where deptno values . Using the ampamp Substitution Variable
select empno.default .ename.ename.ename. Using Explicit Default Values insert into emp
empno..ename. Using Verify Commands set verify on .hiredate.mgr.ampampcolumnname
from emp order by ampcolumnname .ename.sal .dddd.ename.hiredate. select empno.sal set
feedback on COLUMN JOB clear COLUMN ename clear COLUMN sal clear clear Break
Using Sub query in an INSERT Statements insert into select empno.sal. ename. Using Sub
query in an INSERT Statements with check option insert into select empno.hirdate values
.job. Performing TOP . select empno.deptno from emp where empnoampempno .deptno
from emp where empno ampempno .sal select empno. SQL Sample Report set feedback off
TTITLE EMployeeReport BTITLE Confidential BREAK ON JOB COLUMN JOB HEADING
JOBCattegory COLUMN ename HEADING EMPLOYEE NAME COLUMN sal HEADING
SALARY select job.sal from emp order by sal desc where rownum lt .ddddd.hiredate.sal from
emp where sal lt order by job.DEFINE empno .deptno from emp where deptno with check
option values .ename. Conditional INSERT ALL INSERT ALL WHEN SAL gt then INTO
salhistory values empno. Unconditional INSERT ALL INSERT ALL INTO salhistory values
empno.
weekid.salesTHU empno.salesfri salessourcedata . Easy Maintenance Improved data
security and integrity. .salesWED empno.mgr from emp where empno gt .weekid. Pivoting
Insert INSERT ALL INTO salesinfo INTO salesinfo INTO salesinfo INTO salesinfo INTO
salesinfo values values values values values empno. PL/SQL can handle errors. You can
program with procedural language control structures.weekid. .weekid.hiredate. Improved
code clarity. . PL/SQL Architecture Benefits of PL/SQL PL/SQL is portable.
.saleswed.weekid. Improved Performance Benefits of Subprogram .salesmon empno.sal
select empno. Improved performance.salesTUE empno.WHEN MGR gt THEN INTO
mgrhistory values empno.salesthu.salestue. PL/SQL Introduction to PL/SQL PL/SQL
required for data processing It is a procedural language extension to the nonprocedural
SQL.mgr. Blocks of PL/SQL code are passed to and processed by a PL/SQL
engine.salesFRI from select empno.sal.salesmon.weekid. You can declare variable.
The database table and column . The record can store an entire row of data selected from
the table or fetched by a cursor declared later. end . Vorderdate date sysdate .PL/SQL Block
Structure DECLARE Optional Variables. Naming Rules DECLARE mempid number . cursor.
Using ROWTYPE The ROWTYPE attribute provides a record type that represents a row in a
table or view.The previously declared variable name .Declaring Variables with the TYPE
Attribute vName emp.SQL statements . userdefined exception Begin Mandatory . the
attribute type is used EMPROWVAR EMPROWTYPE . begin select empno into mempno
from emp where empno. In case. vvalid BOOLEAN NOT NULL TRUE . Base Scalar Data
Types CHAR VARACHAR LONG LONG RAW NUMBER BOOLEAN Scalar Values
Declaration Declare Vjob Varchar . Declaring PL/SQL Variables assign operator DECLARE
vhiredate date.jobtype . vjob emp. then instead of declaring them individually.PL/SQL
statements Exception Optional Actions to perform when errors occur End. vdeptno number .
Using TYPE . variables for the entire row of a table need to be declared.enametype .
. Commenting Code / / declare Vename emp. Some Sample Progamme using PL/SQL Block
declare x number .saltype.sal . ..Putlinethe value of z is y . End . consisting of the column
names of the table as its members.PUTLINE set serveroutput on . y number . BEGIN select
sal into gsalary from emp where empno ... Declare vsal begin vsal vsal / . begin Declare Y
Number. Nested Block Declare x number. z number . .DBMSOUTPUT.. dbmsoutput. Print
gsalary For Printing the values . the following syntax will be used EMPROWVAR.
dbmsoutput.Here. end . Using BIND Variables VARIABLE gsalary number .. end .. sal SAL..
begin vconat Vename Vsal . dbmsoutput.. To refer to a specifiec variable. DEFINE panualsal
. Begin .. Vsal emp..empnotype . end .. vconat varchar.Putthe value of z is x . end
..putlineThe monthly salary vsal . begin z xy . the variable EMPROWVAR will be a composite
variable..
EDP.The Into clause declare mempno emp. end . Update command using declare Vsalinc
emp. end. Operators in PL/SQL Logical Arithmetic Concatenation Same as SQL Select
Statement in PL/SQL . end.deptnotype .empnotype . declare vdeptid dept. begin delete from
emp where deptno vdeptno .dname.Putlinethe value of z is z . mename emp.saltype
.deptnotype . . Delete command using declare Vdeptno emp.PutlineThe sasasasasa. begin
delete from dept where deptnovdeptid . begin update emp set sal sal vsalinc where deptno
.enametype . dbmsoutput.ename into mempno. end. Insert delete Update Merge Insert
command using begin insert into dept deptno.dbmsoutput. Manipulating data Using PL/SQL
Make Changes to database tables by using tables.America .mename from emp where
empno. end. begin select empno.loc values .
LOOP ltStatementgt exit looplabel WHEN Condition end loop . Example if vnameKING then
vjob President . elsif vnameJONES then vjob Manager .saltype. dbmsoutput. msal emp.
.putlinea . end if .empnotypeampempno . end if . a varchar .dbmsoutput. end . elsif msal gt
and msal lt then aSalary is between and . Conditional and Iterative Control The conditional
control available with PL/SQL are IFTHEN ELSE statement The type of Loops available with
PL/SQL Basic Loop While Loop For Loop IF STATEMENTS Syntax IF ltconditiongt then
ltstatementgt elsif ltconditiongt then ltstatementgt else ltstatementgt end if. begin select sal
into msal from emp where empnomempno. if msal gt and msal lt then aSalary is between
and . else aSalary is greater than . else vjob Clerk . Basic Loop The syntax is. end . declare
mempno emp.putline sqlrowcount Row deleted .
i i . end. end ... begin while I lt loop dbmsoutput. FOR Loop The Syntax is FOR ltvargt IN
ltlowergt. loop dbmsoutput.ltuppergt LOOP ltStatementgt End loop Example declare i number
. end loop. end . dbmsoutput. vappraisal varchar . begin vappraisal CASE vgrade WHEN A
then Execllent WHEN B then Very Good WHEN C then Good else No Such Grade end. . exit
when i gt .putlinei . end . end loop.Example declare i number . end loop. begin loop
dbmsoutput. Using CASE EXPRESSIONS declare vgrade char upper ampVgrade . WHILE
Loop The syntax is. i i .putlinei .putline Grade vgrade Appraisal vappraisal .putlinei . WHILE
conditionLOOP ltStatementgt end loop . begin for i in . Example declare i number .
Open the Cursor .putline Grade vgrade Appraisal vappraisal . end. Cursor The Oracle
Engine uses a work area for its internal processing in order to execute an SQL
statement.putlineWellcome. dbmsoutput. Closing the Cursor .Same program but we can
write some other way declare vgrade char upper ampVgrade . Opening the Cursor OPEN
empcursor .putlinefjbfbfbb. Controlling Explicit Cursors . ltltpqrgtgt dbmsoutput. else
dbmsoutput. .Vsal. Close the Cursor Declaring the Cursor CURSOR empcursor is Select
empno. Using GOTO Statement declare x number. Fetching Data from the Cursor Fetch
empcursor into vempno. if zgt then goto pqr. yampy.ename from emp . z number. Fetch a
row. Two Types Cursor A Implicit Declared for all DML and PL/SQL SELECT statements B
Explicit Declared and named by the programmer. begin vappraisal CASE WHEN vgrade A
then Execllent WHEN vgrade B then Very Good WHEN vgrade C then Good else No Such
Grade end. zxy. begin xampx. This work area is private to SQLs operations and called a
Cursor. y number. end if.Vename. vappraisal varchar . end.
vsal .Evaluates TRUE if the Cursor Open NOTFOUND . cursor c is select empno. begin
open empcursor. Explicit Cursor Attributes ISOPEN .Close Empcursor . end loop. End LOOP
. loop fetch empcursor into vempno.sal from emp. begin Open empcursor . for i in . loop fetch
c into vempno.sal from emp. vsal. LOOP fetch empcursor into vempno. cursor empcursor is
select empno. vename emp. exit WHEN empcursorrowcount gt or empcursornotFOUND.
begin open c.ename. vsal emp. dbmsoutput. for i in .enametype . end.Evaluates to the total
number of rows returned so far. dbmsoutput..saltype .Vename. Using FOR LOOP declare
vempno emp.putline vempno vsal. vsal emp.Evaluates TRUE if the most recent fetch return
a row ROWCOUNT . Examples Using BASIC LOOP declare vempno
emp.empnotype.empnotype.vsal. end.saltype . Same Program using notfound Implicit Cursor
declare vempno emp. cursor empcursor is select empno.vsal.putline vempno end loop.sal
from emp .Evaluates TRUE if the most resent fetch does not return a row FOUND
.putlineThe Employee No vempno and name is vename The salary is vsal.saltype . Close
empcursor.. exit when cnotfound. end. declare .empnotype. vsal emp. dbmsoutput.
mename emp.enametype msal emp.saltype mjob emp.jobtype mempno emp.empnotype
cursor c is select empno,ename,job,sal from emp begin open c loop fetch c into
mempno,mename,mjob,msal if msal lt then update emp set salmsal where empnomempno
dbmsoutput.putlinemempno mename msal mjob elsif msal between and then update emp set
salmsal. where empnomempno dbmsoutput.putlinemempno mename msal. mjob elsif msal
gt then update emp set salmsal. where empnomempno dbmsoutput.putlinemempno mename
msal. mjob end if exit when cnotfound end loop close c end FOR LOOP Declare cursor c is
select empno,ename,deptno from emp begin for emprecord in c loop if emprecord.deptno
then dbmsoutput.putlineEmployee No emprecord.empno emprecord.ename end if end loop
end Implicit Cursor Attributes SQLISOPEN Is always false because Oracle automatically
close an Implicit cursor after executing its SQL statement SQLNOTFOUND 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
Name
is
Cursor with parameter
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
cursorname parameter name data type is select statement Begin Open cursorname
parameter values End
Paremeter data types are the same as scalar data type but do not give them sizes. Example
declare mename emp.enametype mempno emp.empnotype cursor empcursor mdeptno
number, mjob varchar is select empno,ename from emp where deptnomdeptno and jobmjob
begin for emprecord in empcursor ,SALESMAN loop fetch empcursor into mempno,mename
dbmsoutput.putlinemename mempno end loop end Cursor with Subqueries Subquery returns
a value or set of values to outer query. Syntax Cursor empcur is select empno, ename, sal
from EMP where deprno in select deptno from dept Defining REF Cursor Type Explicit cursor
is a static cursor It is always refers only one work area in memory REF CURSOR is dynamic
cursor It is like a pointer in C It refer different work area in memory at run time more than one
SQL statement can be associated to ref cursor at run time. Cursor variable is like a pointer
define with REF type Types of REF CURSOR STRONG REF CURSOR the REF CURSOR
which is return type WEAK REF CURSOR the REF CURSOR without return type Define a
REF cursor type Type reftypename is REF CURSOR Declare a variable of the type refcv
reftypename STRONG REF CURSOR Declare Type refc is ref cursor return emprowtype C
refc Vrec emprowtype Vdno number ampvdno Begin If vdno then Open c for select from emp
where jobMANAGER Elsif vdno then Open c for select from emp where jobSALESMAN Else
Open c for select from emp where jobCLERK End if
Loop Fetch c into vrec Exit when cnotfound dbmsoutput.putlinevrec.empno vrec.ename end
loop close c end WEAK REF CURSOR declare vempno emp.empnotype vsal emp.saltype
vename emp.enametype mdname dept.dnametype type r is ref cursor empcursor r begin
Open empcursor for select empno,ename,sal from emp LOOP fetch empcursor into
vempno,Vename,vsal dbmsoutput.putlineThe Employee No vempno and name is vename
The salary is vsal exit WHEN empcursorrowcount gt or empcursornotFOUND End LOOP
Open empcursor for select dname from dept LOOP fetch empcursor into mdname
dbmsoutput.putlineThe dept name is mdname exit WHEN empcursorrowcount gt or
empcursornotFOUND End LOOP end
EXCEPTION HANDLING
An Exception is an identifier in PL/SQL that is raised during execution that terminates main
body of action. EXCEPTION is raised by two methods An Oracle error occurs and then
associated exception is raised automatically. Using RAISE statement within the block, the
exception being raised may be user defined or predefined EXCEPTION is three type Pre
Defined Exception UserDefined Exception NonPre Defined Exception Pre Defined Exception
The predefined oracle package standard has defined exceptions for certain common errors.
Exceptions are handled using names not using error numbers. The errors which are not
handles using exception, can be handled usinf exception OTHERS Examples Toomanyrows
Nodatafound Zerodivide others Some Sample Programs Using PreDefined Exceptions
begin select sal into x from emp where deptnoy. dbmsoutput.saltype . Using zerodivide
Exceptions declare x number . when others then dbmsoutput. Using toomanyrows Exception
declare mename emp. dbmsoutput. end.putlinemore then one error
selected.putlinewellcome. begin zx/y . y number . dbmsoutput.msal from emp where empno
.Putlinez . end.msal from emp where deptno .saltype. z number .sal into mename. end. msal
emp.Raised Explicitely with RAISE statements . begin select ename.putlineno record
found.saltype. y emp.putlinesal of empno isx. exception when toomanyrows then
dbmsoutput.deptnotypeampdeptno.putlineInvaild empno .putlinemenamemsal . begin select
ename.enametype . exception when nodatafound then dbmsoutput. if sqlrowcount gt then
dbmsoutput.Putline Too many rows returned . exception when toomanyrows then
dbmsoutput.sal into mename. end.enametype. Using toomanyrows and others Exception
declare x emp. User Defined Exception User defined exceptions must be . exception when
zerodivide then dbmsoutput.declared in the declare section of a PL/SQL Block .PutlineThe
values is divided by Zero .PutlineThe emp name is mename salary is msal . end if.
dbmsoutput. Using nodatafound Exception declare mename emp. msal emp.
declare x emp.wrong empno .putlinewellcome. declare vempno numberampempno .
exception when empexc then dbmsoutput. EinvalidDept Exception.Some Sample Programs
Using User Defined Exceptions declare vempno number .msal from emp where empno
.Putlinemsal . end if .sal into mename. begin select sal into x from emp where empnoy. end if
. declare mename emp.putlinesalary is greater than .saltype. y emp. begin delete from emp
where empnovempno . salexc exception . if SQLNOTFOUND Then
RAISEAPPLICATIONERROR . msal emp. RAISEAPPLICATIONERROR can be used in
either the executable section or exception section of a PL/SQL
program.empnotypeampempno. end . Exception WHEN EinvalidDept then DBMSOUTPUT.
end if. empexc exception . if msal gt then Raise empexc . else dbmsoutput. if x gt then raise
salexc. end . begin select ename. begin delete from emp where empnovempno .
dbmsoutput.putlinesal of empno isx. if SQLNOTFOUND Then RAISE
EinvalidDept.enametype .PUTLINEWrong EMPNO .saltype . else dbmsoutput.
RAISEAPPLICATIONERROR Procedure Is used to communicate a predefined exception
interactively by defining a non standard error code and error message. . end.
end. is done in the declare section of a PL/SQL block. . create a parent child relationship
table gt Entity integrity error declare eempremaining EXCEPTION . to a name i. begin delete
from dept where deptno . commit. PRAGMA EXCEPTIONINITzdivide. The Pragma action
word is a call to a precompiler.e. begin select sal into msal from emp where deptno. which
immediately binds the numbered exception handler to a name when encountered.end if. end.
exception when zdivide then dbmsoutput. z number.putlineNumber is divided zero .
exception when salexc then raiseapplicationerror. This binding of a numbered of a numbered
exception handler. when others then dbmsoutput. declare trowmany EXCEPTION . . .
exception when trowmany then dbmsoutput.putlineno data found.putlinecanot remove dept .
. String. exception when eempremaining then dbmsoutput. end. These lines will be included
in the Declare section of the PL/SQL block. end. PRAGMA
EXCEPTIONINITtrowmany.Salary is greater than .putlineToo Many Rows returned . x
number . The function Exceptioninit takes two parameters the first is the user defined
exception name the second of the oracle engines exception number. y number . PRAGMA
EXCEPTIONINITeempremaining. declare zdivide EXCEPTION . begin zx/y. NonPredefined
Exception Using PRAGMA EXCEPTIONINIT The technique that is used to bind a number
exception handler to a named using Pragma Exceptioninit.
putlineToo Many Rows returned . Declare Errnum number . 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. .declare trowmany EXCEPTION .
we can identify the associated error code and error message by using two functions. msal
emp.saltype. . as a schema object. PRAGMA EXCEPTIONINITtrowmany. which then return
the message associated with the error number. Errmsg Varchar . End . . Parameter mode
datatype ASIS PL/SQL BLOCK Procedural Parameter Modes Type of Parameter Description
IN Parameter Passes a constant value from the calling environment into the procedure.
SQLCODE returns number of the Oracle error for internal exception. Insert into errors values
errnum. exception when trowmany then dbmsoutput. Errmsg sunstrSQLERRM. We can pass
an error number to SQLERRM. PROCEDURES A Procedure is type of subprogram that
performs an action. begin select sal into msal from emp where deptno. Syntax for Creating
Procedure Create or Replace procedure procedure name Parameter mode datatype.errmsg
.A procedure can be stored in the database. Error Trapping Functions When an Exception
occurs. . end. Begin Exception Errnum SQLCODE . for repeated execution.
vcomm out emp. substrpphoneno. end. dbmsoutput.enametype.comm into vname.vsal.
end.vcomm from emp where empnovempid. b in number is c number.commtype IS begin
select ename. substrpphoneno.. end . end . . OUT Parameter create or replace procedure
queryemp vempid in emp. create or replace procedure empproc mempno in number is begin
update emp set salsal where empnomempno. end .empnotype..saltype. Steps for printing the
IN OUT result variable gphoneno varchar begin gphoneno .A.B.sal.steps for the printing the
out parameter VARIABLE A VARCHAR VARIABLE B NUMBER VARIABLE C NUMBER
EXEC QUERYEMP . .C print A print B print C IN OUT Parameter create or replace
procedure formatphone pphoneno in out varchar is begin pphoneno
substrpphoneno.putlineThe values of c is c.IN Parameter create or replace procedure
Addproc a in number. vname out emp. . vsal out emp. begin c ab .
create or replace procedure empproc mdeptno emp. cursor empcursor is select ename. vsal
emp. loop fetch empcursor into vename.job from emp where deptnomdeptno.saltype
.sal.enametype. begin select ename. checkemp exception .putlineNo such Employee
number exist./ execute formatphonegphoneno print gphoneno Invoking Procedure from
another procedure create or replace procedure viewprocdept mdeptno in number is vdname
dept. vsal emp.sal into vename. dbmsoutput.sal from emp where deptnomdeptno
.dnametype. mjob emp. mename emp. end loop. end . viewprocdeptmdeptno. EXCEPTION
WHEN nodatafound then dbmsoutput.enametype. end .enametype.putlineThe employee
name is vename Salary is vsal .vsal from emp where empnomempno.putlineThe employee
name is vename Salary is vsal . dbmsoutput. end . dbmsoutput. begin select dname into
vdname from dept where deptnomdeptno .saltype . .deptnotype as cursor c is select ename.
msal emp.saltype . Using Exception in Procedure create or replace procedure viewexecemp
mempno in number is vename emp. begin open empcursor . exit when empcursornotfound.
create or replace procedure viewprocemp mdeptno in number is vename
emp.jobtype.putlineThe department name is vdname . close empcursor .vsal.
salary is msal mjob . else dbmsoutput.locnametype default unknown IS begin insert into
locations values vlocationid. exception when checkemp then dbmsoutput. Syntax for
Creating Function Create or Replace function function name parameter mode datatype. end .
end loop . Dropping Procedure drop procedure viewprocemp.msal. exit when cnotfound .
loop fetch c into mename. Functions A Function is a named PL/SQL block that returns a
value. .putlinethe employee name is mename end if . vlocname IN
locations.vlocname.locationidtype default .begin open c. select tax from dual . Default Option
for Parameter in Procedure create or replace procedure addlocation vlocationid in
locations.putline the deptno not found .mjob . End . end. parameter mode datatype RETURN
datatype ASIS PL/SQL BLOCK Some Programs Using Functions create or replace function
tax pvalue in number return number is Begin return pvalue . if crowcount lt then raise
checkemp . drop procedure viewexecemp . drop procedure viewprocdept .
create or replace function total a number . end.empnotype return number IS vsal number.
select getsal from dual . from dual .empnotype return number IS vsal number. end . sal.
taxsal from emp where deptno . b number return number is begin return ab . execution
Method . Create or replace function getsal mempid in emp. return vsal. select area . BEGIN
select sal into vsal from emp where empnomempid . Create or replace function getsal
mempid in emp. .ename. Variable gsal number execute gsal getsal Print gsal select empno.
execution Method .
create or replace function funcname mempno in number return number is msal emp. if
sqlrowcount gt then return mename . end .x number. select funcname from dual . begin
select sal into msal from emp where empnomempno . end if . end if .saltype. x vsal. end if
.putlineright .putlinewrong . end. end . if msal gt then return true . else return msal . create or
replace function funcname mempno in number return varchar as mename emp. if msal gt
then return msal . begin if funcname then dbmsoutput. return x .enametype . end.saltype.
end . else return false . create or replace function funcname mempno in number return
boolean is msal emp. begin select sal into msal from emp where empnomempno . begin
select ename into mename from emp where empnomempno . else dbmsoutput. begin select
sal into vsal from emp where empnomempid . end if . . .
PACKAGE and PACKAGE BODY Packages A Package is an Oracle object. Dropping a
Function Drop function functionname . which holds other objects within it. cursors and
subprograms that are available for use.Using Exception create or replace function funcname
mempno in number return varchar as mename emp. A Package body fully defines cursor.
Desc userobjects .enametype . A Package consists of two components . functions.Body A
Package Specification declares the types variable of the Record type. variables. cursors and
exceptions. end . desc usersource select text from usersource where NAMEFUNCNAME .
desc usererrors select from usererrors . end if . exceptions. Objects commonly held within a
package are procedures. begin select ename into mename from emp where empnomempno
.Specification . select from userobjects . constants. . constants. memory variables. functions
and procedure and thus implements the specification. return mename . if sqlrowcount gt then
return mename . exception when nodatafound then menameno data .
and the interfaces between packages are simple. Some Sample Program using Package
and Package Body create or replace package empproc as Procedure emppr mempno
number . end. Package improves performance by loading multiple objects into memory at
once. dbmsoutput. Each package is easily understood. Procedure deptpr mdeptno number
.putlinesal is msal . end. Therefore all cursors and procedures that execute in the
environment can store them. begin select sal into msal from emp where empnomempno .
Thereby reducing redundant coding. end. subsequent calls to related sub programs in the
package require no I/O.putlinedname is mdname . dbmsoutput. . begin select dname into
mdname from dept where deptnomdeptno. Therefore. Procedure deptpr mdeptno number as
mdname varchar . Package allows granting of privileges efficiently. A Packages public
variables and cursor persist for the duration of the session. clear and well defined. Packages
enable the overloading of procedures and functions when required. Creating the Package
Body Syntax CREATE Or Replace PACKAGE BODY packagebodyname IS AS private type
and item declarations subprogram body End packagebodyname. Package promotes code
reuse through the use of libaries that contain shared procedures and functions.Why Use
Package Packages offer the following advantages Packages enable the organization
applications into efficient modules. Creating the Package Specification Syntax CREATE Or
Replace PACKAGE packagename IS AS public type and item declarations subprogram
specifications End packagename. create or replace package body empproc as Procedure
emppr mempno number as msal number .
putthe dept . dbmsoutput. end. begin xp. Using Cursors in Packages create or replace
package packcur IS cursor c is select empno from emp . end pro. declare x number
.putlinethe multiplication ofx andyz. empproc. END.emppr . dbmsoutput. empproc.deptpr .
create or replace package body p as function fx number return number as y number.pro.
procedure procemp . procedure procemp . procedure pro x number.putlinex. create or
replace package p as function fx number return number . end.end. end . dbmsoutput.putthe
emp . . To execute this Program exec p. begin zxy.f. To execute the previous program
declare begin dbmsoutput. end f. procedure pro x number.. begin yx/. y number as z number.
return y.y number .
end loop . create or replace package packcur IS cursor c is select empno from emp .
procedure procemp is begin open c. dbmsoutput. end . dbmsoutput. procedure procemp .
end procemp . procedure procdept.putlinemdname . procedure procdept IS begin open c.
procedure procemp is begin open c. close c. cursor c is select dname from dept
.putlinemempno .putlinemempno . end procdept . dbmsoutput. end . end loop . end procemp
. procedure procemp IS begin loop fetch c into mempno .empnotype.end . loop fetch c into
mempno . . end loop . create or replace package body packcur IS mempno emp. end loop .
dbmsoutput. loop fetch c into mdname . end procemp .putlinemempno . exit when crowcount
gt .dnametype. exit when crowcount gt . loop fetch c into mempno . exit when crowcount gt .
close c. exit when crowcount gt . create or replace package body packcur IS mempno
number. end . mdname dept.
OVERLOADING PROCEDURES AND FUNCTIONS A Package is an Oracle object that can
hold a number of other objects like procedure and functions. To Execute the Package and
Package Body declare x number. DROP PACKAGE BODY packagebodyname . return z.
yardmeter CONSTANT NUMBER ... begin zxy. function fx number.Declaring a Bodiless
Package CREATE or REPLACE PACKAGE globalconsts IS milekilo CONSTANT NUMBER .
. end.. CREATE OR REPLACE PROCEDURE metertoyaard pmeter IN number. end f.
kilomile CONSTANT NUMBER . return y. end globalconsts. begin yx. 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. y number return number as z number.
meteryard CONSTANT NUMBER . create or replace package body p as function fx number
return number as y number.meteryard . create or replace package p as function fx number
return number. multiple functions that are declared with the same name are called
Overloaded Functions. Multiple procedures that are declared with the same name are called
Overloaded Procedures.y number return number.. Similarly. end. Droppimg/ Removing
Package and Package Body DROP PACKAGE packagename . End . function fx number.
pyard out Number IS BEGIN pyard pmeter globalconsts. end f.
end if.f. end. create or replace package body p as function fx number return boolean as
begin if x gt then return true. end if. declare x boolean. create or replace package p as
function fx number return boolean.y number return boolean.putlinex. end. begin if
p.putlinetrue. declare x number. if zgt then return true. end f. end.. begin zxy. function fx
number. else return false. dbmsoutput. begin if p. else return false.y number return boolean
as z number. To execute the Program declare x boolean. function fx number. end if.
end.begin xp. dbmsoutput.putlinex.f then dbmsoutput.f.putlinetrue. end if.f then dbmsoutput.
end. end f. end. . begin xp.
exception when nodatafound then dbmsoutput.putlineNo data found . begin select ename
into mename from emp where empnomempno . procedure empproc mempno number.
end.saltype. . end empproc.putlineEmployee name is mename . msal emp.Can be either
DML Trigger . . view.putlineEmployee name is mename salary is msal . schema or the
database.enametype . end if. create or replace package body packover as procedure
empproc mempno number as mename emp. create or replace package packover as
procedure empproc mempno number . declare x boolean.fires whenever INSERT.declare x
boolean. mdeptno number . end empproc.enametype .mdeptno number as mename emp.
end .putlineNo data found . exception when nodatafound then dbmsoutput. UPDATE. begin if
p. end.f then dbmsoutput. end . and Trigger A Trigger .f. procedure empproc mempno
number. dbmsoutput.sal into mename. DELETE .putlinetrue.Is a PL/SQL block or a PL/SQL
procedure associated with a table. else dbmsoutput. then dbmsoutput.putlinefalse . begin
select ename.putlinetrue. dbmsoutput.Executes implicitly whenever a particular event takes
place.msal from emp where empnomempno deptnomdeptno . end if . begin if p.
UPDATE or DELETE . INSTEAD OF Execute the trigger body instead of the triggering
statement.for View INSERT.. Update amp Delete statement on a table. This is the default.
Row The trigger body executes once for each row affected by the triggering events.Trigger
Type Row or Statement .gt BEFORE row trigger SMITH JONES gt AFTER row trigger
SURESH gt AFTER statement trigger Syntax for creating DML Statement Triggers CREATE
OR REPLACE trigger Triggername timing events OR events OR events ON tablename
Triggerbody create or replace trigger empBefinst before insert on emp begin dbmsoutput. A
row trigger is not executed if the triggering events affect no rows. even if no rows are affected
at all. ALTER.Triggering Event On table..for table BEFORE. A statement trigger fires once.
AFTER .putlinebefore .Trigger body PL/SQL block DML Trigger Components BEFORE
Execute the trigger body before the triggering DML event on a table. DROP DatabaseTrigger
. AFTER Execute the trigger body after the triggering DML event on a table. .Schema Trigger
CREATE. shutdown or startup occurs on a schema or a database Creating DML Triggers A
triggering statement contains . View . Trigger type Statements The trigger body executes
once for the triggering events. Firing Sequence gt BEFORE statement trigger Empno Ename
Deptno .fires whenever system events such as Logon.WHEN Clause Restricting condition .
This is used for views that are not otherwise modifiable.Trigger Timing . Triggering user
events The triggering event is an Insert. end .
end.empno . begin meno new..create or replace trigger empaftinst after insert on emp begin
dbmsoutput.Employee cannot insert. dbmsoutput. create or replace trigger ressalary before
insert on emp begin dbmsoutput. .ename.Employee cannot delete.sal. end . insert into emp
empno. create or replace trigger aftins after insert on emp for each row declare meno emp.
end. end. create or replace trigger ressalary before insert on emp begin
RAISEAPPLICATIONERROR . CREATE TRIGGER SalaryCheck AFTER INSERT OR
UPDATE OF sal ON emp FOR EACH ROW BEGIN IF new. create or replace trigger
ressalary before update of sal on emp begin RAISEAPPLICATIONERROR . end .putlineNew
employee no is meno . end. delete from emp where empno .putlinewelcome.rrr. update emp
set sal where empno .sal lt THEN .empnotype . create or replace trigger ressalary before
delete on emp begin RAISEAPPLICATIONERROR .Employee cannot update.deptno values
.putlineafter .
END. end if .SUN or tocharsysdate. Trigger using conditional Predicates create or replace
trigger secureemp before insert or update or delete on emp begin if
tocharsysdate.RAISEAPPLICATIONERROR. end if . end. end.comm is null then new. else
new. end.SUN or tocharsysdate.HHMI not between and then if deleting then
raiseapplicationerror .You may insert into emp table only during businees.DY in SAT. else
raiseapplicationerror .jobMANAGER begin if inserting then new. END IF.U canot do ant DML
operation during lunch time .DY in SAT.HHMM into a from dual .HHMI not between and then
raiseapplicationerror .comm . begin select tocharsysdate. create or replace trigger lunch
before insert or update or delete on emp declare a varchar.You may insert into emp table
only during businees.You may updating emp table only during businees. no negative salary
allowed. end .comm . .You may deleting emp table only during businees. elsif old. Restricting
a ROW triggers create or replace trigger derivecommpct after insert or update or delete on
emp for each row WHEN new. end if . elsif inserting then raiseapplicationerror .You may
update into emp table only during businees. if a between and then raiseapplicationerror. .
end if. create or replace trigger secureemp before insert on emp begin if
tocharsysdate.comm old. elsif updating SAL then raiseapplicationerror . end if.comm .
new. NEWSALARY NUMBER. old.empno. new. Trigger ROW LEVELUsing old and new
qulaifier create table auditemptable USERNAME VARCHAR.sal. end.ename.Trigger ROW
LEVELUsing old qualifier create or replace trigger restrictsalary before insert or update of sal
on emp for each row begin if not new.dddd.Employee cannot earn this amount .ID.
NEWTITLE VARCHAR.job from emp . Trigger ROW LEVEL Using as Instead of Trigger
INSTEAD OF Triggers Use INSTEAD OF Triggers to modify data in which the DML
statement has been issued against an inherently nonupdateable view. create or replace
trigger auditempvalues after insert or update or delete on emp for each row begin insert into
AUDITEMPTABLE USERNAME. select from auditemptable .sal gt then
raiseapplicationerror.sal.TIMESTAMP. Syntax for Creating an INSTEAD of Trigger CREATE
OR REPLACE TRIGGER triggername INSTEAD OF events or event or event ON viewname
Referencing create table newemp as select empno.MANAGER.job.
NEWLASTNAME.ename.ename.deptno values ..ename.NEWSALARY values user. ID
VARCHAR.. TIMESTAMP DATE.deptno. OLDTITLE VARCHAR.sal.CLERK and new.
OLDSALARY NUMBER.OLDLASTNAME. These triggers are called INSTEAD OF triggers.
old. old. new.sal. OLDLASTNAME VARCHAR. sysdate.hiredate. insert into emp empno. end.
end if .job. . old.job in MANAGER.NEWTITLE. . NEWLASTNAME
VARCHAR.OLDTITLE.OLDSALARY.job.
new.deptno .empno . sumd.deptnod. update newdepts set totdeptsal totdeptsal
new.e.ename.job .ename.sal where deptno new.e.deptno .sal where deptno old.dept d
where e..e.create table newdepts as select e.d.sal totdeptsal from emp d. end if .sysdate.
create or replace trigger newempdet instead of insert or update or delete on empdetails for
each row begin if inserting then insert into newemps new. elsif deleting then delete from
newemps where empno old. .deptno.d.empno. create table newdept as select
deptno.dddd.Deptno .sal.loc from emp e.deptnoe. update newdepts set totdeptsal totdeptsal
new. insert into newdept values new. elsif updating deptno then update newemps set deptno
new.sal.sal where deptno new.empno .d.empno.dname . create table NEWEMP as select
empno. update newdepts set totdeptsal totdeptsal . MANAGING TRIGGERS Alter trigger
triggername Disable enable .new..new. update newdepts set totdeptsal totdeptsal .deptno
from emp .new.dname.deptno.empno..sal where empno new.deptno group by
e.old.dname.ACCOUNTING . dept d where d.dname from emp e . end.new.sal where deptno
new.empno.empno.old. create view empdetails as select
e.new.deptno.deptno.job.ename.old. insert into EMPDETAILS values .deptno . Alter table
tablename Disableename ALL triggers .ename.deptno. create or replace trigger instrigs
instead of insert on empdeptview begin insert into newemp values new.sal .ename.ffff .new.
elsif updating sal then update newemps set sal new. dept e where
d.deptnoe.MANAGER.e.sal where deptno new.dname from dept .e. values update newdepts
set totdeptsal totdeptsal new. Drop trigger triggername .e.suresh. create view empdeptview
as select e.deptno .e.deptno.e. end . insert into empdeptview values .dname .deptno .deptno
.deptno where empno old.deptno .
A specific error or any error being raised. end.Shutting down or starting up the database
.Logging On . ACTION VALUES user.sysdate. user has created an object at LOGON and
LOGOFF Trigger Example create table LOGTRIGTABLE USERID varchar. ACTION .
Creating Trigger on DDL Statements These Trigger will be fired implicitely whenever user
performs any DDL operations like create.LOGDATE.Logging on or off Triggering database or
system event . ACTION varchar . ALTER or DROP . create or replace trigger logontrigs
AFTER LOGON ON SCHEMA BEGIN INSERT INTO LOGTRIGTABLE USERID.dd/mm/yyyy
hhmiss . LOGDATE date. After create Create or replace trigger ddltrigger after create on
schema begin insert into auditobjectsuse values tocharsysdate.Creating Database Triggers
Triggering user Events .U cannot create a table end. alter or dropping an object The Syntax
is Create or replace trigger lttriggername Beforeafter DDL statement on schema PL/SQL
Block Example Before create Create or replace trigger ddltrigger Before create on schema
begin Raiseapplicationerror. end. create or replace trigger logofftrigs before LOGOFF ON
SCHEMA BEGIN INSERT INTO LOGTRIGTABLE USERID.CREATE.LOGDATE.
Viewing Trigger Information You can view the following trigger inormation by using
USERTRIGGERS SQLgt select triggername..filetype.VALUES user. vname substrvstring.
vname varchar. triggeringevent. vstring varchar. end. . flat. flat.fopenC. .vstring. loop utlfile.to
create flat file .W . status.W . insert into person code.Logging Off . commit . end loop .name
values vcode. triggertype.It is a DB Package . tablename.Used for . exception when
nodatafound then utlfile.. vcode substrvstring.txt. . loop utlfile.vname . vcode substrvstring.
create or replace procedure proca as vfileid utlfile.sysdate. .It do validation also FOPEN
FCLOSE GETLINE NEWLINE PUT Datatype Filetype create or replace procedure proca as
vfileid utlfile.getline vfileid.to load data into Oracle DB from flat file . begin vfileid utlfile. vcode
varchar.filetype. vname varchar. Referencingnames. vname substrvstring. end . vcode
varchar.vstring.fclosevfileid . triggerbody from USERTRIGGERS Where
triggernameCHECKSALARY.fopenC.name values vcode. File Input/Output I/O UTLFILE .
.getline vfileid. begin vfileid utlfile.txt. select from LOGTRIGTABLE .vname ... vstring varchar.
insert into person code.
checks the statementss syntax and associates it with the opned cursor DDL statement are
immediately executed when parsed Binds the given value to the variable identified by its
name in the parsed statement in the given cursor Executes the SQL statement and returns
the number of rows processed Retrives a row for the specified cursor for multiple rows.
Oracle Supplied Packages Oracle Supplied Package Are provided with the Oracle Server
Extend the functionality of the database Enables access to certain SQL features normally
restricted for PL/SQL.PARSEcursorname. end loop .Enables generalpurpose code to be
written .dbmssql. . call in a loop Closes the specified cursor create or replace procedure
deleteallrows ptabname in varchar. .Enables datadefination.DELETE From
Ptabname.closecursorcursorname .Is a SQL staement with placeholders abd is stored as a
character string. DBMSSQL. Some of the procedures and functions of the package includes
OPENCURSOR PARSE BINDVARIABLE EXECUTE FETCHROWS CLOSECURSOR
Componets of the DBMSSQL Package Function or Porcedure OPENCURSOR PARSE
BINDVARIABLE EXECUTE FETCHROWS CLOSECURSOR Description Opnes a new
cursor and assigns a cursor ID number Parses the DDL or DML ststements that is. exception
when nodatafound then utlfile. begin cursorname DBMSSQL. . datacontrol or sessioncontrol
statements to be written and executed from PL/SQL. Using the DBMSSQL Package The
DBMSSQL package is used to write dynamic SQL in stored procedures and to parse DDL
statements. prowsdel out number is cursorname integer.native .EXECUTEcursorname
.commit .opencursor . DBMSSQL.Is written using either DBMSSQL or native dynamic SQL.Is
a SQL statement that contains variables that can change during runtime .fclosevfileid . Using
Native Dynamic SQL . prowsdel DBMSsql. end .
COALESCE expr.. exprn END select comm. comm. End . . SQLgt variable a number SQLgt
execute delrows EMP. a SQLgt print a Using DBMSJOB for Scheduling DBMSJOB enables
the scheduling and execution of PL/SQL programs Submitting jobs Executing jobs Changing
execution parameters of jobs Remove jobs Suspending Jobs New SQL function in Oracle i
COALESCE You can also use COALESCE as a variety of the CASE expression. prowsdeld
out number IS Begin Execute immediate delete from ptablename .. Dynamic SQL Using
EXECUTE IMMEDIATE Create procedure delrows ptablename in varchar. for ngt is
equivalent to CASE WHEN expr IS NOT NULL THEN expr ELSE COALESCE expr. from
emp .. For example. Prowsdeld SQLROWCOUNT .. .end. in a value in the Gregorian
calendar of datatype DATE. COALESCE expr.. . expr.. CURRENTDATE Purpose
CURRENTDATE returns the current date in the session time zone.comm.
exprn.COALESCE. expr is equivalent to CASE WHEN IS expr NOT NULL THEN expr ELSE
expr END Similarly.
then the default is . SESSIONTIMEZONE CURRENTTIMESTAMP . APR . take care that the
format mask matches the value returned by the function. APR . SELECT
SESSIONTIMEZONE.Examples The following example illustrates that CURRENTDATE is
sensitive to the session time zone ALTER SESSION SET TIMEZONE . SELECT
SESSIONTIMEZONE. In the optional argument. CURRENTTIMESTAMP FROM DUAL.
consider the following table CREATE TABLE currenttest col TIMESTAMP WITH TIME
ZONE... If you omit precision. AM If you use the CURRENTTIMESTAMP with a format mask.
SESSIONTIMEZONE CURRENTDATE . SELECT SESSIONTIMEZONE. MAY
CURRENTTIMESTAMP Purpose CURRENTTIMESTAMP returns the current date and time
in the session time zone. ALTER SESSION SET NLSDATEFORMAT DDMONYYYY
HHMISS. For example.. precision specifies the fractional second precision of the time value
returned. PM ALTER SESSION SET TIMEZONE . in a value of datatype TIMESTAMP WITH
TIME ZONE. The difference between this function and LOCALTIMESTAMP is that
CURRENTTIMESTAMP returns a TIMESTAMP WITH TIME ZONE value while
LOCALTIMESTAMP returns a TIMESTAMP value. The time zone offset reflects the current
local time of the SQL session. MAY ALTER SESSION SET TIMEZONE .
SESSIONTIMEZONE CURRENTTIMESTAMP .. . CURRENTTIMESTAMP FROM DUAL.
CURRENTDATE FROM DUAL. Examples The following example illustrates that
CURRENTTIMESTAMP is sensitive to the session time zone ALTER SESSION SET
TIMEZONE . SESSIONTIMEZONE CURRENTDATE . ALTER SESSION SET
NLSDATEFORMAT DDMONYYYY HHMISS. CURRENTDATE FROM DUAL. SELECT
SESSIONTIMEZONE.
The following statement fails because the mask does not include the TIME ZONE portion of
the type returned by the function INSERT INTO currenttest VALUES
TOTIMESTAMPTZCURRENTTIMESTAMP. query the VTIMEZONENAMES dynamic
performance view. emp WHERE EXTRACTYEAR FROM . the value returned is a string
containing the appropriate time zone name or abbreviation. ENAME EMPNO HIREDATE .MI.
DDMONRR lt ORDER BY hiredate. the value returned is in UTC.MI. When you extract any of
the other values. The following statement uses the correct format mask to match the return
type of CURRENTTIMESTAMP INSERT INTO currenttest VALUES TOTIMESTAMPTZ
CURRENTTIMESTAMP. EXTRACT DATETIME Purpose EXTRACT extracts and returns the
value of a specified datetime field from a datetime or interval value expression. SELECT
EXTRACTYEAR FROM DATE FROM DUAL.SSXFF PM. If only one row ranks as FIRST or
LAST. When extracting from a datetime with a time zone value. DDMONRR HH. the
aggregate operates on the set with only one element.. empno. This function takes as an
argument any numeric datatype or any nonnumeric datatype that can be implicitly converted
to a numeric datatype. hiredate FROM TODATEhiredate. The function returns the same
datatype as the numeric datatype of the argument. 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. the value returned is in the Gregorian calendar.
EXTRACTYEARFROMDATE The following example selects from the sample table hr. When
you extract a TIMEZONEREGION or TIMEZONEABBR abbreviation.employees all
employees who were hired after SELECT ename. For a listing of time zone names and their
corresponding abbreviations.suresh JAN SMITH DEC ALLEN FEB WARD FEB FIRST
Purpose FIRST and LAST are very similar functions. DDMONRR HH.SSXFF PM TZHTZM.
as indicated by a jobid in the jobhistory table different from the current jobid in the
employees table SELECT e. then the function returns null. then they must be of the same
datatype. If they are equal. or Oracle returns an error..ename. NULLIFe. DEPTNO Worst
Best . then the function returns expr. If they are not equal. j. MAXsal KEEP DENSERANK
LAST ORDER BY comm quotBestquot from emp group by deptno . the FIRST and LAST
functions eliminate the need for self joins or views and enable better performance. jobhistory
j WHERE e. and returns that datatype. ENAME Old Job I .ADAMS ALLEN BLAKE CLARK
FORD ggggg suresh Program . If the arguments are not numeric.empno j. implicitly converts
the other argument to that datatype. but the needed value is not the sort key. NULLIF
Purpose NULLIF compares expr and expr.job. select deptno.empno ORDER BY
ename.When you need a value from the first or last row of a sorted group. If both arguments
are numeric datatypes. You cannot specify the literal NULL for expr. then Oracle Database
determines the argument with the higher numeric precedence. minsal KEEP DENSERANK
FIRST ORDER BY comm quotWorstquot.job quotOld Jobquot FROM emp e. The NULLIF
function is logically equivalent to the following CASE expression CASE WHEN expr expr
THEN NULL ELSE expr END Examples The following example selects those employees
from the sample schema hr who have changed jobs since they were hired.
In an object table. CREATE TYPE personty AS OBJECT name vachar. the chance of
reusing previously written code modules is increased.If OO code is written. state varchar.
major object types are described. In the following sections. Similarly. Minimizing cost through
reusibility Oracle provides full support for all three different implementation Relational. then
the chances they will be used increase exponentially. CREATE TYPE addressty AS OBJECT
Street varchar.Oriented Relational. Standard adherence. the columns of the table map to the
columns of an abstract datatype. ObjectRelational. zip number . An abstract data type can be
used to create an Object Table. CREATE TYPE personty AS OBJECT name vachar. then a
de facto standard for application of tables is being created. and VARCHAR. If multiple
applications or tables use the same set of database objects. state vachar. city varchar.
Abstract Data type Abstract Data type is a datatype that consists of one or more
subtypes.Represent real thing as objects Object Technology is a method of managing
complexity so that we can develop solutions that simulate realworld problems. address
addressty . address addressty . Object. objects may help in other ways. Examples of benefits
that come from using OO features are Object reuse . city varchar. Besides simplifying the
interaction with data. Creation of an Object CREATE TYPE addressty AS OBJECT Street
varchar. the abstract data type can more accurately describe data. DATE.Model real Thing .
Why Should Objects Be Used Objects reduce complexity by giving an intuitive way of
representing complex data and its relations. OBJECT TYPES Oracle supports many different
types of objects. zip number . if OO database objects are created the chances that these
database objects will be reused in increased. .If database objects are built using
standards.Implementing Object Techniques Object Technology Object Technology is another
step forward in the software enginnering life cycle that allows us to . Rather that being
constrained to the standard Oracle data type of NUMBER.
the array is a nested table a limited set of rows Varying Arrays. Object views allow the
development of OO features within a relational database. Thus.CREATE TABLE customer
customerid number. A nested is a collection of rows. it is an object that is treated as a
column in a table. person personty Retrieving Data using Objects SELECT client. city
varchar. Another type of object.person. Varying Arrays A varying array is a set if objects.
When a table is created with a varying array. They are physically embedded within another
object. Nested Tables A nested table is a table within a table. represented as a column within
the main table.Address.cityMumbai where Client.Name Client. A row object is different from
a column object. In one sense.addess. object views give the benefits of relational table
storage and OO structures. For each record within the main table.person. CREATE TABLE
customer . on the other hand. Object views Object views allow adding OO concepts on top of
existing relational tables. a kind of bridge between the relational and OO worlds. References
Nested tables and Varying Arrays are embedded objects.city like M .person.addess. A row
object. Updating Data using Objects UPDATE customer client SET client. CREATE TYPE
addressty AS OBJECT Street varchar.cityMumbai .Person. its a way of storing a onetomany
relationship within one table. The size of the array is limited when it is created. References
also known as REFs are essentially pointers to row objects. each with the same data type.
zip number . called referenced objects.CityChennai . For example. state varchar. Deleting
Data using Objects DELETE from customer client where client. always represents a row.City
FROM customer client WHERE client. the nested table as a column. address addressty .
allows storing repeating attributes in tables. also known as VARRAYS. References are
typically among the last OO features implemented when migrating a relational database to
an objectrelational or pure OO one.Person.address. An example of a column object would be
a varying array.Address.Person. an abstract data type can be created based on an existing
table definition. CREATE TYPE personty AS OBJECT name varchar. are Physically
separated from the objects that refer to them.
but takes more space. person personty . REF scope can be set at either the column or table
level. address companyaddressty. SCOPE clauses prevent dangling references. because an
unscoped REF can refer to any accessible object table. Relational tables however. For
example. Varying arrays are collectors that allow repetition of only those column values that
change.e. this can be used as a part of the creation of either a table or an abstract datatype
Create table companyinfo companyname varchar. An OID is a bytes base number. i. A
scope clause in a definition forces a set of REFs for a given column to be confined to a single
object table. which contains an embedded object called address that is a varray of type
companyaddressty. and to allow the user to select that object. To get the value stored in the
.state. This statement creates a varray type called companyaddresstyp. have difficulty.
VARIABLE ARRAYS A varying array allows the storing of repeated attributes of a record in a
single row. This data type acts as a pointer to an object. each storing address information for
the company. There can be only one REF clause for a given REF column. If with ROWID is
not specified with the REF clause. 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. as they will not
allow REF values unless the corresponding entries in the SCOPE table is present. much the
same way as a primarykey/foreignkey relationship in relational tables.customerid number.
ORCLE stores the varying array data internally using the RAW datatype. create view custobj
of addressty with object oid customerid as select customerid. Storing a REF with a ROWID
seeds dereferencing operation. which is not very useful except as handle to the object
instance. A call to a REF returns the OID of the object instance. Now that the varying array
companyaddressty is created.persontyname. if more than one table is needed in a
primarykey/foreignkey relationship related to a single table. potentially saving storage space.
this SQL statement creates a table called companyinfo. the default is to not store ROWIDs
with the REF values.city. entries per record. The use of REFs eliminates this problem. an
address table. A REF is used primarily to store an object identifier. which can hold a
maximum of elements of data type varchar.zip from customer . REF columns can be added
to nested tables with the ALTER TABLE command. REF values can be stored with or without
a ROWID. REFs establish relationship between twoobject tables. CREATE TYPE
COMPANYADDRESSTY AS VARRAY OF varchar . that stores addresses from several
entities. A REF can also be used in a manner similar to a foreign key in a
RDBMS.addresstyStreet. Reference object The referencing object REFs data type is
something that is new to ORACLE i.
prodid GROUP BY t.dmp logfilename. the DEREF routine is used.prodid. p. Oracle Utilities
Export A backup utility provided by Oracle Writes data from an Oracle database into Oracle
binaryformat 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 Tables Level Export
Cgt exp username/passward Tablestablename.prodid s. The time in the past to which the
table can be flashed back is dependent on the amount of undo data in the system.timeid s.
SUMs. The FROM clause of the query can name tables.calendaryear.log ownerusername
Entire Database Level Cgt exp system/manager filefilename.instance that is referred to by a
REF. DEREF returns values in the object instance referenced by a specific REF value. sales
s WHERE t. Some advance features in Oracle i MATERIALIZED VIEW A materialized view
is a database object that contains the results of a query.prodid. Collectively these objects are
called master tables a replication term or detail tables a data warehousing term. views.timeid
AND p. products p.log fully Import Is used for importing data exported using the exp
command into the Oracle database . p. FLASHBACK TABLE Purpose Use the FLASHBACK
TABLE statement to restore an earlier state of a table in the event of human or application
error. This reference uses quotmaster tablesquot for consistency.dmp logfilename.tablename
filefilename. The databases containing the master tables are called the master databases
CREATE MATERIALIZED VIEW salesmv REFRESH FAST ON COMMIT AS SELECT
t.amountsold AS sumsales FROM times t. and other materialized views.
Also.calendaryear.dmp logfilename.log User Level Export Cgt exp system/manager
filefilename. Oracle Database cannot restore a table to an earlier state across any DDL
operations that change the structure of the table.
txt To create multiple table in a SINGLE SQL Query Create schema authorization sss Create
table a a number Create table b a number.log fromuser username touserusername Sql
Loader This tool is used to move data from a NonOracle standard source into the Oracle
Database Load data into multiple datafiles by Sql Loader .dmp logfilename.tablename
Importing User Cgt Imp system/manager filefilename.log Tablestablename.txt MILLER
FORD step .dmp logfilename.create a control file load data ex .Importing tables Cgt Imp
username/passward filefilename. Where SSS is the User Name Oracle Architecture In Every
Oracle Server consists of an Oracle Instance and Database . name varchar.txt infile ltfile
location of the data filegt into table person code position char. . cgt sqlldr useridsss/sss
controlcctrl.create a table ex create table person code number. . setp . name postion char
step .create a data file ex test. Background Process is two types Mandatory Optional
Mandatory are Process Monitor PMON .sqlldr step .ctrl. An Oracle Instance is the
combination of System Global AreaSGA and the Background Process.
first it reads from the parameter file. the Program Global Area PGA contains data such as
users session variables and arrays for use only by a single process. Its contents is
visible/accessible to several user applications and system processes. There must be atleast
some parameter require to start. Control File It Stores the crushial information about the
database like . Its contents is not visible to other processes unless Oracle multithreaded
server MTS is used. Program Global Area PGA When singlethreaded servers are used.
Password File Password file is required to connect database remotely from one serever to
another server.Location of each data files . It stores the redo entries Atleast two files is
required and the size should be in KBs. .ora Redo Log file It stores the changed information
made by the Redolog buffer Cache by the help of Log Writer LGWR. Such as Database
Name Control File Location Whether Rollback Segmnet or Undo Management
Background/User/Core Dump Location etc.Name of each data files . System Monitor SMON
Database Writer DBWR Log Writer LGWR Checkpoint CKPT Optional are Oracle Parallel
Query Option OPQO Multi DBWR Archiver ARCH Recoverer Reco Oracle Database consists
mainly these files Redo Log File Control File Data File Parameter File Initialisation File init.
.Block Id New Contents Data file .The actual data stores in the data file. The file size should
be in MBs or GBs or may be TBs..No of data files . System Global Area SGA The Shared
System Global Area SGA contains user data and control information for a single Oracle
Instance.Database original creation date Parameter File While datatabase is starting. what
parameter u have set in the database.One data file belongs only one Tablespace. It contains
File Id.
Shared SQL Pool When an SQL statement is issued by a user process. such as bind
variables. and so on. it goes through a parse tree in the shared pool. The shared pool
contains the library cache. Oracle uses a Shared SQL area to save in cache the intermediate
results from SQL commands previously returned. It contains information such as user
account data. So before performing a hard disk operation. This is done for efficiency .
Database Buffer Cache The data block buffer stores the most recently queried data from the
database. Each private area is deallocated after the cursor to the session is closed. It
contains sessionspecific information. Its size is controlled by the variable
DBBLOCKBUFFERS parameter. Data Dictionary Cache This area saves the rereading of
data from the Dictionary Table on a hard disk referenced while parsing SQL statements. the
persistent area contains information that is valid and applicable through multiple executions
of the SQL statement. extent locations. The vlibrarycache view lists performance information
for each type of object in the library cache. the shared area contains the parse tree and
execution path for SQL statements. Oracle can service identical requests simply by retrieving
them from its cached memory for reuse. Within the private SQL area of the library cache.
segment names. To improver Oracle performance. Specifically.ora parameter. contains
library cache performance information for each type of object in the library cache. and
Privileges. which has a value calculated from the size of about . It contains information such
as segment information. data dictionary cache. The number of private SQL areas a user
session can have open at one time is limited by the value of the OPENCURSORS init.to
avoid timeconsuming hard disk operations. datafile names. It also contains headers of
PL/SQL packages and procedures that have been executed. runtime stacks and buffers. A
private SQL area is created for each transaction initiated. security and access privileges.
environment and session parameters. table descriptions. The runtime area contains data that
is used only while the SQL statement is being executed. execution plan and parse tree for
SQL statements. Library Cache The Library Cache contains both shared and private SQL
areas. and available free storage space.
Database Writer DBWn The Database Writer DBWR writes and retrieves blocks from
datafiles through the buffer cache. If the command shutdown abort is issued by the user. It
releases locks held by processes which failed before they released memory allocations. to
percent of the database. The number of redo log space requests can be monitored using the
vsysstat view.ora specifies the maximum number of processes accessing the database. It
wakes itself up routinely to clean up free space in datafiles much like a defragmenter for hard
drives. performs quotgarbage collectionquot. disk blocks and memory blocks accessed while
executing the statement. Redo Log Buffer Cache The redo log buffer is used to store redo
information in memory before it is flushed to the Online Redo Log Files. and restarts failed
processes in the database. PMON analyzes user processes that access the database. The
Vbgprocess view lists all background processes. User and Server Processes Snnn
Applications and utilities access the RDBMS through a user process. including background
and user processes. which can be dedicated to one user process or shared by many user
processes. It is also the process that reads data blocks from the data files into the database
buffer cache. The server process parses and executes SQL statements that are submitted to
it and returns the result sets back to the user process. Oracle doesnt have time to write
modified database changes from the System Global Area SGA down to disk. Process
Monitor PMON The Process monitor performs recovery such as releasing locks failed
processes held on resources. . The vprocess view displays all processes that are connected
to the database.required for startup of each Oracle instance System Monitor SMON The
System monitor performs automatic crash recovery on the Oracle instance in the event it
fails. Four background processes are mandatory . System Background Processes The
PROCESSES parameter in init. and other information. Its size is initialized according to the
LOGBUFFER bytes parameter. Large Pool Introduced with Oracle to store user session
global area infor and for parallel processing/recovery. This space is managed by latching and
writing the Least Recently Used LRU block to hard disk. Some suggest using the
DBWRITERS parameter to define as many DBWR processes as there are physical disks
used to store data files. The vsqlarea view displays the text of SQL statements in the shared
SQL area. The user process connects to a server process. It looks for free spaces and
organizes them into contiguous areas. plus the number of users accessing the statements.
it updates all the data and control files with the new log file control number. User trace
Database trace startup and other commands and responses to commands to a database are
stored in an Alert Log. This process is optionally enabled if parameter
CHECKPOINTPROCESS contains a TRUE value. Redo log files are achived to tape or other
media by the ARCH background process.. the database will hang. If the database is
operating in archivelog mode AND the ARCHIVELOGSTART parameter in the init.ora file is
not set to TRUE. The varchive view provides information on the archived logs written by
ARCn ARCH pre Oraclei. Trace Writer TRWR The operating system Process ID for each
running process are maintained in a trace file located in the file name specified in parameter
BACKGROUNDDUMPDEST. Archival Process ARCn The full online redo logs are copied to
the archived redo log files by this process.Log Writer LGWR The Log Writer writes and
retrieves its blocks from datafiles through the Redo Log Buffer. At a specified time. It is a
background process that monitors the number of dirty buffers that have not been written to
disk. In Oracle i. it also gives the DBWR a wakeup call to write dirty buffer to disk. the
DBWRIOSLAVES parameter defines the number of I/O slaves to improve performance. Alert
Logs Database startups and other commands and responses to commands to a database
are stored in an Alert Log. Other background system processes .. Depending on the
LOGCHECKPOINTINTERVAL parameter. Checkpoint Process CKPT The checkpoint CKPT
process frees up limited memory space and ensures instance recovery. . By default. thats
folder /admin/INSTANCENAME/bdump under the ORACLEBASE folder.