Sunteți pe pagina 1din 56

1. What is Normalization?

Ans: Normalization is the process of organizing the tables to remove the redundancy. There are mainly 5 Normalization
rules.

1st Normal Form: A table is said to be in 1st normal form when the attributes are atomic and there is no repeating groups
2nd Normal Form: A table is said to be in 2nd Normal Form when it is in 1st normal form and all the non-key columns are
functionally dependant on the primary key. .
3rd Normal Form: A table is said to be in 3rd Normal form when it is in 2nd normal form and all non key attributes not
dependant transitively.
4th Normal Form: A table is said to be in 4th normal form when it is in 3rd normal form and has no multi -valued
dependencies.
5th Normal Form: A table is said to be in 5th normal form when it is in 4th normal forma and every join dependency for the
entity is a consequence of its candidate keys.

2. What is the Purpose of the Distinct Clause in SQL?

Distinct Clause allows you to display unique from the result set. This can be used with only select statements.

3. What are the DDL Commands and the Purpose of these commands?
DDL (Data Definition Language) command is used for defining the structure of the Data. DDL Statements are auto
commit.
• CREATE - to create objects in the database
• ALTER - alters the structure of the database
• DROP - delete objects from the database
• TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed
• COMMENT - add comments to the data dictionary
• RENAME - rename an object
4. What are the DML commands and Use Of these commands?

DML (Data Manipulation Language) statements are used for managing data within schema objects.
• INSERT - insert data into a table
• UPDATE - updates existing data within a table
• DELETE - deletes all records from a table, the space for the records remain
 DML Statements can be roll backed.
 DML Statements can’t be roll backed When DDL Statement Executed immediately after the DML statement.
5. What are the DCL Commands and purpose of it?
DCL is Data Control Language statements.
o GRANT - gives user's access privileges to database
o REVOKE - withdraw access privileges given with the GRANT command

6. What are the TCL Commands and Purpose of it?

(Transaction Control Language) Manages the changes made by DML statements. These commands allow statements to
be grouped together into logical transactions.
o COMMIT - save work done
o SAVEPOINT - identify a point in a transaction to which you can later roll back
o ROLLBACK - restore database to original since the last COMMIT
7. What is the Difference between TRUNCATE and DROP?
Truncate Delete the entire data from the table and keeps the structure.
TRUCATE TABLE table name
DROP drops the table structure also.
DROP TABLE Table name
8. What is the Difference between TRUNCATE and DELETE?

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 1
TRUNCATE DELETE
It’s DDL Statement It’s DML Statement
Auto commit, we can’t retrieve the data back we can Retrieve the data back
We can delete entire rows (No condition) we can delete rows conditional wise

9. What is NULL?
NULL in Oracle is an Absence of information. A NULL can be assigned but not evaluated by it self also.
 NULL not equal to null
 NULL Can not be Not equal to NULL (Neither Equal Not Not Equal)
 NULL Does not equal to empty String or doe not equal to ZERO.

10. How can we sort the rows in SQL?

We can Sort the rows Using ORDER By clause.


- ASC : Ascending Order is Default order
- DESC : Sorting in Descending
 Null Values Displayed At last in ascending Order

11. How can we convert NULL Value?


Using NVL Function we can convert Null Value to an Actual Value.
NVL(exp1, exp2).
If exp1 is NULL then it returns the exp2.

12. Purpose and Syntax of NVL2 ?

Convert the Null values in to Actual Value.


NVL2 (Exp1,exp2,exp3). If exp1 is NULL it returns the exp3 . if exp1 is not null then it returns the exp2.

13. When Cartesian product formed?


• A join condition Omitted
• A Join condition Invalid
 To Avoid Cartesian Product, always include Valid Join condition

14. What type of joins using in SQL?

1) EQUI JOIN: The equi join is normally used to join tables with primary key foreign key relation ships.
2) NON-EQUI JOIN:
A join condition where any relation operator other than "=" equal to
operator is used.
3) OUTER JOIN:
In EQUI JOIN rows that does not satisfy specified condition would not be displayed. Example: consider EMO and DEPT
table as Example
DEPTNO 40 is not displayed in the Equi example because there are no employees in it. If we want to diplay its detail also
then we have to use OUTER JOIN.Otherwise OUTER JOIN is imilar to EQUI JOIN except for the difference it uses outer
join (+) operator. (A plus within parenthesis) towards the side not having required data. Outer join operator will substitute
null values when there are no values available.
SQL> SELECT E.DEPTNO,ENAME,DNAME FROM EMP E , DEPT D
2 WHERE E.DEPTNO (+) = D.DEPTNO;
4) SELF JOIN:
When we join a table to itself it is called self join.To join a table itself means that each row of the table is combined with
itself and with every other row of the table. The self join can be seen as join of two copies of the same table.

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 2
SQL> SELECT E.ENAME,M.ENAME FROM EMP E,EMP
WHERE E.MGR=M.EMPNO;
15. What are the Group Functions?
Group Functions Operate on Sets of rows to give one result per group. The types of group functions
AVG,COUNT,MAX,MIN,SUM,STDDEV,VARIANCE

 All columns in SELECT List that are not in group functions must be in the GROUP BY clause.

16. Can you Use Group functions in the Where Clause?

NO, We Can’t.
17. How can we restrict the Group Results?

Using HAVING Clause. We can’t use WHERE for these results.


18. What is difference Between SUBQUERY and CORRELATED SUBQUERY?

SUBQUERY :
A query within another quey. A select statement whose output is substituted in the condition of another select
statement .(A query is a statement written for returning specific data). The subquery is executed only once. A subquery is
enclosed in parenthesis.
EX: SQL> SELECT ENAME FROM EMP
WHERE DEPTNO = (SELECT DEPTNO FROM EMP
WHERE ENAME = 'SMITH');
CORRELATED QUERY:
In a correlated subquery the table used in outer query refers to the table used in the inner query. The correlated
subquery is executed repeatedly once
for each row of the main query table.
Query to display name of highest salary taker.
SQL> SELECT EMPNO, ENAME FROM EMP A
WHERE 1 > ( SELECT COUNT(*) FROM EMP B
WHERE A.SAL < B.SAL)

19. What are the Multiple-Row comparisons Operators?

IN :EQUAL to any member in the list.


ANY : Compare value to each value returned by the sub query
ALL :Compare Value to Every value returned by the sub query.

20. You are updating the table, you ask some another user to logon to database to check your changes before you issue
the commit command ? Can he see the changes done by you?

Another user can’t see the the changes done by you until you have given commit.

21. What is MERGE Statement do?

Provides the ability to conditionally update or insert data into a database table.
Performs update if the row exists and an insert if it is a new row.

22. What is the Use of SAVEPOINT?


A SAVEPOINT is a marker within a transaction that allows for a partial rollback. As changes are made in a
transaction, we can create SAVEPOINT to mark different points within the transaction. If we encounter an error, we can
rollback to a SAVEPOINT or all the way back to the beginning of the transaction.

Ex : Insert Statement

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 3
SAVEPOINT A
UPDATE Statement
SAVEPOINT B
DELETE Statement
SAVEPOINT C
Roll Back to SAVEPOINT B (means it roll backs to till UPDATE statement)

23. What is the Use of ALTER Statement?

To Add new column


To modify the datatype and size of the existing column
To Drop a column

24. What are the Difference between UNION and UNION ALL?

UNION Query displays the Unique rows ( No duplicate rows)


UNION ALL Query displays the Duplicate rows also.

25. If you a Table A, You want to create table B having the same fields in TABLE A ? That means you have to copy only
structure not the data?

CREATE TABLE TABLEB AS (SELECT * FROM TABLE A where 1=2);

26. What is Synonym?


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

27. What is view?


A View is a virtual table ,it does not physically exist rather , it is created by a query joining one or more tables.

28. Can we Update the Data in View?


A view is created by joining one or more tables. When you update record(s) in a view, it updates the records in the
underlying tables that make up the view.
So, yes, you can update the data in a view providing you have the proper privileges to the underlying tables.
29. What is Sequence?
Sequence is for generating auto number field. This can be useful when you need to create a unique number to act as
primary key.
Syntax:
CREATE SEQUENCE sequence_name
MINVALUE value
MAXVALUE value
START WITH value
INCREMENT BY value
CACHE value;
30. How do we set the LASTVALUE value in an Oracle Sequence?
You can change the LASTVALUE for an Oracle sequence, by executing an ALTER SEQUENCE command.
31. What is pseudo columns ? Name them?
A pseudocolumn behaves like a table column, but is not actually stored in the table. You can select from pseudocolumns,
but you cannot insert, update, or delete their values. This section describes these pseudocolumns:
* CURRVAL
* NEXTVAL
* LEVEL
* ROWID
* ROWNUM

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 4
Rowid
Rowid is pseudo column that uniquely identifies a row with in the table but not with in the database.
It is possible for two rows of different tables stored in the same cluster have the same row id.
Connect By Prior
A condition that identifies the relationship between parent rows and child rows of the heirarchy.

Level
For each row returned by heirachical query the level pseudo columns returns 1 for root row , 2 for child row of the root
and so on.

32. How many columns can table have?


The number of columns in a table can range from 1 to 254.
33. How many rows and Columns in DUAL table?
One Row and One Column Only
34. What is the Use of CASE and DECODE?
CASE and DECODE statements Both perform procedural logic inside a SQL statement without having to resort to
PL/SQL.
Syntax:
DECODE (F1,E2,E3,E4) { If F1=E2 Then E3 else E4}
Syntax:
CASE
WHEN E1 THEN E2 {If E1 True E2 Else E3 CASE evaluated the Expression only once with
ELSE E3 that result values be compared}
END

 It is Best to use CASE Statement when comparing ranges or more complex logic

35. What is Inline View?

SQL Statement in the FROM clause of SQL statement called Inline View. Oracle treats the data set that is returned from
the inline view as if it were a table.
This is not a schema Object.
A common use for inline views in oracle sql is to simplify the complex queries by removing join operations and
condensinfg several separate queries into single query.

SELECT * from (SELECT * from table);

36. What is the Purpose of Index?


SQL indexes are used because they can provide the following benefits / functions:
• Rapid access of information
• Efficient access of information
• Enforcement of uniqueness constraints

CREATE INDEX (Index_name) on TABLE_NAME(Field1,field2);

37. What are Constraints? And what are the constraint Types?

 Constraints Enforced rules at the table level.


 Constraints prevent the deletion of a table if there are decencies.

Following are the Constraint Types

NOTNULL:

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 5
Ensures the null values are not permitted for the column. Defined at column Level.

CREATE TABLE Tablename( Empname VARCHAR2(10) NOTNULL)

UNIQUE:
Not allow already existing value
Is defined either table level or column level

CREATE TABLE T1( X1 NUMBER,


X2 VARCHAR2(10),
CONSTRAINT x2_UK UNIQUE(X2))

PRIMARY KEY:
Doesn’t allow Nulls and already existing values.
CREATE TABLE T1( X1 NUMBER,
X2 VARCHAR2(10),
CONSTRAINT x2_UK PRIMARY KEY(X2))

FOREIGN KEY:
Foreign Key defines the column in the child table at table constraint level.

CREATE TABLE T1( X1 NUMBER,


X2 VARCHAR2(10),
CONSTRAINT x2_UK FOREIGN KEY(X2)
REFERENCES TABLE2(field2))

CHECK
Defines a condition that each row must satisfy

CONSTRAINT emp_salary CHECK(SAL>0)

38. What is the Purpose ON DELETE CASCADE?


Deletes the dependent rows in the child table, when a row in parent table is deleted.

39. How can you view the constraints?


User_constraints table

40. Can we perform the DML Operations On View?


 You can perform DML operations on Simple view (selecting view from one table and also all not null
columns selected).

 If view is complex View and View contains the following then we can’t modify the view
--GROUP Functions
-- A Group By clause
-- DISTINCT Keyword
-- Not null columns in Base table that are not selected by View

41. How to deny the DML operation on simple View?

CREATE a view with ‘WITH READ ONLy’ option

42. When to create an Index?


You should create an index if :
• A Column contains a wide range of values

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 6
• A Column contains a large number of null values
• One or more columns frequently used together in join condition
• Table is large and most queries expected to retrieve less than 2 to 4% of the rows.

43. When Not create an Index?

You should not create an index if:


TABLE is Small
The columns are not often used as a condition in the query
The table is updated frequently

44. What is Functional Based Index?


A functional Based index is an index based on expression

CREATE INDEX ind_name table_name (UPPER(field_name))

45. What is the result of the following Command?


SELECT 1 FROM DUAL
UNION
SELECT ‘A’ FROM DUAL
Error : Expression Must have the same datatype as corresponding expression.

46. What is the difference between alias and Synonym?


Alias is temporary and used in one query. Synonym is Permanent aliasing

47. Can Dual table be deleted or dropped or altered or inserted?


YES,we can do

48. What Is the result for the following queries?


1) SELECT * from emp where rownum < 3
2) SELECT * from emp where rownum =3

1) 2 rows selected
2) No rows selected

49. Can we create index on View?


We can’t create index on view.

50. How to eliminate the duplicate rows?


Using ROWID we can delete duplicate rows.

DELETE FROM EMPMASTER A WHERE A.ROWID> (SELECT MIN(B.ROWID) FROM EMPMASTER B WHERE
A.EMPNO=B.EMPNO);

51. How can we find the nth salary in the table?

SELECT DISTINCT (A.SAL) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT (B.SAL)) FROM EMP B
WHERE A.SAL<=B.SAL)

52. What is the ROWID?


ROWID is pseudo column. It uniquely identifies a row with in a table, but not with in the database.

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 7
53. What is the ROWNUM?
ROWNUM is pseudo column to limit the number of returned rows. This behaves like a table column but is not
actually stored in tables.

54. What is the difference between Group by and Order by?


Group by is used to group set of values based on one or more values.
Order by is to sort values either in ascending or descending order.

55. How Many CODD rules Oracle satisfies?


Out of 12 , 11 rules Oracle satisfying .

56. What is the difference Between Primary Key and Unique Key?

Primary Key Unique Key


You can have only one primary key in a table You can have more than one Unique key in a table
Primary disallows the duplicates and Nulls also Unique key disallows only duplicates, it accepts the
Nulls.

PL/SQL:

1. What is the difference between %TYPE and %ROWTYPE?


%TYPE : It provides the datatype of a variable or database column
%ROWTYPE : It provides the record type that represents a row in a table.

2. What are the main Benefits using %TYPE and %ROWTYPE?


• You need not know the exact datatype of the field in the table.
• If you change the database definition (field size increased), datatype declared using %TYPE or %ROWTYPE at the
time of runtime it will be take changed database field.

3. What is Collection? What are the collection types using in PL/SQL?


A Collection is an ordered group of elements , all of the same type.
PL/SQL offers these Collections:
a. Nested Tables
b. VArrays
c. Index-By-tables (Associate arrays)
4. Give the Brief description on Nested Tables?
• PL/SQL Nested tables like one dimensional array. Nested tables size unbounded ,So the size of the
Nested table can increase dynamically.
• We can delete elements from Nested table using DELETE ( it might leave gaps) and NEXT for iterate
over the scripts.

Syntax:
TYPE type_name AS TABLE OF element_type

Ex:
CREATE TYPE Stulist AS TABLE OF VARCHAr2(10)
/
CREATE TYPE student AS OBJECT (
id NUMBER,
name VARCHAR2(10),
stuinfo stulist)

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 8
5. What is VARRY?
Varrays allow you to associate a single identifier with an entire collection.
Varray has the maximum size which you must specify in its type definition.

Syntax:
TYPE type_name AS VARRAY(size limit) OF element_type
Ex:
CREATE TYPE Stulist AS VARRAY(50) OF VARCHAr2(10)
/
CREATE TYPE student AS OBJECT (
id NUMBER,
name VARCHAR2(10),
stuinfo stulist)

6. What is the Index-By-Tables (Associated Arrays) ?


Associative arrays are sets of key-value pairs, where each key is unique and is used to locate a corresponding
value in the array. The key can be an integer or a string.

Syntax :
TYPE type_name IS TABLE OF element type
INDEX BY BINARY_INTEGER

Ex: TYPE EmpTabTyp IS TABLE OF emp%ROWTYPE


INDEX BY BINARY_INTEGER;
emp_tab EmpTabTyp;

7.What is the difference between Nested tables and Varrays?


Varrays is good choice when the number of elements known in advance and all the elements are usually accessed
in sequence.
Nested tables are dynamic. You can delete arbitrary elements rather than just removing an item from end.

8. What is the difference between Nested tables and Index-By-tables(Associated Arrays)?


Nested tables can be stored in database column, but associated arrays can not. Nested tables are appropriate for
important data relationships that must be stored persistently.

Associated Arrays are appropriate for relatively small lookup tables where the collection can be constructed in
memory each time a procedure is called or Package is initialized. These are good for collecting information whose value is
unknown before hand, because there is no fixed limit on their size.

9. Can we Delete Individual Element from VARRAYS?


VARRAYS are dense. We can’t delete elements from VARRAYS.

10. What is bulk binding?

A DML statement can transfer all the elements of a collection in a single operation, a process known as bulk
binding.
For example If the collection has 20 elements, bulk binding lets you perform the equivalent of 20 SELECT, INSERT,
UPDATE, or DELETE statements using a single operation.
 This technique improves performance by minimizing the number of context switches between the PL/SQL and
SQL engines

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 9
11. Where can you use the FORALL statement?
To do bulk binds with INSERT,UPDATE and DELETE statements you enclose the SQL statement with in a PL/SQL
using FORALL
Syntax:
FORALL index IN lower_bound..upper_bound
sql_statement;

12. Where you use the BULK COLLECT?


To do bulk binds with SELECT statements, you include the BULK COLLECT clause in the SELECT statement
instead of using INTO.

13. What is a cursor? Why Use a cursor?


When a query executed in oracle, the result set is produced and stored in the memory .Oracle allows accessing this
result set in the memory through Cursor.
Need of the cursor is Many times, when a query returns more than one row. We might want to go through each
row and process the data in different way for them.

14. What are the CURSOR types?


PL/SQL uses 2 types of Cursors
Implicit Cursor:
PL/SQL declares a cursor implicitly for all SQL data manipulation statements, including queries that return
only one row.
Explicit Cursor:
Queries that return more than one row, you must declare an explicit cursor

15. How many ways CURSOR can open?


CURSOR can open in two ways
1) OPEN ---FETCH –CLOSE
Ex:
CURSOR c1 IS
SELECT ename,empno from EMP;
OPEN C1;
LOOP
FETCH ename,empno INTO var1,var2;
EXIT WHEN C1%NOTFOUND;
END LOOP;
CLOSE C1;
2) FOR LOOP
Ex:
CURSOR c1 IS
SELECT ename,empno from EMP;

FOR c1 in C2 LOOP
Var1 =c2.ename;
Var2 = c2.empno;
END LOOP;

16. What is the difference between OPEN-FETCH-CLOSE and FOR LOOP in CURSORS?
FOR LOOP in CURSOR:
A cursor FOR loop implicitly declares its loop index as a %ROWTYPE record, opens a cursor, repeatedly fetches
rows of values from the result set into fields in the record, and closes the cursor when all rows have been processed.

OPEN-FETCH-CLOSE:

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 10
Explicitly we have to open the query and closing the query.

17. Can we pass the parameters in CURSOR?


Yes, we can
18. What are the explicit cursors attributes?
%FOUND,%ISOPEN,%NOTFOUND,%ROWCOUNT
19. What are the implicit cursors attributes?
%FOUND,%NOTFOUND and %ROWCOUNT
20. What is the purpose of %ROWCOUNT?
How many rows effected we can know from the %ROWCOUNT. %ROWCOUNT yields the number of rows
affected by an INSERT, UPDATE, DELETE or SQL statement.
If INSERT,UPDATE,DELETE statements effected no rows or SELECT statement returns no rows then the
%ROWCOUNT value is ZERO.
If SELECT statement returns more than one row and PL/SQL raises the TOO_MANY_ROWS then %ROWCOUNT
VALUE is 1. it doesn’t retrieve the actual value.

21. What is the REF CURSOR?


REF CURSOR is a cursor variable. Use of the cursor variables to pass the query result sets between PL/SQL stored
subprograms, packages to client.
Syntax:
TYPE ref_cursor_name IS REF CURSOR [RETURN return_type]
Ex:
DECLARE
TYPE DeptCur IS REF CURSOR RETURN dept%ROWTYPE;
Deptcut deptmain;
REF Cursors

Ref cursor is a Data type. A variable created using this data type is usually called as a Cursor Variable. A cursor variable
can be associated with different queries at run-time. The primary advantage of using cursor variables is their capability to
pass result sets between sub programs (like stored procedures, functions, packages etc.)

It is of two types:

Strong: With a Return Type


Weak: Without a Return Type

Advantages of Ref Cursors:

* Uses the same memory area for all the active sets created by different queries.
* Can be used to pass result sets between sub programs.
* Ability to change the query based on a certain criterion.

Difference between Static and Ref Cursors:

Static Cursors cannot be passed to sub programs whereas ref cursors can be passed between sub programs.
Static Cursors as the name suggests are Static and decided at the design time itself whereas Ref Cursors are changed
during the execution time as per certain criterion.

Important Note: Ensure that any open cursor is closed before attempting to open the next cursor.

Examples of Ref Cursors:

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 11
%ROWTYPE with Ref Cursor:

declare
type r_cursor is REF CURSOR;
c_emp r_cursor;
er emp%rowtype;
begin
open c_emp for select * from emp;
loop
fetch c_emp into er;
exit when c_emp%notfound;
dbms_output.put_line(er.ename ' - ' er.sal);
end loop;
close c_emp;
end;

RECORDS with Ref Cursor:


declare
type r_cursor is REF CURSOR;
c_emp r_cursor;
type rec_emp is record ( name varchar2(20), sal number(6) );
er rec_emp;
begin
open c_emp for select ename,sal from emp;
loop
fetch c_emp into er;
exit when c_emp%notfound;
dbms_output.put_line(er.name ' - ' er.sal);
end loop;
close c_emp;
end;
Multiple queries using Ref Cursor:
declare
type r_cursor is REF CURSOR;
c_emp r_cursor;
type rec_emp is record
( name varchar2(20),
sal number(6) );
er rec_emp;
begin
open c_emp for select ename,sal from emp where deptno = 10;
dbms_output.put_line('Department: 10');
dbms_output.put_line('--------------');
loop
fetch c_emp into er;
exit when c_emp%notfound;

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 12
dbms_output.put_line(er.name ' - ' er.sal);
end loop;
close c_emp;
open c_emp for select ename,sal from emp where deptno = 20;
dbms_output.put_line('Department: 20');
dbms_output.put_line('--------------');
loop
fetch c_emp into er;
exit when c_emp%notfound;
dbms_output.put_line(er.name ' - ' er.sal);
end loop;
close c_emp;
end;

Ref Cursor used as Parameters between Sub Programs:


declare
type r_cursor is REF CURSOR;
c_emp r_cursor;
type rec_emp is record ( name varchar2(20),
sal number(6) );
procedure PrintEmployeeDetails(p_emp r_cursor) is
er rec_emp;
begin
loop
fetch p_emp into er;
exit when p_emp%notfound;
dbms_output.put_line(er.name ' - ' er.sal);
end loop;
end;
begin
for i in (select deptno,dname from dept)
loop
open c_emp for select ename,sal from emp where deptno = i.deptno;
dbms_output.put_line(i.dname);
dbms_output.put_line('--------------');
PrintEmployeeDetails(c_emp);
close c_emp;
end loop;
end;

22. What are the PL/SQL Exceptions?


Pre defined Exceptions:
These Exceptions are raised implicitly by the run-time system.
Ex: NO_DATA_FOUND, ZERO_DIVIDE
User defined Exceptions:
User-defined exceptions must be raised explicitly by RAISE statements.
DECLARE
SAL_check EXCEPTION;
BEGIN
IF SAL <100 THEN
RAISE SAL_CHECK
END IF;

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 13
EXCEPTION
WHEN SAL_CHECK THEN
-----
END;
23. How to define our Own Error Messages?
We can define using RAISE_APPLICATION_ERROR.
Syntax:
RAISE_APPLICATION_ERROR ( Error number,error message);
 When this called, it ends the subprogram and returns the user defined error message to application.

 Error Number range is -20000 to-20999

24. What are SQLCODE and SQLERROR?


SQLCODE: returns the number of the Oracle Error.
SQLERRM: Associated error message for the SQLCODE

25. What are subprograms?


Subprograms are named PL/SQL blocks that can take parameters and be invoked. PL/SQL has two types of
subprograms called Procedures and functions.

26. Where can we use procedure and Function?


Procedure used for to perform an action. Function to compute Value.

27. Advantages of subprograms?


Extensibility, modularity, reusability and maintainability.

28. Give the procedure Syntax?


[CREATE [OR REPLACE]]
PROCEDURE procedure_name[(parameter[, parameter]...)]
[AUTHID {DEFINER | CURRENT_USER}] {IS | AS}
[PRAGMA AUTONOMOUS_TRANSACTION;]
[local declarations]
BEGIN
executable statements
[EXCEPTION
exception handlers]
END [name];

29. What is AUTHID? What is the Purpose of AUTHID in procedure?


The AUTHID clause determines whether a stored procedure executes with the Privileges of its owner (the default)
or current user.

30. What is AUTONOMOUS_TRANSACTION?


 The pragma AUTONOMOUS_TRANSACTION instructs the PL/SQL compiler to mark a
procedure as autonomous (independent).
 Autonomous transactions let you suspend the main transaction, do SQL operations, commit or roll back those
operations, then resume the main transaction.

31. Can we call a function from SELECT Statement?


YES
32. What is forward declaration?

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 14
Forward Declaration advises PL/SQL that the body of procedure can be found later in the block, but the specification
should be declared first.

33. What are actual and Formal Parameters?


Variables or expressions referenced in the parameter list of a subprogram call are actual parameters.
Ex: update_sal(empnum,sal);
Variables declared in subprogram specification and referenced in the subprogram body are formal parameters.
Ex: PRCODURE update_sal(empnum number,sal number)
34. What are the types of notations?
Positional, Named and Mixed notations

Ex: PROCEDURE acc_update (acct_no NUMBER, amount NUMBER);

Positional Notation :
Acc_update(acct,amt);
Named Notation : acc_update(amount =>amt, acct_no => acct);
Or
Acc_update(acct_no=>acct,amount=>amt);
Mixed Notation:
Positional Notation must precede named notation. And the reverse notation is not allowed.
Acc_update(acct,amount => amt);

35. What are the Parameter Modes and what is the default parameter mode?
Parameter Modes are IN,OUT,INOUT

IN parameter is the default parameter mode.

36. In Parameter modes which are pass by Reference and Pass by Value?

Pass By Reference : IN
Pointer to the actual parameter is passed to the corresponding formal parameters. Both Parameters use
the same memory location.

Pass By Value :OUT,IN OUT


The Values of OUT Actual parameters copied into the corresponding formal parameters.

37. What is NOCOPY? When we use it?

NOCOPY is Compiler Hint. When the Parameters hold large data structures such as collections and records , all
this time copying slows down the execution. To prevent this we ca specify NOCPY. This allows the PL/SQL Compiler to
pass OUT and INOUT parameters by reference.

38. What is Table Functions?


Table functions are functions that produce a collection of rows (either a nested table or a Varray) that can be
queried like a physical database table or assigned to PL/SQL collection variable. We can use the table function like the
name of the database table.

39. What is PL/SQL Package? And what are the parts of the package?
Package groups logically related PL/SQL types, procedures, functions.
Package having the two parts: Package specification and Package Body.

• Package Body is optional in some cases

40. What are the advantages of the Packages?

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 15
Modularity, Easier application design, Information hiding, better performance.

• When you call the Packaged Procedure for the first time ,the whole package is loaded in to memory. So
later calls to related subprograms in the package require no disk I/O.
• Packages stop cascading dependencies and thereby avoid unnecessary recompiling.
41. What are Private and Public variables in Package?
• Variables declared in Package Body and restricted to use with in the package those variables are called Private
Variables.
• Variables declared in Package specification and this variable is Visible outside the package ,those variables are
called public variables.
42. Which Package can we use to display the output from the PL/SQL blocks or subprogram?

DBMS_OUTPUT
43. Which statement we have to set to display output on SQL*PLUS?

SET SERVEROUTPUT ON
44. How to read and write the text files?
Using UTL_FILE

45. What is Dynamic SQL?


Some Statements can, probably will change from execution to execution means change at runtime, and they are
called dynamic SQL statements.

46. What is the need for Dynamic SQL?


• You want to execute the DDL statements from the PL/SQL block
• You want to Execute the Control statements from the PL/SQL block

47. How can we execute DDL statements from PL/SQL Block?


Using EXECUTE_IMMEDIATE statement
Ex: EXECUTE_IMMEDIATE(‘TRUNCATE TABLE T1’);

48. What is Trigger? And Define the Parts of the trigger?


Trigger is stored procedure, that run implicitly when an INSERT, UPDATE Or DELETE statement issued against the
table or against the view or database system action Occurs.

Parts of the Trigger :


• Triggering Event or statement
• Trigger restriction
• Triggering action

49. What are the types of triggers?


• ROW Level Triggers
• Statement Level Triggers
• BEFORE and AFTER Triggers
• INSTEAD of Triggers
• System Event and User event Triggers

50. What is the difference Between Row Level Trigger and Statement Level Trigger?

• Row level trigger executes once for each row after (or before) the event. This is defined By using FOR EACH
ROW
• Statement Level trigger executes once after (or before) the event, independent how many rows are affected by the
event.

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 16
51. How can we access the attribute values in triggers?

Using :OLD and :NEW only with Row level trigger

52. Where can we use instead of triggers?


INSTEAD-OF triggers Provide a transparent way of modifying views, that can’t be modified directly through
SQL DML statements.

53. What are the System Event Triggers?


System events that can fire triggers are related to instances startup and shutdown and error messages
 STARTUP
 SHUTDOWN
 SERVERERROR
54. What are the User event Triggers?
User events that can fire triggers are related to user logon and logoff, DDL statements
LOG ON
LOG OFF
BEFORE CREATE and AFTER CREATE
BEFORE ALTER and AFTER ALTER
BEFORE DROP and AFTER DROP
55. Can we give the Commit and Roll back in side the Trigger?
NO
56. What is mutating table Error?
A mutating table is a table that is currently being modified by an update, delete, or insert statement. When a
trigger tries to reference a table that is in state of flux (being changed), it is considered "mutating" and raises an error since
Oracle should not return data that has not yet reached its final state.
57. What is Optimization? What are the types of optimization?
Optimization is the process of choosing the most efficient way to execute SQL statement.
Optimization is in two approaches:
RULE Based
COST Based
58. What is Execution Plan?
Combination of steps Oracle Uses to execute a statement is called an execution plan. Execution plan includes an
access method for each table that the statement accesses and ordering of the tables
We can check the execution plan by EXPLAIN PLAN Command.

59. What are the LOCKS providing by ORACLE?


Oracle provides two different levels of locking
 ROW LEVEL
Each row in the table locked individually
 TABLE LEVEL

Entire Table Locked

60. What are the Modes of the LOCKING?


o Exclusive LOCK Mode
o Share Lock Mode
61. What is exclusive Lock mode?
This Lock prevents the associated resource from being shared. This Lock Mode obtained to modify data.

Ex : LOCK TABLE table_name IN EXCLUSIVE MODE

62. What is Share Lock Mode?


This Lock allows the associated resource to be shared, depending on the operations involved.
Ex: LOCK TABLE table_name IN SHARE MODE

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 17
Plsql Tables

Plsql table is one dimentional, unbounded, collection of elements indexed by binary interger.
plsql table can have only one column,it is similar to one dimentional array.
it is onbounded there is no predefined limit of the number od rows in plsql table.
The plsql table is in this way very different from aray.
plsql table can have only single column, all rows in plsql table contain of the values of same data type.
Indexed by binary integer
Plsql tables correctly supports a single index mode by binary integer.
This number acts as primary key od plsql table.
You can’t commit information to plsql table or rollback changes from the table.
You can’t select from plsql table.
You can’t isssue DML statemts.

Materialiazed Views
It is special kind of views which physically exists inside the database,it can contain joins or aggragate functions to improve
performances .
The existances of materiliazed views is transparent to sql applications,so DBA can create or drop materiliazed views of any
time without affecting the sql applications.

Oracle 10g new Features.


New Features in Oracle10g release 10.1.0
• Oracle10g Grid – RAC enhanced for Oracle10g dynamic scalability with server blades
• Completely reworked 10g Enterprise Manager (OEM)
• AWR and ASH tables incorporated into OEM Performance Pack and Diagnostic Pack options
• Automated Session History (ASH) materializes the Oracle Wait Interface over time
• Data Pump replaces imp utility with impdp
• Automatic Database Diagnostic Monitor (ADDM)
• Automatic Storage Management (ASM) introduced Stripe And Mirror Everywhere (SAME) standard
• Automatic Workload Repository (AWR) replaces STATSPACK
• SQLTuning Advisor
• SQLAccess Advisor
• Rolling database upgrades (using Oracle10g RAC)
• dbms_scheduler package replaces dbms_job for scheduling
• OEM Partition Manager introduced
Miscellaneous Oracle10g enhancements:
• Set Database Default Tablespace syntax
• Rename Tablespace command
• Introduced RECYCLEBIN command for storing objects before they are dropped. Required new PURGE command
for maintenance.
• sqlplus / as sysdba accessibility without quote marks
• SYSAUX tablespace
• Multiple Temporary Tablespaces supported to reduce stress on sorting in TEMP
• RMAN introduces compression for backups
• New drop database syntax
• New alter database begin backup syntax
• Oracle10g Data Guard Broker introduced
• Oracle10g RAC supports secure Redo Log transport
• Flashback operations available on row, transaction, table or database level
• SQL Apply feature

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 18
• VPD (FGAC, RLS) supports both row-level and column-level VPD
• Cross Platform Transportable Tablespaces
• External Table unload utility
• SQL Regular Expression Support with the evaluate syntax
• New ROW TIMESTAMP column
• Improvement to SSL handshake speed
• Automatic Database Tuning of Checkpoints, Undo Segments and shared memory
• Automated invoking of dbms_stats for CBO statistics collection
• RAC introduces Integrated Cluster ware
• Oracle Application Builder supports HTML DB
• Browser Based Data Workshop and SQL Workshop
• PL/SQL Compiler enhanced for compile-time Warnings in utl_mail and utl_compress
• VPD (FGAC, RLS) supports both row-level and column-level VPD
• External Table unload utility
• SQL Regular Expression Support with the evaluate syntax
• New ROW TIMESTAMP column
• Ability to UNDROP a table from a recycle bin
Ability to rename tablespaces
Ability to transport tablespaces across machine types (E.g Windows to Unix)
• New database scheduler - DBMS_SCHEDULER
DBMS_FILE_TRANSFER Package
Difference between Normal View and Materialized view.
1 View is a logical or virtual table it doesn't have data on its own, but materialized view has a physical structure it
stores data in local machine or on its own. materialized view can be refreshed automatically or manually. but in
view, if any changes happened in the base tables, we want to reflect the same in the view means view has to issue
the select statement again to the database;
2 DML Opereations are allowed in Normal where as Materialized view DML operations or not allowed.

Difference between function and procedure


1Function is mainly used in the case where it must return a value. Where as a procedure may or may not return a
value or may return more than one value using the OUT parameter.
2. Function can be called from SQL statements where as procedure can not be called from the sql statements
3. Functions are normally used for computations where as procedures are normally used for executing business
logic.
4. You can have DML (insert update delete) statements in a function. But you cannot call such a function in a SQL
query.
5. Function returns 1 value only. Procedure can return multiple values (max 1024).
6.Stored Procedure: supports deferred name resolution. Example while writing a stored procedure that uses table
named tabl1 and tabl2 etc..but actually not exists in database is allowed only in during creation but runtime
throws error Function wont support deferred name resolution.
7.Stored procedure returns always integer value by default zero. where as function return type could be scalar or
table or table values
8. Stored procedure is precompiled execution plan where as functions are not.
9.A procedure may modify an object where a function can only return a value The RETURN statement
immediately completes the execution of a subprogram and returns control to the caller.

Pcakage :

A package is a schema object that groups logically related PL/SQL types, items, and subprograms. Packages usually have
two parts, a specification and a body, although sometimes the body is unnecessary. The specification (spec for short) is the
interface to your applications; it declares the types, variables, constants, exceptions, cursors, and subprograms available for
use. The body fully defines cursors and subprograms, and so implements the spec.

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 19
The spec holds public declarations, which are visible to your application. You must declare subprograms at the end of the
spec after all other items (except pragmas that name a specific function; such pragmas must follow the function spec).
The body holds implementation details and private declarations, which are hidden from your application. Following the
declarative part of the package body is the optional initialization part, which typically holds statements that initialize
package variables
Advantages of PL/SQL Packages
Packages offer several advantages: modularity, easier application design, information hiding, added functionality, and
better performance.
Modularity
Packages let you encapsulate logically related types, items, and subprograms in a named PL/SQL module. Each package is
easy to understand, and the interfaces between packages are simple, clear, and well defined. This aids application
development.
Easier Application Design
When designing an application, all you need initially is the interface information in the package specs. You can code and
compile a spec without its body. Then, stored subprograms that reference the package can be compiled as well. You need
not define the package bodies fully until you are ready to complete the application.
Information Hiding
With packages, you can specify which types, items, and subprograms are public (visible and accessible) or private (hidden
and inaccessible). For example, if a package contains four subprograms, three might be public and one private. The
package hides the implementation of the private subprogram so that only the package (not your application) is affected if
the implementation changes. This simplifies maintenance and enhancement. Also, by hiding implementation details from
users, you protect the integrity of the package.
Added Functionality
Packaged public variables and cursors persist for the duration of a session. So, they can be shared by all subprograms that
execute in the environment. Also, they allow you to maintain data across transactions without having to store it in the
database.
Better Performance
When you call a packaged subprogram for the first time, the whole package is loaded into memory. So, later calls to related
subprograms in the package require no disk I/O. Also, packages stop cascading dependencies and thereby avoid
unnecessary recompiling. For example, if you change the implementation of a packaged function, Oracle need not
recompile the calling subprograms because they do not depend on the package body.
Disadvantages:
1 Updating one of the functions/procedures will invalid other objects which use different functions/procedures since
whole package is needed to be compiled.
2 More memory may be required on the Oracle database server when using Oracle PL/SQL packages as the whole
package is loaded into memory as soon as any object in the package is accessed.
3 Exceptions :
4 An exception is a runtime error or warning condition, which can be predefined or user-defined. Predefined
exceptions are raised implicitly (automatically) by the runtime system. User-defined exceptions must be raised
explicitly by RAISE statements. To handle raised exceptions, you write separate routines called exception
handlers

Exceptions :

An exception is a runtime error or warning condition, which can be predefined or user-defined. Predefined exceptions are
raised implicitly (automatically) by the runtime system. User-defined exceptions must be raised explicitly by RAISE
statements. To handle raised exceptions, you write separate routines called exception handlers

ACCESS_INTO_NULL 06530 -6530 A program attempts to assign values to the attributes of an uninitialized
object
CASE_NOT_FOUND 06592 -6592 None of the choices in the WHEN clauses of a CASE statement is selected,

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 20
and there is no ELSE clause.
COLLECTION_IS_NULL 06531 -6531 A program attempts to apply collection methods other than EXISTS to an
uninitialized nested table or varray, or the program attempts to assign
values to the elements of an uninitialized nested table or varray.
CURSOR_ALREADY_OPEN 06511 -6511 A program attempts to open an already open cursor. A cursor must be
closed before it can be reopened. A cursor FOR loop automatically opens
the cursor to which it refers, so your program cannot open that cursor
inside the loop.
DUP_VAL_ON_INDEX 00001 -1 A program attempts to store duplicate values in a column that is
constrained by a unique index.
INVALID_CURSOR 01001 -1001 A program attempts a cursor operation that is not allowed, such as closing
an unopened cursor.
INVALID_NUMBER 01722 -1722 n a SQL statement, the conversion of a character string into a number fails
because the string does not represent a valid number. (In procedural
statements, VALUE_ERROR is raised.) This exception is also raised when
the LIMIT-clause expression in a bulk FETCH statement does not evaluate
to a positive number.
LOGIN_DENIED 01017 -1017 A program attempts to log on to Oracle with an invalid username or
password.
NO_DATA_FOUND 01403 +100 A SELECT INTO statement returns no rows, or your program references a
deleted element in a nested table or an uninitialized element in an index-
by table.
Because this exception is used internally by some SQL functions to signal
completion, you should not rely on this exception being propagated if you
raise it within a function that is called as part of a query.
NOT_LOGGED_ON 01012 -1012 A program issues a database call without being connected to Oracle.
PROGRAM_ERROR 06501 -6501 PL/SQL has an internal problem.
ROWTYPE_MISMATCH 06504 -6504 The host cursor variable and PL/SQL cursor variable involved in an
assignment have incompatible return types. When an open host cursor
variable is passed to a stored subprogram, the return types of the actual
and formal parameters must be compatible.
SELF_IS_NULL 30625 - A program attempts to call a MEMBER method, but the instance of the
30625 object type has not been initialized. The built-in parameter SELF points to
the object, and is always the first parameter passed to a MEMBER method.
STORAGE_ERROR 06500 -6500 PL/SQL runs out of memory or memory has been corrupted.
SUBSCRIPT_BEYOND_COUNT 06533 -6533 A program references a nested table or varray element using an index
number larger than the number of elements in the collection.
SUBSCRIPT_OUTSIDE_LIMIT 06532 -6532 A program references a nested table or varray element using an index
number (-1 for example) that is outside the legal range.
SYS_INVALID_ROWID 01410 -1410 The conversion of a character string into a universal rowid fails because
the character string does not represent a valid rowid.
TIMEOUT_ON_RESOURCE 00051 -51 A time out occurs while Oracle is waiting for a resource.
TOO_MANY_ROWS 01422 -1422 A SELECT INTO statement returns more than one row.
VALUE_ERROR 06502 -6502 An arithmetic, conversion, truncation, or size-constraint error occurs. For

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 21
example, when your program selects a column value into a character
variable, if the value is longer than the declared length of the variable,
PL/SQL aborts the assignment and raises VALUE_ERROR. In procedural
statements, VALUE_ERROR is raised if the conversion of a character
string into a number fails. (In SQL statements, INVALID_NUMBER is
raised.)
ZERO_DIVIDE 01476 -1476 A program attempts to divide a number by zero.

Object Types :
• An object type is a user-defined composite datatype representing a data structure and functions and procedures
to manipulate the data. With scalar datatypes, each variable holds a single value. With collections, all the elements
have the same type. Only object types let you associate code with the data.
• The variables within the data structure are called attributes. The functions and procedures of the object type are
called methods
Advangates with object types :
• Object types let you break down a large system into logical entities. This lets you create software components
that are modular, maintainable, and reusable across projects and teams.
To see how objects can be used, suppose an object is created to represent a person. In this case, a person is defined by three
attributes: first_name, last_name and date_of_birth. Returning the age of the person is also desired, so this is included as a
member function, get_age.
CREATE OR REPLACE TYPE t_person AS OBJECT (
first_name VARCHAR2(30),
last_name VARCHAR2(30),
date_of_birth DATE,
MEMBER FUNCTION get_age RETURN NUMBER
);
/
Type created.
Next the type body is created to implement the get_age member function.
CREATE OR REPLACE TYPE BODY t_person AS
MEMBER FUNCTION get_age RETURN NUMBER AS
BEGIN
RETURN tRUNC(MONTHS_BETWEEN(SYSDATE, date_of_birth)/12);
END get_age;
END;
/
Type body created.
Once the object is defined, it can be used to define a column in a database table.
CREATE TABLE people (
id NUMBER(10) NOT NULL,
person t_person
);
Table created.
To insert data into the PEOPLE table, the t_person() constructor must be used. This can be done as part of a regular DML
statement or using PL/SQL.
INSERT INTO people (id, person)
VALUES (1, t_person('John', 'Doe', TO_DATE('01/01/2000','DD/MM/YYYY')));
1 row created.
COMMIT;
Commit complete.
DECLARE
l_person t_person;
BEGIN

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 22
l_person := t_person('Jane','Doe', TO_DATE('01/01/2001','DD/MM/YYYY'));
INSERT INTO people (id, person)
VALUES (2, l_person);
COMMIT;
END;
/
PL/SQL procedure successfully completed.
Once the data is loaded, it can be queried using the dot notation:
• alias.column.attibute
• alias.column.function()
The query below shows this in action.
SELECT p.id,
p.person.first_name,
p.person.get_age() AS age
FROM people p;
ID PERSON.FIRST_NAME AGE
---------- ------------------------------ ----------
1 John 5
2 Jane 4
2 rows selected.

Structure of an Object Type


Like a package, an object type has a specification and a body. The specification (or spec for short) defines the
programming interface; it declares a set of attributes along with the operations (methods) to manipulate the data. The body
defines the code for the methods.
All the information a program needs to use the methods is in the spec. You can change the body without changing the
spec, and without affecting client programs.
In an object type spec, all attributes must be declared before any methods. If an object type spec declares only attributes,
the object type body is unnecessary. You cannot declare attributes in the body. All declarations in the object type spec are
public (visible outside the object type).
Components of an Object Type
An object type encapsulates data and operations. You can declare attributes and methods in an object type spec, but not
constants, exceptions, cursors, or types. You must declare at least one attribute (the maximum is 1000). Methods are
optional.
Attributes
Like a variable, an attribute is declared with a name and datatype. The name must be unique within the object type (but
can be reused in other object types). The datatype can be any Oracle type except:
• LONG and LONG RAW
• ROWID and UROWID
• The PL/SQL-specific types BINARY_INTEGER (and its subtypes), BOOLEAN, PLS_INTEGER, RECORD, REF
CURSOR, %TYPE, and %ROWTYPE
• Types defined inside a PL/SQL package
Object Methods
The general kinds of methods that can be declared in a type definition are:
Member
Static
Constructor

A principal use of methods is to provide access to the data of an object. You can define methods for operations that an
application is likely to want to perform on the data so that the application does not have to code these operations itself. To
perform the operation, an application calls the appropriate method on the appropriate object.

For example, the following SQL statement uses the get_idno() method to display the Id number of persons in the contacts
table:

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 23
SELECT c.contact.get_idno() FROM contacts c;

You can also define static methods to compare object instances and to perform operations that do not use any particular
object's data but instead are global to an object type.A constructor method is implicitly defined for every object type, unless
this default constructor is over-written with a user-defined constructor. A constructor method is called on a type to
construct or create an object instance of the type.

Using an ALTER TYPE statement, you can modify, or evolve, an existing user-defined type to make the following changes:
• _ Add and drop attributes
• _ Add and drop methods
• _ Modify a numeric attribute to increase its length, precision, or scale
• _ Modify a varying length character attribute to increase its length
• _ Change a type's FINAL and INSTANTIABLE properties

Object Tables
• An object table is a special kind of table in which each row represents an object. For
• example, the following statement creates an object table for person_typ objects:
• CREATE TABLE person_obj_table OF person_typ;
• You can view this table in two ways:
• _ As a single-column table in which each row is a person_typ object, allowing
• you to perform object-oriented operations
• _ As a multi-column table in which each attribute of the object type person_typ;
• such as idno, name, and phone; occupies a column, allowing you to perform
• relational operations

For example, you can execute the following instructions:


INSERT INTO person_obj_table VALUES (
1, 'John Smith', '1-800-555-1212');
SELECT VALUE(p) FROM person_obj_table p
WHERE p.name = 'John Smith';
References
A REF is a logical pointer to a row object that is constructed from the object identifier (OID) of the referenced object and is
an Oracle built-in datatype. REFs and collections of REFs model associations among objects, particularly many-to-one
relationships, thus reducing the need for foreign keys. REFs provide an easy mechanism for navigating between objects.
You can use the dot notation to follow the pointers. Oracle does joins for you when needed, and in some cases can avoid
doing joins.

You can use a REF to examine or update the object it refers to. You can also use a REF to obtain the object it refers to. You
can change a REF so that it points to a different object of the same object type hierarchy or assign it a null value.

The following example illustrates a simple use of a REF.


Example 1–2 Using a REF to an Object
CREATE TYPE emp_person_typ AS OBJECT (
name VARCHAR2(30),
manager REF emp_person_typ );
/
CREATE TABLE emp_person_obj_table OF emp_person_typ;

INSERT INTO emp_person_obj_table VALUES (


emp_person_typ ('John Smith', NULL));

INSERT INTO emp_person_obj_table


SELECT emp_person_typ ('Bob Jones', REF(e))

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 24
FROM emp_person_obj_table e
WHERE e.name = 'John Smith';
Scoped REFs
In declaring a column type, collection element, or object type attribute to be a REF, you can constrain it to contain only
references to a specified object table. Such a REF is called a scoped REF. Scoped REF types require less storage space and
allow more efficient access than unscoped REF types.
The following example shows REF column contact_ref scoped to person_obj_
table which is an object table of type person_typ.
CREATE TABLE contacts_ref ( contact_ref REF person_typ SCOPE IS person_obj_table,
contact_date DATE );
To insert a row in the table, you could issue the following:
INSERT INTO contacts_ref
SELECT REF(p), '26 Jun 2003' FROM person_obj_table p WHERE p.idno = 1;
A REF can be scoped to an object table of the declared type (person_typ in the example) or of any subtype of the declared
type. If scoped to an object table of a subtype, the REF column is effectively constrained to hold references only to instances
of the subtype (and its subtypes, if any) in the table.

Dereferencing REFs
Accessing the object referred to by a REF is called dereferencing the REF. Oracle provides the DEREF operator to do this.
Dereferencing a dangling REF returns a null object. For example:
SELECT DEREF(c.contact_ref), c.contact_date FROM contacts_ref c;

Oracle also provides implicit dereferencing of REFs. For example, to access the manager's name for an employee, you can
use a SQL expression similar to the following:
SELECT e.name, e.manager.name FROM emp_person_obj_table
WHERE e.name = 'Bob Jones';

In the example, e.manager.name follows the pointer from the person's manager, and retrieves the manager's name.
Following the REF like this is allowed in SQL, but not in PL/SQL.

Obtaining REFs
You can obtain a REF to a row object by selecting the object from its object table and applying the REF operator. For
example, you can obtain a REF to the person with identification number 1 as follows:

Declare
person_ref REF person_typ;
BEGIN
SELECT REF(p) INTO person_ref
FROM person_obj_table p
WHERE p.idno = 1;
END;

Rules for REF Columns and Attributes


• In Oracle, a REF column or attribute can be unconstrained or constrained using a SCOPE clause or a referential
constraint clause. When a REF column is unconstrained, it may store object references to row objects contained in
any object table of the corresponding object type.

• Oracle does not ensure that the object references stored in such columns point to valid and existing row objects.
Therefore, REF columns may contain object references that do not point to any existing row object. Such REF
values are referredto as dangling references.

• A REF column may be constrained to be scoped to a specific object table. All the REF values stored in a column
with a SCOPE constraint point at row objects of the table specified in the SCOPE clause. The REF values may,
however, be dangling.

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 25
• A REF column may be constrained with a REFERENTIAL constraint similar to the specification for foreign keys.
The rules for referential constraints apply to such columns. That is, the object reference stored in these columns
must point to a valid and existing row object in the specified object table.

• PRIMARY KEY constraints cannot be specified for REF columns. However, you can specify NOT NULL
constraints for such columns.

Collections
For modeling multi-valued attributes and many to many relationships, Oracle supports two collection datatypes: varrays
and nested tables. Collection types can be used anywhere other datatypes can be used. You can have object attributes of a
collection type in addition to columns of a collection type. For example, you might give a purchase order object type a
nested table attribute to hold the collection of line items for a given purchase order.

You use the CREATE TYPE statement to define collection types. In Example 1–3, the CREATE TYPE statements define the
object types people_typ and dept_persons_typ.

Example 1–3 Creating a Collection Datatype


CREATE TYPE people_typ AS TABLE OF person_typ;

CREATE TYPE dept_persons_typ AS OBJECT (


dept_no CHAR(5),
dept_name CHAR(20),
dept_mgr person_typ,
dept_emps people_typ);

In this simplified example, people_typ is a collection type, specifically a nested table type. The dept_persons_typ object
type has an attribute people_typ of this type. Each row in the people_typ nested table is an object of type person_typ.

Constraints for Object Tables


You can define constraints on an object table just as you can on other tables. You can define constraints on the leaf-level
scalar attributes of a column object, with the exception of REFs that are not scoped.
The following examples illustrate the possibilities. The first example places a PRIMARY KEY constraint on the idno
column of the object table person_extent:

CREATE TYPE location_typ (


building_no NUMBER,
city VARCHAR2(40) );
/
CREATE TYPE office_typ AS OBJECT (
office_id VARCHAR(10),
office_loc location_typ,
occupant person_typ );
/
CREATE TABLE office_tab OF office_typ (
office_id PRIMARY KEY );
The department_mgrs table in the next example has a column whose type is the object type location_typ defined in the
previous example. The example defines constraints on scalar attributes of the location_typ objects that appear in the
dept_loc column of the table.
CREATE TABLE department_mgrs (
dept_no NUMBER PRIMARY KEY,
dept_name CHAR(20),
dept_mgr person_typ,
dept_loc location_typ,

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 26
CONSTRAINT dept_loc_cons1
UNIQUE (dept_loc.building_no, dept_loc.city),
CONSTRAINT dept_loc_cons2
CHECK (dept_loc.city IS NOT NULL) );

INSERT INTO department_mgrs VALUES


( 101, 'Physical Sciences',
person_typ(65,'Vrinda Mills', '1-800-555-4412'),
location_typ(300, 'Palo Alto'));

Indexes for Object Tables


You can define indexes on an object table or on the storage table for a nested table column or attribute just as you can on
other tables.

You can define indexes on leaf-level scalar attributes of column objects, as shown in the following example. You can only
define indexes on REF attributes or columns if the REF is scoped.

Here, dept_addr is a column object, and city is a leaf-level scalar attribute of dept_addr that we want to index:

CREATE TABLE department_loc (


dept_no NUMBER PRIMARY KEY,
dept_name CHAR(20),
dept_addr location_typ );

CREATE INDEX i_dept_addr1


ON department_loc (dept_addr.city);

Wherever Oracle expects a column name in an index definition, you can also specify a scalar attribute of an object column.

Triggers for Object Tables

You can define triggers on an object table just as you can on other tables. You cannot define a trigger on the storage table
for a nested table column or attribute. You cannot modify LOB values in a trigger body. Otherwise, there are no special
restrictions on using object types with triggers.

The following example defines a trigger on the office_tab table defined in "Constraints for Object Tables" on page 2-4.

CREATE TABLE movement (


idno NUMBER,
old_office location_typ,
new_office location_typ );
CREATE TRIGGER trigger1
BEFORE UPDATE
OF office_loc
ON office_tab
FOR EACH ROW
WHEN (new.office_loc.city = 'Redwood Shores')
BEGIN
IF :new.office_loc.building_no = 600 THEN
INSERT INTO movement (idno, old_office, new_office)
VALUES (:old.occupant.idno, :old.office_loc, :new.office_loc);
END IF;
END;

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 27
Index :

What is an Index?
An index is a performance-tuning method of allowing faster retrieval of records. An index creates an entry for each value
that appears in the indexed columns. By default, Oracle creates B-tree indexes.
Create an Index
The syntax for creating a index is:
CREATE [UNIQUE] INDEX index_name
ON table_name (column1, column2, . column_n)
[ COMPUTE STATISTICS ];

There are several types of indexes available in Oracle all designed for different circumstances:
• b*tree indexes - the most common type (especially in OLTP environments) and the default type
• b*tree cluster indexes - for clusters
• hash cluster indexes - for hash clusters
• reverse key indexes - useful in Oracle Real Application Cluster (RAC) applications
• bitmap indexes - common in datawarehouse applications
• partitioned indexes - also useful for datawarehouse applications
• function-based indexes
• index organised tables
• domain indexes
Let's look at these Oracle index types in a little more detail.
B*Tree Indexes
B*tree stands for balanced tree. This means that the height of the index is the same for all values thereby ensuring that
retrieving the data for any one value takes approximately the same amount of time as for any other value. Oracle b*tree
indexes are best used when each value has a high cardinality (low number of occurrences)for example primary key indexes
or unique indexes. One important point to note is that NULL values are not indexed. They are the most common type of
index in OLTP systems.
B*Tree Cluster Indexes
These are B*tree index defined for clusters. Clusters are two or more tables with one or more common columns and are
usually accessed together (via a join).

CREATE INDEX product_orders_ix ON CLUSTER product_orders;


Hash Cluster Indexes
In a hash cluster rows that have the same hash key value (generated by a hash function) are stored together in the Oracle
database. Hash clusters are equivalent to indexed clusters, except the index key is replaced with a hash function. This also
means that here is no separate index as the hash is the index.

CREATE CLUSTER emp_dept_cluster (dept_id NUMBER) HASHKEYS 50;


Reverse Key Indexes
These are typically used in Oracle Real Application Cluster (RAC) applications. In this type of index the bytes of each of
the indexed columns are reversed (but the column order is maintained). This is useful when new data is always inserted at
one end of the index as occurs when using a sequence as it ensures new index values are created evenly across the leaf
blocks preventing the index from becoming unbalanced which may in turn affect performance.

CREATE INDEX emp_ix ON emp(emp_id) REVERSE;


Bitmap Indexes
These are commonly used in datawarehouse applications for tables with no updates and whose columns have low
cardinality (i.e. there are few distinct values). In this type of index Oracle stores a bitmap for each distinct value in the
index with 1 bit for each row in the table. These bitmaps are expensive to maintain and are therefore not suitable for
applications which make a lot of writes to the data.

For example consider a car manufacturer which records information about cars sold including the colour of each car. Each

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 28
colour is likely to occur many times and is therefore suitable for a bitmap index.

CREATE BITMAP INDEX car_col ON cars(colour) REVERSE;


Partitioned Indexes
Partitioned Indexes are also useful in Oracle datawarehouse applications where there is a large amount of data that is
partitioned by a particular dimension such as time.

Partition indexes can either be created as local partitioned indexes or global partitioned indexes. Local partitioned indexes
means that the index is partitioned on the same columns and with the same number of partitions as the table. For global
partitioned indexes the partitioning is user defined and is not the same as the underlying table.

Function-based Indexes
As the name suggests these are indexes created on the result of a function modifying a column value. For example

CREATE INDEX upp_ename ON emp(UPPER(ename));

The function must be deterministic (always return the same value for the same inputs).
Index Organised Tables
In an index-organised table all the data is stored in teh Oracle database in a B*tree index structure defined on the table's
primary key. This is ideal when related pieces of data must be stored together or data must be physically stored in a
specific order. Index-organised tables are often used for information retrieval, spatial and OLAP applications.
Domain Indexes
These indexes are created by user-defined indexing routines and enable the user to define his or her own indexes on
custom data types (domains) such as pictures, maps or fingerprints for example. These type of index require in-depth
knowledge about the data and how it will be accessed.

Bulk Collect :

‘Bulk collect..into’ clause improve performance of the select statements. To loop through records collected using bulk
collect we can use FORALL syntax. FORALL clause works with DML statements in batches and much faster than the
regular for loop construct. In this blog post, we are going to talk about FORALL exceptions with the
%BULK_EXCEPTIONS attribute. This attribute allows us to continue with the process, even if run into any DML exception
for some record in between. Basically this mechanism allows us to complete the process without stopping if any error
occurs.
All exceptions raised during execution are saved in %BULK_EXCEPTION attribute. It also stores a collection of records
similar to BULK COLLECT. It has two fields.
• %BULK_EXCEPTIONS(i).ERROR_CODE holds the corresponding Oracle error code.
• %BULK_EXCEPTIONS(i).ERROR_INDEX holds the iteration number of the FORALL statement for which the
exception was raised.
• %BULK_EXCEPTIONS.COUNT holds total number of exceptions encountered.
In order to bulk collect exceptions, we have to use FORALL clause with SAVE EXCEPTIONS keyword. Let us see with the
example.
Connect to SQL*Plus with proper credentials and run following query to create the table and populate it with some data.
CREATE TABLE TEST
(
Test_ID NUMBER(9) NOT NULL PRIMARY KEY,
Test_Desc VARCHAR(30),
New_Desc VARCHAR(30)
)
/
SQL> INSERT INTO TEST(TEST_ID,TEST_DESC)
2 SELECT ROWNUM, TABLE_NAME
3 FROM USER_TABLES;

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 29
9 rows created.
Run following PL/SQL block to populate the table and later on update it to see the exception behavior. We have created
this PL/SQL block based on the example shown in Oracle manual.
DECLARE
TYPE ga_Test_ID IS TABLE OF TEST.TEST_Id%TYPE;
TYPE ga_Test_Desc IS TABLE OF TEST.TEST_DESC%TYPE;
va_Test_ID ga_Test_ID;
va_Test_Desc ga_Test_Desc;
V_Err_count NUMBER;
BEGIN
SELECT Test_ID, Test_Desc
BULK COLLECT INTO va_Test_ID, va_Test_Desc
FROM Test;
FORALL i IN va_test_ID.FIRST..va_test_ID.LAST SAVE EXCEPTIONS
UPDATE TEST
SET NEW_DESC = TEST_DESC || LPAD(‘ ‘,22,’A')
WHERE TEST_ID = va_test_ID(i);
EXCEPTION
WHEN OTHERS THEN
v_Err_Count := SQL%BULK_EXCEPTIONS.COUNT;
DBMS_OUTPUT.PUT_LINE(‘Number of statements that failed: ‘ || v_Err_Count);
FOR i IN 1..v_Err_Count
LOOP
DBMS_OUTPUT.PUT_LINE(‘Error #’ || i || ‘ occurred during ‘||
‘iteration #’ || SQL%BULK_EXCEPTIONS(i).ERROR_INDEX);
DBMS_OUTPUT.PUT_LINE(‘Error message is ‘ ||
SQLERRM(-SQL%BULK_EXCEPTIONS(i).ERROR_CODE));
END LOOP;
END;
/
If you execute above PL/SQL block, it will display following information. It may be different for your scenario as data will
be different.
Number of statements that failed: 2
Error #1 occurred during iteration #6
Error message is ORA-12899: value too large for column
Error #2 occurred during iteration #9
Error message is ORA-12899: value too large for column
From above results we know that our iteration #6 and #9 failed because of the exceeding column length. This is really
useful feature for error handling when we are dealing with larger data set. Instead of exiting at first error, we can loop
through entire set and then work with the erroneous records later on.
UTL file package example :
CREATE OR REPLACE PROCEDURE rw_demo IS
InFile utl_file.file_type;
OutFile utl_file.file_type;
vNewLine VARCHAR2(4000);
i PLS_INTEGER;
j PLS_INTEGER := 0;
SeekFlag BOOLEAN := TRUE;
BEGIN
-- open a file to read
InFile := utl_file.fopen('ORALOAD', 'in.txt','r');
-- open a file to write
OutFile := utl_file.fopen('ORALOAD', 'out.txt', 'w');

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 30
-- if the file to read was successfully opened
IF utl_file.is_open(InFile) THEN
-- loop through each line in the file
LOOP
BEGIN
utl_file.get_line(InFile, vNewLine);

i := utl_file.fgetpos(InFile);
dbms_output.put_line(TO_CHAR(i));

utl_file.put_line(OutFile, vNewLine, FALSE);


utl_file.fflush(OutFile);

IF SeekFlag = TRUE THEN


utl_file.fseek(InFile, NULL, -30);
SeekFlag := FALSE;
END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN
EXIT;
END;
END LOOP;
COMMIT;
END IF;
utl_file.fclose(InFile);
utl_file.fclose(OutFile);
EXCEPTION
WHEN OTHERS THEN
RAISE_APPLICATION_ERROR (-20099, 'Unknown UTL_FILE Error');
END rw_demo;
1. Can a function or procedure be called from database trigger or vice versa?
Ans : Yes its possible to call a procedure in a database trigger.by using 'CALL' Keyword. But the viceversa is not
true. i.e You cannot call a trigger Explicitly.

2. Is it possible to have DML operations (Insert , Update , Delete ) STATEMENTS in a database trigger .?
Is it possible to have DML operations ( Insert , Update , Delete ) STATEMENTS in a database trigger .
Yes, you can do but not on the table on which the trigger is created. Otherwise, you can run into Mutating table
or tansition table state error.

3. Can a package have a database trigger?


No, package can havel procedure or function as subprograms, not the database trigger.
4. what are the limitations on DB triggers ?
 Limitations are trigger must not select, dml on the table on which they are invoked.
 You can't do DML on the table that caused the trigger otherwise you get a 'mutating table' error.
You can't commit inside a trigger or any procedure/function it calls (except for autonomous
transactions)

5. Difference between strong and weak ref corsor?


6. What is PRAGMA and what are different types of pragmas available?

Pragma is a keyword in Oracle PL/SQL that is used to provide an instruction to the compiler.

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 31
There are 5 type of PRAGMAS are there as of my knowledge..
they are

1.PRAGMA EXCEPTION_INIT(message,SQLCODE);---------->Exceptions

Pragma exception_init Allow you to handle the Oracle predefined message by your own message. Means you
can instruct compiler to associate the specific message to oracle predefined message at compile time. This way
you improve the Readability of your program, and handle it according to your own way.

Example : sqlerrr error code 1400 is can’t insert null value this message we can instruct to compiler our own
message.
DECLARE
e_MissingNull EXCEPTION;
PRAGMA EXCEPTION_INIT (e_MissingNull, -1402);
BEGIN
INSERT INTO Employee (id) VALUES (NULL);
EXCEPTION
WHEN e_MissingNull then
DBMS_OUTPUT.put_line('ORA-1400 occurred');
END;

2.PRAGMA AUTONOMOUS TRANSACTION;-------->procedures


AUTONOMOUS_TRANSACTION pragma instructs the compiler to treat the following pl/sql block as
autonomous (independent) from whatever transaction calls it. This means that any changes made to the
database in the autonomous transaction are independent of the main transaction and are either committed or
rolled back without affecting the main transaction.
Create or replace procedure p_log_audit
(what_tx VARCHAR2, descr_tx VARCHAR2,
who_tx VARCHAR2, when_dt DATE)
is
pragma autonomous_transaction;
begin
insert into Audit_emp
values(audit_seq.nextval, what_tx, descr_tx,
who_tx, when_dt);
commit;
end;

3.PRAGMA SERIALLY REUSABLE---->we use this in packages.


The SERIALLY_REUSABLE pragma specifies that the package state is needed for only one call to the server (for
example, an OCI call to the database or a stored procedure call through a database link). After this call, the
storage for the package variables can be reused, reducing the memory overhead for long-running sessions.
Example Serially Reusable Package Specification

CREATE OR REPLACE PACKAGE pkg IS


n NUMBER := 5;
END pkg;
/
CREATE OR REPLACE PACKAGE sr_pkg IS

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 32
PRAGMA SERIALLY_REUSABLE;
n NUMBER := 5;
END sr_pkg;
/
BEGIN
pkg.n := 10;
sr_pkg.n := 10;
END;
/
BEGIN
DBMS_OUTPUT.PUT_LINE('pkg.n: ' || pkg.n);
DBMS_OUTPUT.PUT_LINE('sr_pkg.n: ' || sr_pkg.n);
END;

Output:
pkg.n: 10
sr_pkg.n: 5

4.PRAGMA RESTRICT_REFERENCE------->Purity rules of Functions.


It was used to fix the 'purity level' of a program, i.e. whether it writes/reads from/to the database or packages:
PRAGMA RESTRICT_REFERENCES
(function_name, WNDS [, WNPS] [, RNDS] [, RNPS])
Where function_name is the name of the function whose purity level you wish to assert, and the four
codes have the following meanings:
WNDS – Writes No Database State. Asserts that the function does not modify any database tables.
WNPS – Writes No Package State. Asserts that the function does not modify any package variables.
RNDS – Reads No Database State. Asserts that the function does not read any database tables.
RNPS – Reads No Package State. Asserts that the function does not read any package variables.
Here is an example of two different purity-level assertions for functions in the company_financials package:
CREATE OR REPLACE PACKAGE company_financials IS
FUNCTION company_name (company_id_in IN company.company_id%TYPE) RETURN VARCHAR2;
PRAGMA RESTRICT_REFERENCES (company_name, WNDS, WNPS, RNPS);
END company_financials;
CREATE OR REPLACE PACKAGE BODY company_financials IS
FUNCTION company_name (company_id_in IN company.company_id%TYPE) RETURN VARCHAR2 IS
BEGIN
UPDATE emp SET sal = 0;
RETURN ‘bigone’;
END;
END company_financials;
When you attempt to compile this package body you will get the following error:
3/4 PLS-00452: Subprogram ‘COMPANY_TYPE’ violates its associated pragma
because the company_type function reads from the database and the RNDS purity level has been asserted.

5.PRAGMA FLIP FLOPS

7. What is Raise_application_error?

It is a procedure of package DBMS_STANDARD which allows to issue an user_defined error messages from stored
sub program or database trigger. we can define a user defined error message with error number in case of an
exception.
syntax: RAISE_APPLICATION_ERROR(errnum,'errmsg');

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 33
error number must be between -20000 to -20999
message: 2048 bytes
You can report errors to your application and avoid returning unhandled exceptions.

Example :
create or replace procedure new_emp
( p_name in emp.ename%type
, p_sal in emp.sal%type
, p_job in emp.job%type
, p_dept in emp.deptno%type
, p_mgr in emp.mgr%type
, p_hired in emp.hiredate%type := sysdate )
is
invalid_manager exception;
PRAGMA EXCEPTION_INIT(invalid_manager, -2291);
dummy varchar2(1);
begin
-- check hiredate is valid
if trunc(p_hired) > trunc(sysdate)
then
raise_application_error
(-20000
, 'NEW_EMP::hiredate cannot be in the future');
end if;

insert into emp ( ename , sal , job , deptno , mgr , hiredate )


values
( p_name , p_sal , p_job , p_dept , p_mgr , trunc(p_hired) );
exception
when dup_val_on_index then
raise_application_error
(-20001
, 'NEW_EMP::employee called '||p_name||' already exists'
, true);
when invalid_manager then
raise_application_error
(-20002
, 'NEW_EMP::'||p_mgr ||' is not a valid manager');

end;
/

Materialized View s:
Syntax :
CREATE MATERIALIZED VIEW [schema.]mview
Mview_Options
[USING INDEX storage_options]
[{REFRESH [refresh_options] | NEVER REFRESH]
[FOR UPDATE] [{ENABLE|DISABLE} QUERY REWRITE]
AS subbquery;

CREATE MATERIALIZED VIEW [schema.]mview


ON PREBUILT TABLE [{WITH | WITHOUT} REDUCED PRECISION]

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 34
[USING INDEX storage_options]
[{REFRESH [refresh_options] | NEVER REFRESH]
[FOR UPDATE] [{ENABLE|DISABLE} QUERY REWRITE]
AS subbquery;

Mview_Options:

ORGANIZATION {HEAP [storage_options] [COMPRESS int|NOCOMPRESS]


| INDEX idx_organized_tbl_clause
| EXTERNAL external_table_clause }
or
storage_options
[nested_storage_clause]
[LOB/Modify LOB Storage clause] [lob_partition_storage]
[varray_clause] [lob_partition_storage]
[COMPRESS int|NOCOMPRESS]
[Partitioning clause] [LOGGING | NOLOGGING]
[CACHE | NOCACHE][PARALLEL int | NOPARALLEL]
[BUILD {IMMEDIATE|DEFERRED}]
or
CLUSTER cluster (column,...) [Partitioning clause]
[PARALLEL int | NOPARALLEL] [BUILD {IMMEDIATE|DEFERRED}]

storage_options:
PCTFREE int
PCTUSED int
INITRANS int
MAXTRANS int
STORAGE storage_clause
TABLESPACE tablespace

refresh_options:
FAST | COMPLETE | FORCE
ON [DEMAND | COMMIT]
{NEXT | START WITH} date
WITH {PRIMARY KEY | ROWID}
USING DEFAULT {MASTER|LOCAL} ROLLBACK SEGMENT
USING {MASTER|LOCAL} ROLLBACK SEGMENT rb_segment

idx_organized_tbl_clause:
storage_option(s)
{MAPPING TABLE | NOMAPPING}
[PCTTHRESHOLD int]
[COMPRESS int|NOCOMPRESS]
[ [INCLUDING column_name] OVERFLOW [storage_option(s)] ]

external_table_clause:
([TYPE access_driver_type]
DEFAULT DIRECTORY directory [ACCESS PARAMETERS {USING CLOB subquery |
(opaque_format_spec) }]
LOCATION (directory:'location_specifier'
[,directory2:'location_specifier2'...)
) [REJECT LIMIT {int|UNLIMITED}]

nested_storage_clause:
NESTED TABLE {nested_item | COLUMN_VALUE}

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 35
[ [ELEMENT] IS OF TYPE (ONLY type) ]] | [ [NOT] SUBSTITUTABLE AT ALL LEVELS ]]
STORE AS storage_table
[RETURN AS {LOCATOR|VALUE} ]

Materialized views in Oracle


A materialized view is a stored summary containing precomputes results (originating from an SQL select
statement).
As the data is precomputed, materialized views allow for (seemingly) faster dataware query answers
Types of materialized views
There are three types of materialized views:

• Read only materialized view


• Updateable materialized view
• Writeable materialized view

Read only materialized views


Advantages:

• There is no possibility for conflicts as they cannot be updated.


• Complex materialized views are supported

Updateable materialized views


Advantages:

• Can be updated even when disconnected from the master site or master materialized view site.
• Requires fewer resources than multimaster replication.
• Are refreshed on demand. Hence the load on the network might be reduced compared to using
multimaster replication because multimaster replication synchronises changes at regular intervalls.

Updateable materialized views require the advnced replication option to be installed.


Writeable materialized views
They are created with the for update clause during creation without then adding the materialized view to a
materialized view group. In such a case, the materialized view is updatable, but the changes are lost when
the materialized view refreshes.
Writeable materialized views require the advnced replication option to be installed.
Query rewrite
... yet to be finished ..
The query rewrite facility is totally transparent to an application which needs not be aware of the existance
of the underlying materialized view.
Refreshing process
Refreshing a materialized view
Refreshing a materialized view synchronizes is with its master table.
Oracle performs the following operations when refreshing a materialized view. In the case of a complete
refresh (using dbms_mview.refresh)

1. sys.snap$ and sys.mlog$ are updated to reflect the time of the refresh.
2. The materialized base view is truncated.

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 36
3. All rows selected from the master table are inserted into the snapshot base table.
4. sys.slog$ is updated to reflect the time of the refresh.

In the case of a fast refresh, the steps are:

1. sys.snap$ and sys.mlog$ are updated to reflect the time of the refresh.
2. Rows in the materialized base view are deleted.
3. All rows selected from the master table are inserted into the snapshot base table.
4. sys.slog$ is updated to reflect the time of the refresh.
5. Rows that are not needed anymore for a refresh by any materialized view are deleted from the
materialized view log (<schema name>.MLOG$_table)

If a materialized view is being refreshed can be checked by querying the type of v$lock: if the type is JI a
refresh is being performed.
The following query checks for this:
select
o.owner "Owner",
o.object_name "Mat View",
username "Username",
s.sid "Sid"
from
v$lock l,
dba_objects o,
v$session s
where
o.object_id = l.id1 and
l.type ='JI' and
l.lmode = 6 and
s.sid = l.sid and
o.object_type = 'TABLE'

Scope of Performance Tuning


There is four main area for Performance Tuning.
1. SQL Tuning – Responsibility of the Developer
2. Database Tuning – Responsibility of the Database Administrator
3. System Tuning – Responsibility of the System Administrator
4. Network Tuning – Responsibility of the Network / LAN / WAN Administrator.

SQL Tuning
1. Find the problem to a single SQL
You may be lucky and know already the exact SQL causing the problem. If so, move straight on to the second step. Otherwise, click on
the link above for help on finding the problem SQL.
2. Analyze the SQL to determine the nature of the problem
Most performance problems are quite common and easy to fix. This section will describe some of these and how to spot them, and then
go on to describe a more general analysis method.
3. Fix the problem.
Almost every performance problem has a solution; it’s just that some are more complex than others. In order of increasing complexity
and expense, such fixes include:
• Analyze the underlying table to give Oracle’s Cost Based Optimizer the information it needs to resolve the SQL
efficiently.
• Add one or more hints to the SQL to encourage or discourage certain execution plans.
• Minor changes to the SQL to encourage or discourage certain execution plans.

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 37
• Restructure a poorly designed SQL that cannot be resolved efficiently.
• Alter the underlying infrastructure. eg. Add or change (or even remove!) indexes; introduce clusters, partitions or
index-organised tables; denormalize tables; use materialized views. Note that these actions venture outside the
scope of this document, and should only be performed with the prior permission of (and preferably assistance
from) the DBA and/or System Architect.
• Refer the problem to the database administrator. Possible solutions here would include tuning the Oracle instance,
restructuring or moving tablespaces, or archiving old data.
• Refer the problem to the System Adminstrator. Possible solutions may include reconfiguration of existing
hardware, or acquisition of new hardware.
Database Tuning
For optimum performance an Oracle database should be regularly tuned. Only tune a database after it has been up and running for a
little while.
• Tuning the cache hit ratio
• Tuning the library cache
• Tuning the log buffer
• Tuning buffer cache hit ratio
• Tuning sorts
• Tuning rollback segments
• Identifying missing indexes
• Identifying index fragmentation
• Identifying free list contention
• Identify significant reparsing of SQL
• Reducing database fragmentation
• Rebuilding indexes
• Reduce thrashing or poor system performance (or how to un-tune oracle?!)
System Tuning(Operating System)
Tune your operating system according to your operating system documentation. For Windows platforms, the default settings are
usually sufficient. However, the Solaris and Linux platforms usually need to be tuned appropriately. The following sections describe
issues related to operating system performance:
• Basic OS Tuning Concepts
• Solaris Tuning Parameters
• Linux Tuning Parameters
• HP-UX Tuning Parameters
• Windows Tuning Parameters
• Other Operating System Tuning Information
Details
Network Tuning
Network tuning is the performance optimization and tuning of SQL*Net based on an arbitrary UNP which could be TCP/IP, SPX/IP
or DECnet. SQL*Net performance can be maximized by synchronization with tunable parameters of the UNP, for example, buffer
size.SQL*Net transaction performance can be divided into components of connect time and query time, where
Total SQL*Net (Net8) Transaction Time = Connect Time + Query Time
Connect time can be maximized by calibration of tunable parameters of SQL*Net and the UNP when designing and implementing
networks.
SQL*Net Performance
For this discussion, SQL*Net performance and tuning analysis is based on two categories:
• SQL*Net performance
• SQL*Net tuning

SQL Tuning Tips

• All keywords (SQL Verbs) should be in Upper Case. (e.g. – SELECT, FROM, WHERE etc.)
• Put less cardinality fields on left side in the where clause of the SQL statements.

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 38
• Begin all SQL Verbs on a new line and from same column no.
• Use EXISTS in place of IN (25 mins vs. 2 secs), Use NOT EXISTS in place of NOT IN, wherever possible.
• Use ROWID for Most of the UPDATE
• Use Query Optimizer properly.
• Separate all statement “words” by a single space.
• One should take care for the deallocation of objects so that memory gets release as early as possible. e.g. when
developer opens the cursor it is programmer duty to deallocate cursor after cursor is no longer required.
• Do not create the Indexes on the table unnecessary or do not create too many indexes on the table until it is necessary.
For e.g. create indexes on those columns which are heavily used in the where clause of that table (except primary key.
Note: Primary/ Unique key automatically creates indexes for the columns defined in primary/ unique key).
• Do not use ORDER BY, DISTINCT, GROUP BY clause until it is required as it does the sorting of table and making
query slower.
• Create BITMAP Index on the less cardinality field i.e. when a column is having two/three/four values (e.g. SEX
column in any table as this column will have MALE/FEMALE), Create BITMAP Index subject to condition that this
column is heavily used in where clauses and has less cardinality.
• Use BETWEEN Clause instead of using >= and <=.
• Minimizing the number of table lookups can improve performance of SQL statements. For example: Minimizing the
number of table lookups (sub-queries).
• Avoid Mixed-Mode Expressions Avoid mixed-mode expressions, and beware of implicit type conversions.
NOTE: Always use explicit conversion whenever oracle will look for implicit conversion.
• Watch out for Oracle Internal Conversion Suppression
select product_id, qty
from product
where product_id = 167;
If there is an index on product_id and product_id is a varchar2 datatype, when executed in SQL*Plus, the index will
not be used.
However Oracle internally performs a to_number function on the product_id column prior to executing the statement.
• Do not use SQL functions in predicate clauses or WHERE clauses. The use of an aggregate function, especially in a
subquery, often indicates that you could have held a derived value on a master record.
• Choose an Advantageous Join Order.
Join order can have a significant effect on performance. The main objective of SQL tuning is to avoid performing
unnecessary work to access rows that do not affect the result. This leads to three general rules:
 Avoid a full-table scan if it is more efficient to get the required rows through an index.
 Avoid using an index that fetches 10,000 rows from the driving table if you could instead use another index
that fetches 100 rows.
 Choose the join order so as to join fewer rows to tables later in the join order. The following example shows
how to tune join order effectively:

SELECT info
FROM taba a, tabb b, tabc c
WHERE a.acol between :alow and :ahigh
AND b.bcol between :blow and :bhigh
AND c.ccol between :clow and :chigh
AND a.key1 = b.key1
AMD a.key2 = c.key2;

Thus, if the range of :alow to :ahigh is narrow compared with the range of acol, but the ranges of :b* and :c*
are relatively large, then table taba should be the driving table, all else being equal.

• Use Care When Using IN and NOT IN with a Subquery, Remember that WHERE (NOT) EXISTS is a useful alternative.
• Indexes improve the performance of queries that select a small percentage of rows from a table. As a general guideline,
create indexes on tables that are queried for less than 2% or 4% of the table’s rows. This value may be higher in
situations where all data can be retrieved from an index, or where the indexed columns and expressions can be used
for joining to other tables.

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 39
• Nulls are not equal to anything, Null is not equal to Null so Use the NVL function wherever there is a possibility of
Null values.
• Use the TRUNC function to remove the time portion, from the Date (Data type) variables/columns
• Use appropriate Data type for all local/ global variables declaration
• Don’t Keep unwanted/commented code/ dead code inside the PL/SQL Blocks.
• Use of PLS_INTEGER in-place of NUMBER/ INTEGER Data type where only numeric calculations
• Do not declare any local/ global Variable that is not used.
• Use build-in functions wherever is possible.
• Don’t Pass unneeded parameters in Procedure/ Functions, which are not required.
• Do all cursors use 'for loops' as indicated in the guidelines document?
• Has the code been indented in a proper manner? And Is the code modular and easy to understand?
• If queries have been repeated in multiple places, do they follow the same syntax?
• Have the SELECT statements been optimized for performance?
• Related Functions and procedures must be packaged into packages
• Don’t keep unneeded code inside the Loops.
• Do not create very big PL/SQL Blocks, use middle layered PL/SQL Blocks e.g. approximately 2000-3000 lines.
• Use Packages for PL/SQL Blocks and have procedure inside these Packages and do not create too-many procedure in
a Big Packages.

Oracle's V$ Views
To be finished...
The following views are part of the data dictionary.
See also Oracle's x$ tables
v$archive_dest
Shows all archived redo log destinations. Use this view to find out to which place archived redo logs are
copied: select dest_id,destination from v$archive_dest
These values correspond to the init parameter log_archive_dest_n.
v$archive_dest_status
This view allows to find status and errors for each of the defined
v$archived_log
Displays successfully archived redo logs.
shows received logs on a primary standby database.
v$archive_gap
Lists sequence numbers of the archived los that are known to be missing for each thread on a (physical?)
standby database (highest gap only).
v$archive_processes
This view provides information on the archive processes. It can be used to find out if an ARCH process is
active or not.
v$controlfile
Displays the location and status of each controlfile in the database.
v$controlfile_record_section
See sections in a controlfile.
v$bh
This dynamic view has an entry for each block in the database buffer cache.
The column status can be:

• free
This block is not in use

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 40
• xcur
Block held exclusively by this instance
• scur
Block held in cache, shared with other instance
• cr
Block for consistent read
• read
Block being read from disk
• mrec
Block in media recovery mode
• irec
Block in instance (crash) recovery mode

v$buffer_pool
See buffer pools.
This view's column id can be joined with x$kcbwds.indx
See also x$kcbwbpd
v$buffer_pool_statistics
v$database
This view lets you access database information. For example, you can check (using log_mode) whether or
not the database is in archivelog mode:
ADPDB>select log_mode from v$database;

LOG_MODE
------------
ARCHIVELOG
checkpoint_change# records the SCN of the last checkpoint.
switchover_status: can be used to determine if it is possible to perform a switchover operation Only
available for physical standby databases. Can be:

• NOT ALLOWED,
• SESSIONS ACTIVE,
• SWITCHOVER PENDING,
• SWITCHOVER LATENT,
• TO PRIMARY,
• TO STANDBY or
• RECOVERY NEEDED.

See protection modes in data guard for the columns protection_mode and protection_level.
database_role determines if a database is a primary or a logical standby database or a physical standby
database.
force_logging tells if a database is in force logging mode or not.
v$datafile
This view contains an entry for each datafile of the database.
This view can be used to find out which datafiles must be backed up in a cold backup: select name from
v$datafile

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 41
v$datafile_header
Various information about datafile headers. For example, if you're interested in when the a file's last
checkpoint was:
select name, checkpoint_change#, to_char(checkpoint_time, 'DD.MM.YYYY HH24:MI:SS')
from v$datafile_header
v$dataguard_status
Shows error messages in a data guard environment.
v$db_object_cache
This view displays objects that are cached (pinned) in the library cache. See also dbms_shared_pool.
v$enqueue_stat
If there are a lot of enqueue waits "in" v$session_event or v$system_event, v$enqueue_stat allows to break
down those enqueues in enqueue classes. For each such class, the gets, waits, failures and the cumulative
sum of waited time can be found.
For a list of enqueue types, refer to enqueue types in x$ksqst.
The column cum_wait_time stems from x$ksqst.ksqstwtim.
v$eventmetric
This view is new in Oracle 10g and allows improved timing and statistics.
v$event_name
Contains a record for each wait event.
v$filemetric
This view is new in Oracle 10g and allows improved timing and statistics.
v$filestat
v$fixed_table
This view contains the name of all V$, X$ and GV$ tables. In oracle 8.1.7, there are 187 different v$
tables:
ORA81> select count(*) from v where name like 'V$%';

COUNT(*)
----------
185
If you want to know, which x$ tables there are, do a select name from v$fixed_table where name
like 'X$%';
v$fixed_view_definition
Contains the defintion in its attribute view_definition for the views of v$fixed_table.
v$flash_recovery_area_usage
See also v$recovery_file_dest
v$instance
instance_role can be used to determine if an instance is an active instance (=primary instance) or a
secondary instance (in a standby environment.
dbms_utility.db_version can be used to retrieve the same version as the field version in v$instance.
v$instance_recovery
Can, for example, be used to determine the optimal size of redo logs.
v$latch
Oracle collects statistics for the activity of all latches and stores these in this view. Gets is the number of
successful willing to wait requests for a latch. Similarly, misses is how many times a process didn't
successfully request a latch. Spin_gets: number of times a latch is obtained after spinning at least once.
Sleeps indicates how many times a willing to wait process slept. Waiters_woken tells how often a sleeping
process was 'disturbed'.

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 42
v$librarycache
v$lock
This view stores all information relating to locks in the database. The interesting columns in this view are
sid (identifying the session holding or aquiring the lock), type, and the lmode/request pair.
Important possible values of type are TM (DML or Table Lock), TX (Transaction), MR (Media
Recovery), ST (Disk Space Transaction).
Exactly one of the lmode, request pair is either 0 or 1 while the other indicates the lock mode. If lmode is
not 0 or 1, then the session has aquired the lock, while it waits to aquire the lock if request is other than 0
or 1. The possible values for lmode and request are:

• 1: null,
• 2: Row Share (SS),
• 3: Row Exclusive (SX),
• 4: Share (S),
• 5: Share Row Exclusive (SSX) and
• 6: Exclusive(X)

If the lock type is TM, the column id1 is the object's id and the name of the object can then be queried like
so: select name from sys.obj$ where obj# = id1
A lock type of JI indicates that a materialized view is being refreshed.
A more detailed example can be found here
See also x$kgllk.
v$locked_object
Who is locking what:
select
oracle_username
os_user_name,
locked_mode,
object_name,
object_type
from
v$locked_object a,dba_objects b
where
a.object_id = b.object_id
v$log
Contains information on each log group. See also online redo log.
Comman values for the status column are:

• UNUSED:
Oracle8 has never written to this group,
• CURRENT:
This is the active group.
• ACTIVE:
Oracle has written to this log before, it is needed for instance recovery.
The active log is the one with the current log sequence number
• INACTIVE:
Oracle has written to this log before; it is not needed for instance recovery.

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 43
v$logfile
This view can be queried to find the filenames, group numbers and states of redo log files. For example,
to find all files of group 2, use select member from v$logfile where group# = 2
v$logmnr_contents
See dbms_logmnr.
v$log_history
This view contains an entry for each Log Switch that occured. The column first_time indicates the time of
the first entry???
On physical standby databases, this view shows applied logs.
v$logstdby
Can be used to verify that archived redo logs are being applied to standby databases.
v$managed_standby
Monitors the progress of a standby database in managed recovery mode, more exactly, it displays
information about the activities of log transport service and log apply service.
see here
select process, pid, status, client_process, group# "Stdby Redo Log Gr", block# from
v$managed_standby;
client_process: the corresponding primary database process. If lgwr log transmission is chosen, one row
should have client_process=LGWR. If ARCH transmission is chosen, one row should have ARCH.
v$mystat
This view records statistical data about the session that accesses it. Join statistic# with v$statname.
v$sesstat is also similar to v$sysstat, except that v$sysstat accumulates the statistics as soon as a session
terminates.
See also recording statistics with oracle.
v$nls_parameters
The NLS parameters that are in effect for the session quering this view. The view
NLS_SESSION_PARAMETERS is based on v$nls_parameters. See also v$nls_valid_values.
v$nls_valid_values
This view can be used to obtain valid values for NLS parameters such as

• supported character sets


• languages
• territories
• sorting orders

v$object_usage
v$object_usage gathers information about used (accessed) indexes when an index is monitored using alter
index ... monitoring usage.
See On verifying if an index is used.
v$open_cursor
v$option
This view lets you see which options are installed in the server.
See also dba_registry.
v$parameter
Lists the name-value pairs of the init.ora file (or their default, if not in the init.ora). For example, if you
need to know what your block size is:
select value from v$parameter where name = 'db_block_size'

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 44
The columns isses_modifiable and issys_modifiable can be used to determine if a parameter can be
changed at session level using alter session or at system level using alter system. A parameter is modifiable
at session level if isses_modifiable = 'TRUE'. A parameter is modifiable at system level if issys_modifiable
= 'DEFERRED' or issys_modifiable = 'IMMEDIATE'. However, if a parameter is changed at system level
if issys_modifiable = 'DEFERRED' it only affects sessions that are started after chaning the parameter.
Additionally, the alter system set ... deferred option must be used.
There are also some undocumented (or hidden?) parameters.
v$pgastat
See also pga.
Thanks to Oleg who notified me of a typo (v$pgastat instead of v$pga_stat).
v$process
Join v$process's addr with v$session paddr.
The column traceid is equal to the value used in alter session set .
v$pwfile_users
Lists all users who have been granted sysdba or sysoper privileges. See adding user to a password file.
v$recover_file
Useful to find out which datafiles need recovery.
Join with v$datafile to see filenames instead of numbers....
v$recovery_file_dest
See also v$flash_recovery_area_usage
v$reserved_words
This view can be consulted if one is in doubt wheter a particular word is a reserved word (for example
when writing PL/SQL Code or assigning a password to a user).
Until 10g, the view only consist of two columns: keyword and length. From 10gR2 onwards, it has also
the columns reserved, res_type, res_attr, res_semi and duplicate. Each of these new columns can only
be either 'Y' (meaning: yes) or 'N' (meaning: no)
See also reserved words in SQL and reserved words in PL/SQL.
v$resource_limit
v$rollname
The names of online rollback segments. This view's usn field can be joined with v$rollstat's usn field and
with v$transaction's xidusn field.
v$transaction can be used to track undo by session.
v$rollstat
Statistics for rollback segements
v$session
The column audsid can be joined with sys_context('userenv','SESSIONID') to find out which session is the
"own one". Alternatively, dbms_support.mysid can be used.
The fields module and action of v$session can be set with dbms_application_info.set_module. (See
v$session_longops for an example.
The field client_info can be set with dbms_application_info.set_client_info
Join sid with v$sesstat if you want to get some statistical information for a particular sesssion.
A record in v$session contains sid and serial#. These numbers can be used kill a session (alter system kill
session).
A client can set some information in client_info. For example, RMAN related sessions can be found with
.... where client_info like 'rman%';
What a session is waiting for can be queried with v$session_wait. However, with Oracle 10g, this is not
nessessary anymore, as v$session_wait's information will be exposed within v$session as well.
See also sessions.
Prepared By Venu Thamatam
Venu.thamatam@gmail.com Page 45
v$sessmetric
This view is new in Oracle 10g and allows improved timing and statistics.
v$session_event
This views is similar to v$system_event. However, it breaks it down to currently connected sessions.
v$session_event has also the column max_wait that shows the maximum time waited for a wait event.
v$session_longops
Use v$session_longops if you have a long running pl/sql procedure and want to give feedback on how far
the procedure proceeded.
If the following Procedure is run, it will report its progress in v$session_longops. The Procedure will also
set the module attribute in v$session which makes it possible to find the sid and serial# of the session.
create table f(g number);

create or replace procedure long_proc as


rindex pls_integer := dbms_application_info.set_session_longops_nohint;
slno pls_integer;
-- Name of task
op_name varchar2(64) := 'long_proc';

target pls_integer := 0; -- ie. The object being worked on


context pls_integer; -- Any info
sofar number; -- how far proceeded
totalwork number := 1000000; -- finished when sofar=totalwork

-- desc of target
target_desc varchar2(32) := 'A long running procedure';

units varchar2(32) := 'inserts'; -- unit of sofar and


totalwork
begin

dbms_application_info.set_module('long_proc',null);

dbms_application_info.set_session_longops (
rindex,
slno);

for sofar in 0..totalwork loop

insert into f values (sofar);

if mod(sofar,1000) = 0 then
dbms_application_info.set_session_longops (
rindex,
slno,
op_name,
target,
context,
sofar,
totalwork,
target_desc,
units);

end if;

end loop;

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 46
end long_proc;
If the procedure long_proc is run, you can issue the following query to get feedback on its progress:
select time_remaining,sofar,elapsed_seconds
from v$session_longops l, v$session s
where l.sid=s.sid and l.serial# = s.serial# and s.module='long_proc'
v$session_wait
This views shows what wait event each session is waiting for, or what the last event was that it waited for.
In contrast, v$session_event lists the cumulative history of events waited for in a session.
The columns P1, P2 and P3 are parameters that are dependant on the event. With Oracle 10g,
v$session_wait's information will be exposed within v$session as well.
Since 10g, Oracle displays the v$session_wait information also in the v$session view.
v$session_wait_history
This view is new in Oracle 10g and allows improved timing and statistics.
v$sesstat
This view is similar to v$mystat except that it shows cumulated statistics for all sessions.
Join sid with v$session and join statistic# with v$statname.
v$sesstat is also similar to v$sysstat, except that v$sysstat accumulates the statistics as soon as a session
terminates.
v$sga
Shows how much memory the shared global area uses. Selecting * from v$sga is roughly the same as
typing show sga in sql plus with the exeption that the latter also show the total.
v$sgastat
Showing free space in the sga:
select * from v$sgastat where name = 'free memory'
v$sga_dynamic_components
Information about SGA resize operations since startup.
This view can also be used to find out the granule size of SGA components.
v$sga_resize_ops
v$sort_usage
See temporary tablespaces
v$sort_segment
See Temporary Tablespaces
v$spparameter
Returns the values for the spfile.
v$sql
v$sql is similar to v$sqlarea, the main difference being that v$sql drills down to select * from x$kglob
whereas v$sqlarea drills down to select sum from x$kglob. See also here.
v$sqlarea
Join v$sqlarea's address with v$session's sql_address.
Find the SQL-text of currently running SQL statements:
select sql_text from v$sqlarea where users_executing > 0;
The field version_count indicates how many versions an sql statement has.
v$sqltext
v$sql_plan
variable addr varchar2(20)
variable hash number
variable child number

exec :addr := '&sqladdr'; :hash := &hashvalue; :child := &childno;

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 47
select lpad(' ', 2*(level-1))||operation||' '||
decode(id, 0, 'Cost = '||position) "OPERATION",
options, object_name
from v$sql_plan
start with (address = :addr
and hash_value = :hash
and child_number = :child
and id=0 )
connect by prior id = parent_id
and prior address = address
and prior hash_value = hash_value
and prior child_number = child_number
order by id, position ;
In order to find valid values for sqladdr, hashvalue and childno, this SQL statement can be used:
select sql_text,address,hash_value,child_number from v$sql where users_executing > 0;
v$sqltext_with_newlines
This view can be used to construct the entire text for each session's actual SQL statement. Use the
following statement to to that:
set serveroutput on size 1000000

declare
v_stmt varchar2(16000);
v_sql_text v$sqltext_with_newlines.sql_text%type;
v_sid v$session.sid%type;
begin
for r in (
select
sql_text,s.sid
from
v$sqltext_with_newlines t,
v$session s
where
s.sql_address=t.address
order by s.sid, piece) loop

v_sid := nvl(v_sid,r.sid);

if v_sid <> r.sid then


dbms_output.put_line(v_sid);
<a href='oru_10028.html'>put_line</a>(v_stmt,100);
v_sid := r.sid;
v_stmt := r.sql_text;
else
v_stmt := v_stmt || r.sql_text;
end if;

end loop;
dbms_output.put_line(v_sid);
dbms_output.put_line(v_stmt,100);

end;
/
Thanks to Sarmad Zafar who notified me of an error in this PL/SQL Block.
Note: the function put_line is found here and can be used to prevent ORU-10028.

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 48
v$sql_bind_data
Join cursor_num with cno of v$sql_cursor.
v$sql_bind_capture
New with Oracle 10g
This view captures bind variables for all sessions and is faster than setting 10046 on level 4.
v$sql_cursor
Join parent_handle with address of v$sql or v$sqlarea.
v$sql_workarea
v$sql_workarea can be joined with v$sqlarea on address and hash_value, and it can be joined with v$sql on
address, hash_value and child_number.
v$standby_log
v$statname
Use this view to get decoded names for the statistic# field of v$mystat, v$sysstat and v$sesstat.
v$sysaux_occupants
v$sysaux_occupants doesn't exist in Oracle versions prior to Oracle 10g.
See occupants in the sysaux tablepsaces.
v$sysmetric
This view is new in Oracle 10g and allows improved timing and statistics.
v$sysmetric_history
This view is new in Oracle 10g and allows improved timing and statistics.
v$sysstat
v$sysstat is similar to v$sesstat. While v$sesstat displays statitics for the current session, v$sysstat displays
the cumulated statitics since startup of the database.
For example, it is possible to find out the CPU time (name = 'CPU used by this session')
This view is (among others) used to calculate the Hit Ratio.
v$system_event
This view displays the count (total_waits) of all wait events since startup of the instance.
If timed_statistics is set to true, the sum of the wait times for all events are also displayed in the column
time_waited.
The unit of time_waited is one hundreth of a second. Since 10g, an additional column
(time_waited_micro) measures wait times in millionth of a second.
total_waits where event='buffer busy waits' is equal the sum of count in v$waitstat.
v$enqueue_stat can be used to break down waits on the enqueue wait event.
While this view totals all events in an instance, v$session_event breaks it down to all currently connected
sessions.
v$undostat
undo tablespaces
v$tempfile
v$tempseg_usage
v$tempseg_usage is a public synonym for v$sort_usage.
v$tempstat
v$thread
The Oracle SID can be retrieved through select instance from v$thread
v$timer
This view has only one column (hsecs) which counts hundreths of seconds. Whenever it overflows four
bytes, it starts again with 0.

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 49
v$transaction
Important fields of v$transaction are used_ublk and used_urec. They tell of how many blocks and records
the undo for a transaction consists. In order to find out the name of the corresponding rollback segemnt,
join the xidusn field with the usn field of v$rollname. This is demonstrated in
Transactions generate undo
v$timezone_names
See also timezones for some values of tzabbrev.
v$transportable_platform
Which platforms are supported for cross platform transportable tablespaces.
v$version
Use this view to find out what version you actually work on: select * from v$version;
BANNER
----------------------------------------------------------------
Oracle8i Enterprise Edition Release 8.1.7.0.0 - Production
PL/SQL Release 8.1.7.0.0 - Production
CORE 8.1.7.0.0 Production
TNS for 32-bit Windows: Version 8.1.7.0.0 - Production
NLSRTL Version 3.4.1.0.0 - Production
v$waitstat
total_waits where event='buffer busy waits' is equal the sum of count in v$system_event.

Static data dictionary views


To be finished...
The following views are part of the data dictionary.
Find all views along with a comment in dict:
select * from dict;
USER_ / ALL_ / DBA_
Most static dictionary views come with three prefixes: USER_*, ALL_* and DBA_*. For example, there's
a user_tables, all_tables and a dba_tables view. For brevity, I only give the names of the views that start
with dba_.
Generally, the user_ views show database objects owned by the user who is querying the user_ view.
The all_ views show the database objects that are accessible to the user who is querying the all_view.
The dba_ views show all database objects.
Table related data dictionary views

• dba_tables
• dba_tab_columns
• dba_all_tables
• dba_tab_comments
• dba_col_comments
• dba_external_tables
• dba_external_locations
• dba_tab_histograms
• dba_tab_statistics
• dba_tab_col_statistics
• dba_tab_modifications
• dba_encrypted_columns

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 50
• dba_unused_col_tabs
• dba_partial_drop_tabs

Registry related data dictionary views

• dba_registry,
• dba_registry_hierarchy,
• dba_registry_history,
• dba_registry_log

XML DB related views

• dba_xml_schemas
• dba_xml_tables
• dba_xml_views
• dba_xml_views_cols

Audit related views

• dba_audit_exists
• dba_audit_object
• dba_audit_policies
• dba_audit_policy_columns
• dba_audit_session
• dba_audit_statement
• dba_audit_trail
• dba_common_audit_trail
• dba_fga_audit_trail
• dba_opj_audit_opts
• dba_priv_audit_opts
• dba_repaudit_attribute
• dba_repaudit_column
• dba_stmt_audit_option_opts

Other static data dictionary views


dba_advisor_findings
Exposes the Oracle 10g's advisors tips.
See also dbms_sqltune
dba_advisor_recommendations
Exposes the Oracle 10g's advisors tips.
See also dbms_sqltune
dba_advisor_rationale
Exposes the Oracle 10g's advisors tips.
See also dbms_sqltune
dba_advisor_tasks
Exposes the Oracle 10g's advisors tips.
See also dbms_sqltune
Prepared By Venu Thamatam
Venu.thamatam@gmail.com Page 51
dba_arguments
This view can be used to find out what arguments a procedure's or object type's function/procedure has.
See this page for an example of a select statement, or this pagea.
dba_col_privs
dba_constraints
Derives from con$. Records the constraints.
See also On identifiying parent and child tables.
dba_datapump_jobs
This view monitors data pump jobs.
dba_data_files
If a datafile has autoextend on and unlimited maxsize, the maxsize is reported with a ridiciculous high
number such as 1.7180E+10.
file_id vs relative_fno: file_id is unique in a database while relative_fno is 'only' unique for datafiles
within a tablespace.
dba_db_links
dba_directories
Displays all directories that were created with create directory.
Note: There's no user_directories, only dba_directories and all_directories exist!
defcall
This is a view that belongs to the replication catalog.
defdefaultdest
This is a view that belongs to the replication catalog.
deferror
This is a view that belongs to the replication catalog.
It records entries in the error queue.
defpropagator
This is a view that belongs to the replication catalog.
deftran
This is a view that belongs to the replication catalog.
defcalldest
This is a view that belongs to the replication catalog.
deferrcount
This is a view that belongs to the replication catalog.
deflob
This is a view that belongs to the replication catalog.
defschedule
This is a view that belongs to the replication catalog.
deftrandest
This is a view that belongs to the replication catalog.
Use dbms_defer_sys.delete_tran to get rid of entries in deftrandest.
This view records entries in the deferred transaction queue.
flashback_transaction_query
Used for Flashback transaction queries. (See flashback transaction query example)

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 52
global_name
dba_indexes
dba_jobs
dba_jobs_running
dba_lobs
dba_logstdby_log
Can be used to verirfy that archived redo log are being applied to standby databases.
dba_logstdby_not_unique
dba_logstdby_parameters
dba_logstdby_progress
dba_logstdby_skip
dba_logstdby_skip_transaction
dba_mviews
dba_objects
Displays information about objects.
all_olap2_aw_cubes
Shows all cubes in all analytic workspaces.
all_olap2_aw_dimensions
dba_plsql_object_settings
Stores the values of the following initialization parameters as of compilation time:

• plsql_ccflags
• plsql_code_type
• plsql_debug
• plsql_optimize_level
• plsql_warnings
• nls_length_semantics

dba_procedures
The column procedure_name is null for procedures and functions, it is only set for procedures and
functions in pl/sql packages. The procedures' and functions' names are found in the column object_name,
however, using dba_procedures, it is not possible to find out if it is a procedure or function. This is possible
with dba_objects.
dba_profiles
Allows to see the profiles and their settings.
dba_queues
dba_queue_tables
See drop table.
dba_recyclebin
Displays the object in the recycle bin for the currently logged on user.
recyclebin is a synonym for user_recyclebin.
dba_refresh
dba_registered_mview_groups
This is a view that belongs to the replication catalog.
See also materialized view group.
dba_registry
dba_repcat_refresh_templates
This is a view that belongs to the replication catalog.
dba_repcat_template_objects
This is a view that belongs to the replication catalog.
Prepared By Venu Thamatam
Venu.thamatam@gmail.com Page 53
It keeps track of deployent templates.
dba_repcat_template_parms
This is a view that belongs to the replication catalog.
dba_repcat_template_sites
This is a view that belongs to the replication catalog.
dba_repcat_user_authorizations
This is a view that belongs to the replication catalog.
dba_repcat_user_parm_values
This is a view that belongs to the replication catalog.
dba_repcatlog
This is a view that belongs to the replication catalog.
It can be used to track administrative requests.
dba_repcolumn
This is a view that belongs to the replication catalog.
dba_repcolumn_group
This is a view that belongs to the replication catalog.
dba_repconflict
This is a view that belongs to the replication catalog.
dba_repddl
This is a view that belongs to the replication catalog.
dba_repextensions
This is a view that belongs to the replication catalog.
dba_repgenobjects
This is a view that belongs to the replication catalog.
dba_repgroup
This is a view that belongs to the replication catalog.
dba_repgroup_privileges
This is a view that belongs to the replication catalog.
dba_repgrouped_column
This is a view that belongs to the replication catalog.
dba_repkey_columns
This is a view that belongs to the replication catalog.
dba_repobject
This is a view that belongs to the replication catalog.
dba_repparameter_column
This is a view that belongs to the replication catalog.
dba_reppriority
This is a view that belongs to the replication catalog.
dba_reppriority_group
This is a view that belongs to the replication catalog.
dba_repprop
This is a view that belongs to the replication catalog.
dba_represol_stats_control
This is a view that belongs to the replication catalog.
dba_represolution
This is a view that belongs to the replication catalog.
dba_represolution_method
This is a view that belongs to the replication catalog.

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 54
dba_represolution_statistics
This is a view that belongs to the replication catalog.
dba_repsites
This is a view that belongs to the replication catalog.
dba_repsites_new
This is a view that belongs to the replication catalog.
dba_rewrite_equivalences
This view can be used to show the equivalences that were established using
dbms_advanced_rewrite.declare_rewrite_equivalence.
dba_roles
This view lists all roles except the special role public.
select name, ##A(decode/ora/sql/decode.html)(password, null, 'NO', 'EXTERNAL',
'EXTERNAL',
'GLOBAL', 'GLOBAL', 'YES')
from user$
where type# = 0 and name not in ('PUBLIC', '_NEXT_USER')
dba_role_privs
Lists roles that are assigned to a either another role or a user.
Here is a script that uses dba_role_privs to recursively list privileges assigned to users and roles.
dba_segments
This view shows information about segments.
dba_sequences
dba_sequences is a bit special: Unlike dba_tables, dba_indexes, dba_triggers, dba_constraints,
dba_db_links, dba_jobs, dba_queue_tables and dba_queues, there is no column owner but
sequence_owner.
dba_source
dba_sqltune_binds
This view can be used to get the SQL tuning advisors recommondations.
dba_sqltune_plans
This view can be used to get the SQL tuning advisors recommondations.
dba_sqltune_statistics
This view can be used to get the SQL tuning advisors recommondations.
dba_synonyms
Show all synonyms.
dba_sys_privs
Lists system privileges that are assigned to a either another role or a user.
dba_scheduler_job_run_details
system_privilege_map
Lists all system privileges.
These privileges can be audited.
all_sumdelta
Lists direct path load entries accessible to the current user.
dba_tab_privs
all_tab_privs_made
There is no dba_tab_privs_made, only user_tab_privs_made and all_tab_privs_made.
All_tab_privs_made view lists all object privileges that the current either has granted or for for which he
owns the underlying object.
User_tab_privs_made displays only grants for which the current user is the object owner.

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 55
These views are not role-recursive. That is to say, if I grant an object privilege to a role, and then grant that
role to a user, this view doesn't show me that the user has that object's privilege.
A related view is all_tab_privs_recd.
all_tab_privs_recd
There is no dba_tab_privs_recd, only user_tab_privs_recd and all_tab_privs_recd.
A related view is all_tab_privs_made.
dba_triggers
See also Getting the nth source code line of a trigger.
dba_ts_quotas
Can be used to find out how big the quota of a user is on a tablespace and how much thereof he has already
occupied.
dba_users
Has a record for each user in the database.
The related view user_users has only one row: the one that belongs to the user selecting from user_users.
See also Who am I.
dba_tablespaces
Displays the tablespaces of a database.
dba_views

Prepared By Venu Thamatam


Venu.thamatam@gmail.com Page 56

S-ar putea să vă placă și