You are on page 1of 29

1) what is mean by oracel instance?

2) what is shared pool?


3) what is mean by index?

4) what is use of synonym?


Table reference can be complicated if a schema or database link is included.the synonym will rename the
table referenced.
synonym is a data dictionary object and is ceated by
CREATE SYNONYM synonymname FOR reference.

5) what is sequence?
A sequence is a oracle object that is used to generate unique numbers.
A sequence is created using with CREATE SEQUENCE DDL command.
A sequence is accessed with SEQUENCE.NEXTVAL or SEQUENCE.CURRVAL
A CURRVAL can be accessed only after at least one NEXTVAL has been issued.
Once created can be used in any number of tables.

6) what is coorelated subquery give an example?


7) criteria for creteing a database? what is mean by normalization?
8) what is query hint?
9) diff between procedure and function?
10) diff between procedure and package?

11) what is mean by pragma? types of it?


Pragma are compiler directives.
they serve as instruction to the pl/sql
the compiler will act on the pragma during the compilation of the block.
example
RESTRICTED_REFERENCEs
AUTONOMOUS_TRANSCTION
EXCEPTION_INIT

12) what is mean by autonamous transaction?


An autonomous transaction is a transaction that is started within the context of another transaction know as
parent transaction but is independent of it.
The autonomous transaction can be commited or rollbacked reardless of parent transaction.
The block is marked as autonomous by using a pragma in the decalrative section.PRAGMA
AUTONOMOUSE_TRANSACTION must appear in the decalrative section and only one is allowed.
Location of autonomous Block:
a)Top-level anonymous block
b)Local,stand alone and packaged subprograms
c)Methods of an object type
d)Database Trigger.
Nested pl/sql blocks cannot be autonomous also only individual subprogram within a package can be
marked as autonomous the package itself cannot be.
Properties of autonomous transaction:
It begins with first sql statement and ends with COMMIT or ROLLBACK.
Any transaction control statement can be used in transaction includes
COMMIT,ROLLBACK,SAVEPOINT,ROLL BACK TO SAVEPOINT and SET TRANSACTION.
Ending an autonomouns TRansactions:
Ends with Commit or Rollback.
It does not end if Block containing End.
if autonomous Block ends without ending the transaction an error occur.

13) diff between function and trigger?


14) can u decrease the size of the column when there is values in it?
15) what is views?
16) what is mean by filters?
18) delete duplicte from a column?
19) delete null value from column?
20) tell about full outer join?

21) what is database link?


A database link is a reference to a remote database which can be located in completetly different system
from the local database.
DDL Statement to create database link:
CREATE DATABASE LINK link_name
CONNECT TO user_name IDENTIFIED BY password
USING sqlnet_string
Update students@link_name set major = 'Music' where id = 10005;
If you sql * NET the we can take advantage of databae link.

22) what is autonomous transaction?

23) what is bulk bind? what is bult collect?


bulk binding is a technique by which the entire pl/sql table is passed to sql engine in one step. They are
done using FORALL Statement.
a)fill in array(table)
b)by using for loop insert into table in one step
forall v_count in 1..400
insert into temp_table values (v_number(v_count),v_chars(v_count));
end;

24) what are ll the built in packags u used in a project?


DBMS_OUTPUT.PUTLINE
used to print result on screen.

25) what is cursor? what are all the types of cursor?


In order to process a sql statement, oracle will allocate an area of memory known context area.The context
area contains information nessary to complete the process including the number of rows processed by the
statement.A cursor is a handle or pointer to the context area.
There are two types of cursors
a)implicit cursor.
b)Explicit cursor.

25)a)What is explicit cursor and Explain the process of the cursor?


It is the cursor where name is explicitly assigned to a select statement via the CURSOR.....IS statement.
Four steps are required for cursor process
a)Declare a cursor.
b)Open a cursor fro a query.
c)Fetch the result into pl/sql variable.
d)Close the cursor.
DECLARING CURSOR:
Declaring a cursor defines name of the cursor and assotiated SELECT statement.
CURSOR cursor_name IS select_statement.
NOTE:select_statement contains no INTO clause. when using explicit cursor the INTO clause is a part of
FETCH statement.
A CURSOR declaration can refrence pl/sql variable as well.
Declare
v_department classes.department%type
v_cursor classes.course%type
CURSOR c_classes IS
SELECT * FROM CLASSES where department = v_department and course = v_course
OPENING A CURSOR:
OPEN cursor_name
The value of bind variable are examine.
Based on the value of the bind variable and the contents of the tables referenced in the query the active set
or the set of row match the query is determined.
The active point is set pointer to first row.
IF refrenced PL/SQL variable in the cursor changed after OPEN cursor_name it does not change the active
set of query.To change the cursor actie set it must be closed and open again.
Once a CURSOR has been opened it cannot be reopened unless it is closd.
FETCH FORM CURSOR:
the INTO clause of the query is part of the FETCH statement.
FETCH cursor_name INTO list_of_variable
OR
FETCH cursor_name INTO pl/sql record.
After each fetch the active set pointer is increased to the next row.
CLOSING A CURSOR:
When all of the active set has been retrived, the cursor should be closed nd resources associatd with it can
be freed(storage used to hold the active set and temporary space used to etermined the active set.
CLOSE cursor_name.

25)b)What is cursor attribute?


There are four cursor attribute available.
%FOUND,%NOTFOUND,%ISOPEN,%ROWCOUNT
Cursor Attributes are appended to CURSOR name.
They return a value which can be used in expression.
%FOUND:
It is an boolean attribute.
It return TRUE if FETCH return a row and FALSE if it didn't.
IF %FOUND is checked before opening a cursor an error will raised.
%NOTFOUND:
Behaves opposite to %FOUND.
If prior fetch is return a row the %NOTFOUND returns false else return TRUE.
%ISOPEN:
This Boolean attribute used to determine whether or not the associated cursor is open.
IF open then return TRUE else return FALSE.
%ROWCOUNT:
This is numberic attribute returns the number of rows fetched by the cursor so far.

25)c)What is parameterised Cursor?


This is an additional way of using bind variables in a sursor.
A parameterized cursor takes argument similar to procedure.
open statement is used to pass the actual value into the cursor.

e.g
Declare
v_department classes.department%type
v_cursor classes.course%type
CURSOR c_classes IS
SELECT * FROM CLASSES where department = v_department and course = v_course
OPENING A CURSOR:
OPEN cursor_name

Can be converted into Parameterized as


Declare
CURSOR c_classes(v_department classes.department%type,v_cursor classes.course%type
IS
SELECT * FROM CLASSES where department = v_department and course = v_course;

OPEN c_classes('HIS',101);

25)d)What is implicit cursor or SQL cursor?


All SQL statements are executed inside the context area and thus have a cursor that points to that context
area.This cursor is knon as SQL cursor or Impicit Cursor.
PL/SQL implicitly opens the sql cursor process the sql statement in it and closes the cursor afterwards.
The Implicit cursor is used to process INSERT,DELETE,UPDATE and SELECT...INTO statements.
SQL cursor attributes are avilable SQL%FOUND,SQL%NOTFOUND,SQL%ROWCOUNT,SQL
%ISOPEN(always FLASE)

25)e)What are cursor fetch loops?


The most common operation of the cursor is to fetch all of the rows in the active set. This done via fetch
loop. It is simply a loop that process each of the rows in the active set, one by on.Types of fetch loops are
Simple loop:
The simple Loop syntax is (LOOP…END LOOP) is used fro cursor processing.
Explicit cursor attributes are used to control how many times the loop execute along with EXIT WHEN
statement.
LOOP
---
---
EXIT WHEN cursor_name%NOTFOUND
END LOOP;
While Loop:
A cursor FETCH loop can also be constructed using the WHILE….LOOP.
FETCH c_history INTO v_studentdata
WHILE c_historystudents%found LOOP
--
--
FETCH c_history INTO v_studentdata
END LOOP
FETCH is used before and inside the while loop.(two fetch is used) This is because loop condition is
checked.
Cursor for loop:
This is used to implicitly handle the cursor processing(open,fetch,close)
FOR Count_variable IN Cursor_Name LOOP
--
--
End Loop;
Implicit FOR Loop:
In addition to the record , the cursor itself can be implicitly declared.
For v_studentata IN (select id,first_name,last_name from students where major = ‘HISTORY’) LOOP
--
--
END LOOP;
In this case both the record v_studentdata ad the cursor are implicitly declared. The cursor has no Name

25)f)Difference between NO DATA FOUND and %NOTFOUND


NO_DATA_FOUND:
Exception is raised only for SELECT…INTO statement when WHERE caluse of the query Does not match
any row.
%NOTFOUND:
If the WHERE clause of an UPDATE or DELETE statement does not match any rows, SQL%NOTFOUND
is set TRUE rather than raising NO_DATA_FOUND exception.
25)g)What is FOR UPDATE OF?
FOR UPDATE is used for exclusive row lock on the rows in the active set. This lock prevent other session
to from changing the rows in the active set until the transaction is commited or rollbacked.
It is part of select statement. It is legally the last clause of the statement., after the ORDER BY.
SELECT…FROM…FOR UPDATE [OF column_referenced][NOWAIT]
Column_referenced is a column in the table against which the query is performed. A list of column can be
used.
SELECT…FOR UPDATE will be wait if other session lock on rows in the active set. There is no time-out
for this waiting period so it will hang until the other session will release the lock. If we use NOWAIT
clause it wont wait and return with an error.

What WHERE CURRENT OF clause does in a cursor?


WHERE CURRENT OF:
If the cursor is declared with FOR UPDATE OF clause, the WHERE CURRENT OF clause can be used in
an UPDATE or DELETE.
WHERE CURRENT OF cursor;
It is not advisable to use commit inside the loop of SELECT…FOR UPDATE because lock will be released
and error will throw on next fetch.

25)h)What is cursor variable?


A cursor variable On other hand can be associated with different query at runtime.
Cursor variable are analogous to pl/sql variable.
Static Cursor are analogous to pl/sql constants.
Declaring Cursor Variable:
A cursor variable is reference type so no storage is allocated for it when it is declared. It refers to different
storage location as the program runs.
In order to use a cursor variable it must be declared. Storage for it is allocated at run time because a cursor
variable is REF type. Reference type is declared as follows.
REF type
Where type is previously declared.
The REF keyword indicates that the new type will be a pointer to the defined type.
(what is ref cursor? )
The type of cursor variable is REF CURSOR
TYPE type_name IS REF CURSOR [RETURN return_type];
The return_type for the cursor variable must be a record.
(What are the types of Cursor variable?)
Cursor variable declared for specific return type is called CONSTRAINED cursor variables .
An UNCONSTRAINED cursor variable does not have a RERTURN clause.
Opening a cursor variable:
OPEN cursor variable FOR select_statement.
DECLARE
TYPE t_classesref is REF CURSOR RETURN classes%rowtype;
V_classesCV t_classesCV
OPEN v_classesCV FOR Select * from classes.

The following will raise an error because the select list does not match.
OPEN v_classesCV FOR Select department, course from classes.

25)i)What are the restriction of cursor variable?


Cursor variable cannot be defined in a package. The type itself can but the variable cannot.
Remote program cannot return the value of a cursor variable.
PL/SQL collections(index-by tables, nested tables, varray) cannot store nested variable.

27) what is exception?


Exceptions are designed for run-time error handling rather than compile-time error handling.
When an error occurs an exception is raised when this happens, control is passed to the exception handler
which is separate section of the program.
There are two types of exception.
User-defined
pre-defined.
USER DEFINED:
A user defined exception is an error that is defined by programmer.
User defined exceptions are declared in the declarative section of pl/sql block.
Like variable exceptions have a type “EXCEPTION”.
Declare
e_toomanystudents EXCEPTION;

PREDEFINED EXCEPTIONS:
Oracle has predefined several exceptions that corresponds to the most common oracle errors. The
identifiers for this exceptions are defined STANDARD package so it is not necessary to declare them in the
declarative section like user-defined.
It is possible to associate user-defined exception with oracle errors.
Some pre-defined exceptions.
DUP_VAL_ON_INDEX
INVALID_CURSOR
TRANSACTION_BACKED_OUT
NO_DATA_FOUND
TOO_MANY_ROWS

RAISING EXCEPTION:
When the error associated with an exception occurs the exception is raised.
The user-defined exceptions are raised explicitly via RAISE statement.
The Pre-defined exception(or user defined exception associated with an oracle error through
EXCRPTION_INIT pragma) are raised implicitly when their associated oracle error occurs.
If the oracle error that is not associated with an exception occurs this exception is caught by OTHERS
handler.

HANDLING EXCEPTION:
When exception is raised the control is passed to exception section of the block.
The exception section consists of handler for some or all exceptions.
An exception handler contains the code that is executed when the error associated with the exception
occurs.
EXCEPTION
WHEN exception_name THEN
Sequence of statement
WHEN exception_name THEN
Sequence of statement
WHEN OTHERS THEN
Sequence of statement
END;

OTHERS Exception Handler:


This is an special exception handler defined by pl/sql.
This handler will execute for all raised exceptions that are not handled by any other WHEN clause.

SQLCODE and SQLERRM:


Inside the others handler it is often useful to know which oracle error raised the exception. By using
sqlcode and sqlerrm it will be achieved.
For pre define exceptions SQLCODE returns the current error code and SQLERRM returns the current
error message text. IF error text is more than 200 character itself cause VALUE_ERROR
For user defined exceptions SQLCODE return 1 and SQLERRM return USER-DEFINED exception.
SQLCODE and SQLERRM are assign to local variable and then these variables are used in SQL because
both functions are procedural so they cannot be used directly in SQL statement.

EXCEPTION_INIT Pragma:
You can associate a named exception with a particular oracle error. This gives the ability to trap this error
specially rather than via an OTHER handler. This is done by EXCEPTION_INIT pragma.
PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number) ;
Declare
E_missingnull EXCEPTION;
PRAGMA EXCEPTION_INIT(e_missingnull, -1400);
Begin
---
EXCPTION
When e_missingnull then
End;

RAISE_APPLICATION_ERROR:
You can use the built-in function RAISE_APPLICATION_ERROR to create your own error message it can
be more descriptive than named exceptions..
RAISE_APPLICATION_ERROR(error_numbr,error_message,[keep_message]);
By using this no special error handling is nessary for user-defined errors Vs pre-defined errors.

EXCEPTION PROPAGATION:
An exception can be occur in declarative, executable or exception section of a pl/sql block .
EXCEPTION RAISED IN THE EXECUTABLE SECTION:
1) If the current block has the handler for the exception, executes it and complete the block
successfully control will pass to enclosing block.
2) If there is no handler for the current exception, propagates the exception to by raising it in enclosig
block.
EXCEPTION RAISED IN THE DECLARATIVE SECTION:
If the declarative section raise an exception the exception is immediately propagates to the
enclosing block(not with in current block of EXCEPTION SECTION).
EXCEPTION RAISED IN THE EXCEPTION SECTION:
The exception is propagated to the enclosing block.

28) what is numberic FOR loop?


Simple loop and while loop iterations are not known in advance but numeric for loop on other hand have
defined number of iterations.
FOR loop_counter IN [REVERSE] low_bound..high_bound LOOP
sequence_of_statement
END LOOP;

29)What is pl/sql records?


Records are composite data type and are user defined. In oreder to use composite data type first you must
define that type and then decalre variable of that type.
Any field without initial value is initialized to null.
Declare
type t_studentrecord is record(
first_name varchar2(10),
last_name varchar2(10),
currentcredits number(3));
type t_studentrecord1 is record(
first_name varchar2(10),
last_name varchar2(10),
currentcredits number(3));

v_student t_studentrecord;
v_student1 t_studentrecord;
v_student2 t_studentrecord1;
referencing a Record:
v_student.first_name := 'asd';
Record assignment:
If both record of same type then
v_student := v_student1;
because records of diferent type
v_student1 := v_student2 -- illegal
but
v_student.first_name := v_student2.first_name -- legal as fields are same type.
assigning record to slect statement.
select first_name,last_name, currentcredits into v_student from students;

30)what is %type and %rowtype?


%type attribute is appended to a table colum reference or another variable and return its type.
%rowtype will return a type based on table defenition.
If it is applied to a column of NOT NULL Constraint then the return type does not have this Not NULL
restriction.however length of varchar and number precision are included.

31)What is subtypes?
A subtype is used to give an alternatve name for a type(pl/sql also define subtype eg. decimal and integer
are subtype of number).
declare
subtype t_loopcounter is number
subtype t_loopcounter is number(4) --- illegal
v_dummyvar number(4)
subtype t_loopcounter is v_dummyvar%type

32)what are all the restrictions in the GOTO?


It is illegal to branch into an inner block ,loop,if statement.

33)Null as an statement?
Null statement does not do anything it just serve as a placeholder.

34)what are sql statement?


data manipulation statement:select,insert,update,delete,explain plan.
data defenition languag:drop,create,alter,grant,revoke
transaction control language:commit,rollback,save point set transacton.
session control:alter session,set role
system control: alter system

Only sql statements allowed in pl/sql are dml and transaction control languages.This is because other sql
statements will alter the schema objects.

35)What is Binding?
It is the process of identifying the strorage location associated with an identifier in the program.In pl/sql it
also checks the permission to access the object reference.
36)What is dynamic sql?
A technique that allows all valid sql statements including DDL to be issued in pl/sql.there are two
technique in dynamic sql
a)Native dynamic SQL.
b)DBMS_SQL Package.
Until the block is completed the pl/sql will not create table so inserting values in that will cause error so
'EXECUTE IMMEDIATE' statement is used to avoid this error.

begin
execute immediate 'create table temp_table(num_value number, cahr_value char(10))';
execute immediate 'Insert into temp_table (num_values, cahr_vlue) values (10,"hellow")';
end;

37)What is returning clause?


It is often desirable to know information about rows modified by a DML statement.
This can be done in two ways
a)by using select statement(but this will make another call to rdbms kernal) so inefficient
b)by using returning clause which is valid at the end of any DML statements and used to get informatin
about the row or rows just processed.
Syntax:
returning expression INTO variable;

38)What is a pseudo column. Give some examples?


They are treated like columns in a table however they dont actually exist in the same way that table
columns do rather they are evaluated as a part of sql statements.
Example:rowid,rowno,currval,nextval.

39)What is ROWID?
The ROWID is a psedo column used in select list of a query.
It returns the row identifier of that particular row.
The ROWID psedocolumn returns a value of type ROWID

40)What is ROWNUM?
It return current row number in the query.
It is useful for limiting the total number of rows and it i used in the where caluse of query and set clause of
update statement.
Rownum return a number value.
EXAMPLE:
Select * from students where ROWNUM < 3;

41)What is mean by level?


It is used only in a SELECT statemet that implments the hierarchical tree walk over a table using START
WITH and CONNECT BY Clause.
The LEVEL psedocolum will return the current level of tree as number.

42)What is privilages and what are the type of privilages?


It is permission to perform the operation on the objects. there are two types of privilages
a)Object
An object privilage allows operations on an particular object(Table)
ALTER,DELETE,EXECUTE,INDEX,INSERT,ON COMMIT REFRESH,QUERY
REWRITE,READ,REFERENCE,SELECT,UNDER,UPDATE.
b)System
A System privilages allow operation on entire class of objects.
GRANT and REVOKE:
Both statements can be used for object and system privilages.
GRANT:
GRNAT FOR OBJECT PRIVILAGES:
GRANT privilage ON object TO grantee [WITH GRANT OPTION]
e.g
GRANT SELECT ON classed TO userA;
If WITH GRANT OPTION is specified then userA can in turn grant the privilage to another user
GRANT FOR SYSTEM PRIVILAGE:
GRANT privilage TO grantee [WITH ADMIN OPTION]
e.g
GRANT CREATE TABLE , ALTER ANY PROCEDURE TO userA;
REVOKE:
REVOKE FOR OBJECT PRIVILAGE:
REVOKE privilage ON object FROM grantee [CASCADE CONSTRAINTS][FORCE]
If the CASCASE CONSTRAINTS clause is inclued and the REFERENCES privilage is being revoked,all
referencial integrity constraints created by grantee with this privilage is dropped as well.
the FORCE keyword is used when revoking the EXECUTE PRIVILAGE on an objct type with table
dependencies.
REVOKE ON SYSTEM PRIVILAGE:
REVOKE privilage FORM grantee
REVOKE ALTER TABLE, EXECUTE ANY PROCEDURE FROM userA;

42)a)ROLE(can u expalin me about role)


A role is essentially a collection of privilages both object and system.
Consider the following.
GRANT ROLE table_query;
GRANT SELECT ON students TO table_query
GRANT SELECT ON classes TO table_query
GRANT SELECT ON rooms TO table_query
Now
GRANT table_query TO userA;
GRANT table_query TO userB;
both userA and userB have privilages to this 3 table so instead of givin six GRANT this will do.

The role PUBLIC is predefined in oracle


GRANT privilage TO PUBLIC.

PREDEFINED SYSTEM ROLE:


Role Name - CONNECT
Privilage Granted- ALTER SESSION,CREATE CLUSTER,CREATE DATABASE LINK,CREATE
SEQUENCE,CREATE SESSION,CREATE SYNONYM,CREATE TABLE,CREATE VIEW.
Role Name- RESOURCE
Privilage GRanted-CREATE CLUSTER,CREATE INDEXTYPE,CEATE OPERATOR,RETE
PROCEDURE,CEATE SEQUENCE,CREATE TABLE,CREATE TRIGGER,CREATE TYPE.
Role Name-DBA
Privilage granted-All system privilages(with the ADMIN OPTION,so they can be granted again), Plus
EXP_FULL_DATABASE and IMP_FULL_DATABASE
Role NAME-EXP_FULL_DATABASE
Privilages GRanted-ADMINISTER RESOURCE,BACKUP ANY TABLE,EXECUTE ANY
PROCEDURE,EXECUTE ANY TYPE,SELECT ANY TABLE, plus INSERT,UPDATE,DELETE on the
system table sys.incexp,sys.incvid and sys.incfil.

43)What is transaction?
A transation is a series of sql statements that either succeeds or fils as units.
Used to prevent inconsistent of data.
A transaction begins with first sql statement.
Transaction ends with COMMIT or ROLLBACK.
When COMMIT ISSUED
a)All work done by the transaction is amde perment.
b)Other session can see the changes made by this transaction.
c)Any locks acquired by the transaction are released.
COMMIT [WORK]
WORK - optional available for increased readability.
When ROLLBACK issued
a)All work done by the transaction is undone
b)Any lock acquired by transaction are relesed.
c)Issued when error occurs
ROLLBACK [WORK]
SAVEPOINT:
With SAVEPOINT only part of transaction need be undone.
SAVEPOINT name
name - name of the SAVEPOINT.
Once SVEPOINT is defined it can be used in ROLLBACK as
ROLLBACK [WORK] TO SVEPOINT name
When issed
a)Any work done since the savepoint is undone, the sacepoint remains active.However it can be rollback
again
b)any lock nd resource acquired by the SQL statement since the save point is undone.
c)The transaction isnot finished because SQL statement are still pending.

44)What are types of functions?


There are two types of functions.
a)single row functions
b)group functions
Group Function:
A group function operates on many rows of data and returns a single row result.
They are valid in select list and having clause of a single query.
e.g:count()
Single row function:
Operates on one value and returns another value

45)Name few functions?


a)Character functions returns character value
CHR(x,[using nchar_cs]) - returns the character that has the value equivalent to x in the database character
set.
CONCAT(strinf1,string2) - Returns string1 concatenated with string2 equvalent to || operator.retrun type
VARCAHR2.
INITCAP(string) - Return sting with thw first character of each word capitalized and remaining words of
each character in lower case.
LOWER(string) - Returns all characters in lowercase
LPAD(string1,X[,string2) - Returns string1 padded on the left to length x with the chracters in string2.
LTRIM(string1,string2) - Return string1 with the leftmost characters appearing in string2 remove.string2
defaults to a single blank. The databas will scan string1, starting fromn teh leftmost position. when first
character not in sring2 the result is returned.
REPLACE(strring,search_str[,replace_Str]) - Return string with eery occurnce of search_str replaced by
replace_str
RPAD(string1,x,[string2]) - Retruns string1 padded on the right to length x with the characters in string2.
RTRIM(strin1[,string2]) - Returns string1 with the rightmost character appearing in string2 removed.
SOUNDEX(string) - returns the phonetic representation of string.This is useful for comparing wors that are
spelled differently but sound alike.
SUBSTR(string1,a[,b]) - Returns a portion of string starting at character a,b character long. if a is 0 then it
is treated as "1".
TRANSLATE(strin,from_str,to_str) - Returns string with all occurence of each character in from_str
replaced by the correspnding character in to_str. TRANSLATE is a super set of the functionality provided
by REPLACE.
TRIM([{LEADING | TRALING | BOTH |} [TRIM]) | trim_char) FROM] string) - Returns string with
leading,triling, or both occurence of trim_char removed trim_char must be a single character and default to
a blank. if none of LEADING,TRAILING, or BOTH is specified, occurence of trim_char are removed
from both ends of string.

b)Character function returning Numeric Value


ASCII(string) - Returns the decimal representation of the first byte of string in the datbase character set.
INSTR(string1, string2)[,a][,b]) - returns the position within string1 where string2 is contained
LENGTH(string) - returns length of the string.

Numeric Functions:
ABS(x) - reurns the absolute value of x;
BITAND(x,y) - returns bitwise AND of x and y,each of which must be non-negative inteer value. There is
no BITOR functions.
CEIL(X) - retruns smallest integer greater than or equal to x.
EXP(X) - Returns e raised to the xth power. e=2.71828183.
Floor(x) - returns the largest integer equal to or less than x.
MOD(x,y) - Returns the remainder of x divided by y, if y is 0,x is returned.
POWER(x,y) - Return x raised to yth Power.
ROUND(x,[,y]) - Returns x rounded to y placs to the rigth of the deciaml point. y defaults to 0. which
roundes to the nearest integer.
SIGN(x) - if x < 0 ,returns -1,if x=0 returns 0. if x>0 returns 1.
TRUNC(x,[,y]) - Return x truncatd to y dcimal places.
WIDTH_BUCKET(x,min,max,num_buckets) - allows to crate equal-length histograms based on the input
parameters. The range MIN and MAX is divided into num_buckets sections

Date and Datetime Functions:


ADD_MONTHS(d,x) - Returns the date d plus x months.
CURRENT_DATE - Returns current date in the sesion time zone as a DATE value. This function is similar
to SYSDATE except that SYSDATE is not sensitive to the current session time zone.
CURRENT_TIMESTAMP - Returns the current date in the session time zone, as a TIMESTAMP WITH
TIMEZONE value.
DBTIMEZONE - returns the timezone of the database The format is the same aas used in CREATE
DATABASE statement
EXRACT({YEAR,MONTH,DAY,HOUR,MINUTE,SECONDS,TIMEZONE_HOUR,TIMEZONE_MINU
TE,TIMEZONE_REGION,TIMEZONE_ABBR} FORM datetime_or_interval) - returns the selected data
from datetime_or_interval, which must be either a DATE,DATETIME or INTERVAL expression.
LAST_DAY(d) - returns the date of the last day of the month that contains d.Used to determine how many
days are left in the current month.
LOCALTIMESTAMP[(precision)] - Returns the curret date in the session time zone as a TIMESTAMP
value.
MONTHS_BETWEEN(date1,date2) - Returns number of months between two dates.
NEXT_DAY(d,string) - Returns the date of the first day name by string that is later than the date d.
ROUND(d,[,format]) - Rounds the date d to the unit specified by format.
TRUNC(d[,format]) - Return the date d truncateed to the unit specified by format.

Conversion function:
TO_CHAR - Converts its argument to a character type.
TO_DATE - Converts its argument to a date datatype.
TO_NUMBER - Converts its argument to a number type.

Aggregate and Analytic Functions


AVG([DISTINCT | ALL] col) - returns the average of the column value.
count(* | DISTINCT | ALL ] col)
- Returns no of rows in the query,IF * then all rows are counted of select list item then non-NULL values
are counted.
MAX,MIN,RANK,SUM are other important functions.

Other functions:
BFILENAME - Return the BFILE locator associated with the phyisacal file.
COALESCE - Return non - NULL expr in the argument list.
DECODE(base_expr,compare1, value1,compare2, value2 ... default) - Simiklar to nested IF-THEN-ELSE
EXTRACT(XML type_instance,Xpath_string) - Returns the portion of XML documnet identified by XML
type_instance after applying Xpath_strig
GREAST(expr1[,expr2]...) - Returns the greatest expression of its argument.Each expression is implicitly
converted to the type of expression1 before before the comparision are made.
LEAST(expr1[,expr2]...) - Returns the least value in the list of expression. LEAST behaves similarly to
GREATEST.
NULLIF(a,b) - Returns NULL if a is equal to b and a if they are not equal.
NVL(expr1,expr2) - If expre1 is NULL returns epr2; otherwise return expr1.
NVL2(expr1,expr2,expr3) - If expres1 is NULL the expre2 is returned;otherwise expr3 is returned
UID - Returns an integer that uniquely identifies the current database user.
USER - Retruns a varchar2 value containing the name of current oracle user.

What is collection?
Collections are composite types.
A collection combines variable of same type.
Three types of collections index by table nested table and varray.

What is pl/sql tables?


collectively Index by table and nested tables are called pl/sql tables.

What is Index-by table?


They are similar to arrays in java.
Index-by tables can not be stored in data base.
Index- by tables are unconstrained.
The elements in an index-by table are not necessarily in any particular order Because they are not stored
contiguously.
The keys used for an index-by table don’t have to be sequential. They may be positive or negative.
The only type allowed for the key is Binary-Integer.
When an index-by table is created but does not have any elements then it is simply empty. Cannot be
automatically NULL.
Have No explicit maximum size.
Can be declared inseide PL/SQL block Only.
Elements are assigned directly without initialization.
Can map to host variable.

In order to declare an index-by-table you first declare the table type and then declare a variable to that type.
TYPE tabletype IS TABLE OF type INDEX BY BINARY_INTEGER;
Once the type and variable is declared we can refer by following syntax.
Tablename(index);
Note:INDEX BY BINARY_INTEGER clause is required for index by table which is not presented for
nested table.

Index-By Table of Non-scalar Types


The only non-scalar type supported by index-by tables was a record.

Index-By Tables of Object Types


Oracle8 allows index-by tables of object types.
What is Nested Tables?
A nested table can be thought of as a database table with two columns-key and value.
Elements can be deleted from the middle of a nested table.
Nested tables must be created with sequential keys it can be sparse with non sequential key value.
keys cannot be negative.
Nested tables can be stored in Database
Have no explicit maximum size.
Cannot map to host variable
Table must be initialized and extended before it can be assigned.
TYPE table_name is TABLE OF table_type [NOT NULL]

What is constructor in nested table?


When a nested table is declared but does not contain any elements it will be automatically initialized to
NULL This is done by sing Contructor.
A constructor for a nested table has the same name as the table type itself.
Declare
TYPE wordstab IS TABLE OF VARCHAR2(50);
--create a null table.
V_tab1 wordstab;
Table with one element and which itself is null (CONSTRUCTOR)
V_tab2 wordstab := wordstab();

What is VARRAY?
A variable length array is a data type that had fixed upper bound on its size specified as a part of
declaration.
The elements are stored contiguously in memory this is different from the storage for a nested table.
The key must be positive.
Are constrained to maximum size in the type definition.
Always have space allocated for each elements and have sequential key value.
Can be automatically NULL.
VARRAY must be initialized before elements can be assigned.
It can be stored in database table.
When stored in database VARRAY can retain ordering and subscript value for the elements whereas nested
tables do not.

Declaring VARRAY:
TYPE typename IS {VARRAY| VARYING ARRAY} (maximum_size) OF element_type [NOT NULL];
VARRAY INTIALIZAION:
They are initialized using constructor.

What is multilevel collection?


It is collection of Collection.
Type t_number is table of number index by binary_integer.
Typet_multinumber is table of t_number index by binary_integer.
Begin v_multinumbers(1)(1) := 12345;

What is stored collections or schema level types?


To store and retrieve the collection from the database the collection types must be know to both pl/sql and
sql and should be declared using a CREATE TYPE statement.
It can be used as a datacolumn.
CREATE OR REPLACE TYPE namelist AS VARRAY(20) OF VARCHAR2(20).

What is nested table clause?


For each nested table in a given database table the nested table clause is required.
CREATE OR REPLACE TYPE studentlist AS TABLE OF NUMBER(5);
CREATE TABLE library_catalog(a number,check_out studentlist)
NESTED TABLE checked_out STORE as co_tab;

Manipulating Entire Collections


You can manipulate a stored collection in its entirely using SQL DML statements.

Insert
The INSERT statement is used to insert a collection into a database row.Insert into class-material
values ('MUS',100,Booklist(3001,3002));

UPDATE
Update is used to modify a stored collection.
UPDATE library-catalog
SET checked-out=StudentList(10009)
WHERE catalog-number = 3002;

DELETE
Delete can remove a row containing a collection.

SELECT
SELECT required-reading
INTO v-Books
FROM class-material
WHERE department = p-Department
AND course = p-course;

What are Collection Methods and what are all different type of collection methods?
Nested tables and varrays are object types, and as such they have methods defined on them. Likewise,
index-by tables have attributes.
Syntax:
collection-instance.method-or-attribute

Valid for Index-by tables, nested tables, varrays:


EXISTS:
Return Type is Boolean
Returns TRUE if the specified element exists in the collection
Count:
Return Type is Number
Returns the number of elements in a collection
FIRST&LAST:
Return Type is Binary-Integer
Returns the index of the first (or last) element in a collection
NEXT&PRIOR:
Return Type is Binary-Integer
Returns the index of the next (or prior) element, relative to a given element, in a collection

Valid for Nested tables, Varrays:


LIMIT:
Return Type is Number
Returns the maximum number of elements for a collection
Always returns NULL for Nested table
EXTEND:
Return type is N/A
Adds elements to a collection Upto the maximum size for the type
TRIM:
Return type is N/A
Removes elements from the end of a collection

Valid for Index-by tables, nested tables:


DELETE
Return type is N/A
Removes specified elements from a collection

What is Procedures and functions?


Collectively, procedures and functions are also known as subprograms. When a procedure is created, it is
first compiled, and then stored in the database in compiled form. This compiled code can then be run later
from another PL/SQL block
When the procedure is called parameters can be passed.
A procedure call is a PL/SQL statement by itself. It is not called as part of an expression.
A procedure is a PL/SQL block, with a declarative section, an executable section, and an exception-
handling section.

How to create procedure and functions?


Procedures are created with CREATE PROCEDURE, and functions are created with CREATE
FUNCTION.

CREATE[OR REPLACE] PROCEDURE procedure-name


[(argument[{IN/OUT/INOUT}] type,
...
argument [{IN/OUT/IN OUT}] {IS/AS}
procedure-body

CREATE[OR REPLACE] FUNCTION function-name


[(argument [{IN/OUT/IN OUT}]type,
...
argument [{IN/OUT/IN OUT}] type)]
RETURN return-type {IS/AS}
function-body

A function is very similar to a procedure. Both take parameters, which can be of any mode. A procedure
call is a PL/SQL statement by itself,
while a function call is called as part of an expression.

What is The RETURN Statement?


Inside the body of the function, the RETURN statement is used to return control TO THE CALLING
environment with a value. The general syntax of the RETURN statement is
RETURN expression;

How to Drop Procedures and Functions?


Similar to dropping a table, procedures and functions can also be dropped.
DROP PROCEDURE procedure-name;
DROP FUNCTION function-name;

Subprogram Parameters
The formal parameters are the placeholders for the values of the actual parameters.
Mode
IN
The value of the actual parameter is passed into the procedure when the procedure is invoked. Inside the
procedure, the formal parameter acts like a PL/SQL constant-it is considered read-only and cannot be
changed. When the procedure finishes and control returns to the calling environment, the actual parameter
is not changed.
OUT
Any value the actual parameter has when the parameter is called is ignored. Inside the procedure, the
formal parameter acts like an uninitialized PL/SQL variable, and thus has a value of NULL. It can be
read from and written to. When the procedure finishes and control returns to the calling environment, the
contents of the formal parameter are assigned to the actual parameter.(In Oracle8i, this behaviour can be
altered by using the NOCOPY modifier-see the section "Passing Parameters by Value and by Reference"
later in this chapter.)
INOUT
This mode is a combination of IN and OUT. The value of the actual parameter is passed into the procedure
when the procedure is invoked. Inside the procedure, the formal parameter acts like an initialized variable,
and can be read from and written to. When the procedure finishes and control returns to the calling
environment, the contents of the formal parameter are assigned to the actual parameter(subject to NOCOPY
in Oracle8i, as for OUT).

What is mean by Passing Parameters by Reference and by value?


A subprogram parameter an be passed in one of two ways-by reference or by value. When a parameter is
passed by reference,a pointer to the actual parameter is passed to the corresponding formal parameter.
When a parameter is passed by value, on the other hand, it is copied from the actual parameter into the
formal parameter. Passing by reference is generally faster, because it avoids the copy. PL/SQL will pass IN
parameters by reference, and IN OUT and OUT parameters by value.

What is NOCOPY?
Is an compiler hint.
If NOCOPY is present the compiler will try to pass the parameter by reference rather than by value.
Using NOCOPY in the in parameter will generate compilation error because IN parameter is always passed
by reference.
paramater_name [mode] NOCOPY datatype.
CREATE OR REPLACE PROCEDURE nocopytest(
p_inparameter IN NUMBER,
p_outparameter OUT NOCOPY VARCHAR2,
p_inoutparameter IN OUT NOCOPY CHAR) IS

What are the restriction of NOCOPY RESTRICTION?


The actual parameter is a member of an index-by table. If the actual parameter is an entire table however,
this restriction does not apply.
The actual parameter is constrained by a precision , scale, or NOT NULL constraint. This restriction does
not apply to a character parameter constraint by a maximum length n through the reason for this is that
the pl/sql compiler checks for constraint violation only when returning from a subprogram, when copying
the value back from the formal parameter to the actual parameter, If there is a constraint violation
the original value of the actual parameter needs to be unchanged which is impossible with NOCOPY.
The actual and formal parameters are both records and they were declared either implicitly as a loop control
variable or using $ROWTYPE and the constraint on the corresponding fields differ.
Passing the actual parameter requires an implicitly data type conversion.
The subprogram is involved in a remote procedure(RPC) call. An RPC is a procedure call made over a
database link to a remote server. Because the parameter must be transfer over a network, it is not possible to
pass them by reference.

What is POSTITIOANL AND NAMED NOTATION?


The actual parameters are assciated with the formal parameters by position. This is called positional
parameter.
In named notation the formal parameter and actual parameter are both included for each argument This
allows us to rearrange the order of the argument if desired.
Positional notation is followed by named notation but a named notation is not followed by positional
notation.

What is CALL Statement?


Is an sql statement used to call a stored procedure.
It is not valid inside the pl/sql but is valid in dynamic sql
the parenthesis is always required even if the subprogram takes no argument.
The into clause is used for the output variable of functions only.
CALL subprogram_name ([arguments_list)] [INTO host_variable];

What are the similarities between proc and func?


Both can return more than one values.
Both have declaration, executable and exception handling section.
both can accept default value.
Both can be called using positional and named notation.
Both can accept NOCOPY parameter.

What is the difference between PROCEDURES AND FUNCTIONS?


Use procedure if there is more than one return value. Use function if there is only one return value, even
though the function can return more than one value by using out parameter.

What is PACKAGES?
A package is a PL/SQL construct that allowed related objects to be stored together. The packaaged have
two separate parts.
The package specification
The package Body.
Each of it is stored separately in data dictionary.

What is the difference between procedure and package?


The subprogram can be contained locally in a block or can be stored in the database but the package can
only be stored it cannot be local.
One advantage of putting into a package is the ability to reference them from other pl/sql blocks so a
package provides global variables for pl/sql.

What is Package Specification?


It is also known as package header contains information about the content of the package wowever it does
not contain any code for subprogram.
CREATE [OR REPLACE] PACKAGE package_name [IS|As]
type_def|
procedure_spec|
function_spec|
variable_dec|
cursor_dec|
Pragma_dec
END [package_name]
package elements can appear in any order however as in declarative section an object must be declared
before it is referenced
Any declaration of procedure and function must be forward declaration.
FORWARED DECLARATION:
A forward Declaration simply describes the subprogram and its argument but does not include ant code.

What is Package BODY?


It is a separate data dictionary object from the package header. The body contains the code for the forward
subprogram declarations in the package header.
It can contain declaration which is visible to body and not to specification.
the package body contains the code for the forward declaration in the package header
classpackage.removestudent(10006,'HIS',101);
The package body is optional if the specification does not contain any procedure or functions.

What is OVERLOADING PACKAGED SUBPROGRAM?


More than one procedure or function with the same name but with different parameter.
You cannot overload two subprogram if their parameter differs only in name or mode
You cannot overload two functions based only on their return type.
parameter of overloaded functions must differ by type.

What is Package Initialization?


Initializing code need to be run the first time the package is instantiated within a session. This can be done
by using code with
Begin and end in package body.

Where the subprograms are stored?


Subprogram Locations
Subprograms and packages can be stored in the data dictionary.
The subprogram is created first with the CREATE OR REPLACE command, and then it is called from
another PL/SQL block. A subprogram can be defined within the declarative section of a block. In this case,
it is known as a local subprogram.
A stored subprogram that is invalid is still stored in the database. However, it cannot be called successful
until the error is fixed.

What is native compilation?


You can choose to have PL/SQL compiled to native code. This will create shared library, which is then run
by the Oracle shadow process. In order to use this feature, you must have a C compiler installed on your
system, as the PL/SQL compiler will generate C code that is then compiled into the native library.

What is Forward Declarations?


Since the names of local PL/SQL subprograms are identifiers, they must be declared before they are
referenced. This is normally not a problem. However, in the case of mutually referential subprograms.

What is diffentence between Stored Subprograms and Local subprogram?


Stored subprogram
The stored subprogram is stored in compiled p-code in the database; when the procedure is called, it does
not have to be compiled.
Stored subprograms can be called from any block submitted by a user who has EXECUTE privileges on the
subprogram.
By keeping the subprogram code separate from the calling block, the calling block is shorter and easier to
understand. The subprogram and calling block can also be maintained separately, if desired.
The compiled p-code can be pinned in the shared pool using the DBMS-SHARED_POOL.KEEP packaged
procedure. This can improve performance.
Stand-alone stored subprograms cannot be overloaded, but packaged subprograms can be overloaded
within the same package.
Local Subprograms
The local subprogram is compiled as part of its containingblock.
If the containing block is anonymous and is run multiple times,the subprogram has to be compiled each
time.
Local subprograms can be called only from the block containing the subprograms.
The subprogram and the calling block are one and the same, which can lead to confusion. If a change to the
calling block is made, the subprogram will be recompiled as part of the recompilation of the containing
block.
Local subprograms cannot be pinned in the shared pool by themselves.
Local subprograms can be overloaded within the same block.

What is Subprogram dependencies?


When a stored procedure or functin is compiled all of the oracle objects that is referenced are recorded in
the data dictionary.the procedure is depended on these objects. A subprogram is marked as invalid if it has
compiled errors or any DDL operations performed in it.

What is Automatic Recompilation?


If a dependent object is invalidated, the PL/SQL engine will automatically attempt to recompile it the next
time it is called.

What is package dependencies?


The situation is different for packages. If the package body get invalidated if any dependent object is
modified and the package header is not invalidated so package body can be changed and recompiled
without recompiling the package header.
If there is any changes in the package header then the package body is invalidated.

What is Timestamp Model?(for recompilation)


The timestamp of last modification of the two objects are compared. The last_ddl_time field of
user_objects contains this timestamp. If the base object had a newew timestamp than the dependent
object the dependent object will be recompiled. There are several issues with that model. The date
comparision does not take the location of the two engines into account. If they are in different time zones,
the comparision will not be valid. Slightly more serious is when P1 is contained in a client-side pl/sql
engine such as oracle forms in this case it may not be possible to recompile P1 because the source for it
may not be included with the runtime version of forms.

What is signature Model?(For recompilation)


PL/SQL provides different method for determining when remote dependent object need to be recompiled
that resolves the issue with the timestamp model. This method is called signature model. When a procedure
is created a signature is stored in the data dictionary in addition to the p-code. The signature encodes the
types and order of the parameter. With this model the signature of p2 will change only when the parameters
changes. When p1 is compiled for the first time the signature of p2 is included in the thus only p1 needs to
recompile when the signature of p2 changes.
There are 3 ways to set this mode.
Add the line remote_dependencies_mode=signature to the database initialization file.
Issue command Alter System set remote_dependencies_mode=signature;
ALTER SESSION SET REMOTE_DEPENDENCIES_MODE = SINATURE;

How to recompile procedure manualy?


ALTER PROCEDURE procedure_name COMPILE;
ALTER FUNCTION function_name COMPILE;
To recompile package use any of the follwing.
ALTER PACKAGE package_name COMPILE;(both specification and body will be compiled)
ALTER PACKAGE package_name COMPILE SPECIFICATION;
ALTER PACKAGE package_name COMPILE BODY;

What is Serially Reusable Packages?


The runtime state of a serially reusable package will last only for each database call, rather than for the
entire session. A serially reusable package has the syntax
PRAGMA SERIALLY-REUSABLE;

CREATE OR REPLACE PACKAGE persistpkg2.AS


PRAGMA SERIALLY-REUSABLE;

CREATE OR REPLACE PACKAGE BODY persistpkg AS


PRAGMA SERIALLY_REUSABLE;

Difference between serially reusable package and non serially reusable package?
Serially Reusable Packages
Runtime state is kept in shared memory, and is freed after every database call.
The maximum memory used is proportional to the number of concurrent users of the package.
Non serially Reusable Packages
Runtime state is kept in process memory, and lasts for the life of the database session.
The maximum memory used is proportional to the number of concurrently logged-on users, which is
typically much higher.

What privilege is required to access subprogram?


EXECUTE privilege is required to access a subprogram.
userA owns the procedure recordfullclasses
CREATE OR REPLACE PROCEDURE REcordfullclasses as
CURSOR c_classes IS SELECT department, courses from classes
Begin
For v_classrecord IN c_classes LOOP
IF almostfull(v_classesrecord.department, v_classrecord.course) then
INSERT INTO temp_table (char_col) values (v_classrecord.department||v_classrecord.course)
end if;
end loop;
end recordfullclasses;
The privilage is granted to userB as
GRANT EXECUTE ON procedure_name to userB.
userB can access as follows
begin
userA.recordfullclasses;
end;

IF userB also have temp_table which table is inserted In userA or userB?


table in userA is inserted. This is because a subprogram executes under the privilage set of its owner.

userA creating procedure based on table userB.temp_table have to grant access to userB on procedure OR
stored subprograms?
userA must have granted SELECT privilages on temp_table.
This grant must be done explicitly and not through a role. This is also applied to triggers and packages that
are stored in database as well. Else an error will be through.
This is because PL/SQL uses early binding that is referencing objects at compile time not runtime.
GRNAT and REVOKE are both DDL statements they take effect immediately and new privileges are
recorded in data dictionary. All database sessions will see the new privilege set. However this is not
necessarily true for roles. A role can be granted to a user and that user can then chose to disable the role
with the SET ROLE command. The distinction is that SET ROLE applies to one database session only
while GRANT and REVOKE will apply to all sessions. A role can be disabled in one session but enable in
other session.
In order to allow privileges granted via a role to be used inside stored subprogram and triggers, the
privilages wolud have to be checked every time the procedure is run. The privileges are checked as part of
the binding process. But early binding means that the privileges are checked at compile time not run time in
order to maintain early binding all roles are disables inside stored procedure, functions, packages and
triggers.
Invoker's Vs Definers Rights
if userA and userB have own copy of temp_table and EXECUTE privileges are given to userB on
procedureA created by user then userA's temp_table is affected this is called Definer's rights.
Because unqualified external reference within it are resolved under the privilage set by owner or
definer.
In an invokers rights subprogram, external reference are resolved under the privilege set of the caller not
the owner.
An invokers rights routine is created by using AUTHID clause. It is valid for stand alone subprogram
package specification and object type specification.
Individual subprogram within a package must be all invokers or definers not a mix.
AUTHID [CURRENT_USER|DEFINER]
A database trigger will always be executed with the definers right and will execute under the privilege set
of the schema that owns the triggering table. This is true for pl/SQL functions that is called from view.
How stored functions used in SQL? Or what is purity level
Depending on where a use-defined function is used and what version of oracle you are running it must meet
different restrictions. These restrictions are defined in terms of purity level.
There are four different purity levels

what is the functions of Purity Levels?


A purity level defines what kinds of data structures the function reads or modifies.
Depending on the purity level of a function,it is subject to the following restrictions:
Any function called from a SQL statement cannot modify any database tables (WNDS). (In Oracle8i and
higher, a function called from a non-SELECT statement can modify database tables. See the section
"calling stored functions from SQL in Oracle8i" later in this chapter.)
In order to be executed remotely (via a database link) or in parallel, a function must not read or write the
value of packaged variables (RNPS and WNPS).
Functions called from the SELECT, VALUES, or SET clauses can write packaged variables.
Functions in all other clauses must have the WNPS purity level.
A function is only as pure as the subprograms it calls. If a function calls a stored procedure
that does an UPDATE, for example, the function does not have the WNDS purity level and thus
cannot be used inside a SELECT statement.
Regardless of their purity level stored pl/sql functions cannot be called form a CHECK
constraint caluse of CREATE TABLE or ALTER TABLE.

Explain the type of purity level?


WNDS
Writes no database state
The function does not modify any database tables (using DML statements).
RNDS
Reads no database state
The function does not read any database tables (using the SELECT statement).
WNPS
Writes no package state
The function does not modify any packaged variables (no packaged variables are used on the left side of an
assignment or in a FETCH statement).
RNPS
Reads no package state.
The function does not examine any packaged variable

what are the requirement must be meet by functions to use in SQL?


The following requirement must be meet by user defined functions to call from sql
The function has to be stored in database and should not be local.
The function must take IN parameter not INOUT or OUT.
The formal parameters and return type of the function must use database data types not pl/sql data types
like boolean.
The function must not end the current transaction with COMMIT or ROLLBACK, It must also not issue
ALTER SESSION or ALTER SYSTEM commands.

What is RESTRICTED REFERENCE?


PL/SQL engine can determine the purity level of the stand alone functions, when the function is called form
the sql. This pragma specifies the purity level of the function in a package at compile-time.
PRAGMA RESTRICTERD_REFERENCE(subprogram_or_package_anme,WNDS[,WNPS][,RNDS]
[,RNPS])
Because WNDS is required for all functions used in sql statement it is reqiured for PRAGMA.

Why is RESTRICTED_REFERENCE is used for Package functions and not for stan alone functions?
The PL/SQL Engine need PRAGMA to check the purity level of the packaged function, to verify that it is
being used correctly in the calling block. Whenever the package body is modified the function code is also
checked against the pragma. The pragma is checked at compile time and not run time.
For overloading functions the pragma is applies to the nearest definition prior to the declaration.
For oracle8i and above if the pragma is not specified the database will verify the purity level at run time.

What is the use of DEFAULT key word in RESTICTED_REFERENCE?


The DEFAULT keyword is used instead of subprogram name
PRAGMA RESTRICTED_REFERENCE(DEFAULT,WNDS[,WNPS][,RNDS][,RNPS])
any subsequent subprogram in the package must comply with the purity levels specified.

About the DEFAULT parameter in functions?


When calling a function from procedural statement, you can specify the default value of formal parameter,
but while calling from sql all parameters must be specified and named notation should not be used only
positional notation is used.

What is use of trust key word?


If the TRUST key word is present the restriction listed on the pragma are not enforced rather they are
trusted.

What is Pinning in the shared Pool?


The shared Pool is the part in SGA.
The first time a stored subprogram is called the p-code is loaded from disk to the shared pool. If the object
is no longer referenced then it is free to be aged out of shared pool by using LRU algorithm.
The DBMS_SHARED_POOL package allows you to pin object in the shared pool when it is pinned it will
never get aged out until you request it no mater hw full he pool is. Pinning he object helps minimize
fragmentation of the shared pool.
DBMS_SHARED_POOL has 4 procedures
DBMS_SHARED_POOL.KEEP
This procedure is used to pin objects in the shared pool. Packages, triggers, sequence, object type and java
objects and sql statement can be pinned.
PROCEUDURE KEEP(name VARCHAR2, flag CHAR DEFAULT 'P');
'P' - Package, procedure, or function
'Q' - Sequence
'R' - Trigger
'T' - Object type
'JS' - java source
'C' - Cursor
DBMS_SHARED_POOL.UNKEEP
UNKEEP is the only way to remove a kept object fronm the shared pool without restarting the database.
PROCEUDURE KEEP(name VARCHAR2, flag CHAR DEFAULT 'P');
DBMS_SHARED_POOL.SIZES
It will echo the content of the shared pool to the screen.
PROCEUDRE SIZE(minsize NUMBER);
DBMS_SHARED_POOL.ABORTED_REQUEST_THRESHOLD
If there is not enough memory in the shared pool to satisfied a given request it will begin aging objects until
there is memory.
Procedure ABORTED_REQUEST_THRESHOLD(threshold_size NUMBER);

What is Triggers?
Triggers are similar to procedures and functions.
Like packages triggers are stored in database. It cannot be local to package or block.
A trigger is executed implicitly whenever the triggering event happens and it wont accept any arguments.
The act of executing the trigger is called firing the trigger.

What is the use of trigger?


Maintains complex integrity constraint not possible through declarative constraints enabled at table
creation.
Auditing information in a table by recording the changes made and who made them.
Automatically signaling other programs that an action needs to take place when changes are made to a
table.
Publishing information about various events in a publish-subscribe environment.

Tell about different kinds of triggers?


There are 3 kinds of triggers
DML trigger, instead of trigger and system trigger
General syntax of trigger
CREATE OR REPLACE TRIGGER trigger_name
[BEFORE|AFTER|INSTEAD OF] triggerin event
referencing_clause
WHEN [trigger_condition]
[FOR EACH ROW]
trigger_body.
Referencing clause is used to refer to the data in the row currently being modified by a different name.
NOTE: triggering body should not exceed 32K if exceeds then call it from package or procedure.

What is DML trigger?


A DML trigger is fired by DML statement. DML trigger are defined for INSERT, UPDATE, or DELETE
operations.
They can be fired BEFORE or AFTER the statement executes and can be fired once per affected row or
once per statement.
There are 12 possible types(3 statements(INSERT, UPDATE, OR DELETE) * 2 timing(BEFORE, AFTER)
* 2 level(Row or Statement level))

What is order of DML trigger firing?


1. Execute before statement-level trigger.
2. for each affected by the statement
A. Execute before roe-level trigger if present
B. Execute the statement itself.
C. Execute the after row-level trigger if present.
3. Execute the after statement-level trigger if present.

What are the correlation identifier in row-level trigger?


Inside the trigger you can access the data in the row that is currently being processed. This is accomblish
through two correlation identifiers. It is special kind of pl/sql variable.
:old
:new
The pl/sql will treat then as record of type
Triggering_table%rowtype
Triggering table is the table for which trigger is defined. Thus reference such as
:new.field is valid if field id the field in triggering table.
Triggering statement: INSERT
:old – undefined – all fields are null.
:new – values that will be inserted when the statement is completed.
Triggering statement: UPDATE
:old – Original value of row before update
:new – new value that will be updated when the statement is completed.
Triggering statement: DELETE
:old – original value before the row is deleted.
:new – undefined – all fields are NULL.

:new is modified only in before row-level trigger and :old is never modified.
:old and :new have no meaning in the statement level trigger.
:old and :new cannot be passed to procedure or function that take arguments of triggering_table%rowtype.
What is referencing clause?
It is used to specify different name for :new and :old. This is present after the triggering event, before the
WHEN clause, syntax
REFERENCING [OLD AS old_name][NEW as new_name]
Old and new are without COLON inside the referencing clause.

What is WHEN clause in trigger?


It is valid for row-level trigger only, If present the trigger body will be executed only for those rows that
meet the condition specified by WHEN clause.
WHEN trigger_condition
:new and :old records can be referenced inside the trigger_conditin but like REFERENCING clause the
COLON is not used there.

What is Trigger predicates?


Predicates are Boolean functions used to determine what the operation is. There are 3 types of predicate
INSERTING – TRUE if triggering statement is an INSERT; FALSE otherwise.
UPDATING – TRUE if triggering statement is an UPDATE; FALSE otherwise
DELETING -- TRUE if triggering statement is an DELETE; FALSE otherwise

What is Instead of trigger?


Creating instead-of Triggers
Instead-of triggers fire instead of a DML operation.
Instead-of triggers can be defined only on views.
The instead of trigger must be row level .
Instead-of triggers are used in two cases:
(i) To allow a view that would otherwise not be modifiable to be modified.
(ii) To modify the columns of a nested table column in a view.

What is Modifiable versus Non modifiable Views


A modifiable view is one against which you can issue a DML statement. In general, a view is modifiable if
it does not contain any of the following:
(i) Set operators (UNION, UNIONALL, MINUS)
(ii) Aggregate functions (SUM, AVG, etc.)
(iii)GROUP BY, CONNECT BY, or START WITH clauses
(iv) The DISTINCT operator
(v) Joins

What is key preserved table?


A table is Key-preserved if, after a join with another table, the keys in the original table are also keys in the
resultant join. For more details on Key-preserved tables, see the Application Developer's Guide
Fundamentals.

When the DML operations are permitted?


INSERT
The statement does not refer, implicity or explicitly, to the columns of a nonkey-preserved table.
UPDATE
The updated columns map to columns of a key-preserved table.
DELETE
There is exactly one key-preserved table in the join.
The FOR EACH ROW clauses is optional for an instead-of trigger. All instead-of triggers are row level,
whether or not the clause is present.

What is system triggers?


A system triggers fires when a system event such as database start up or shut down occurs.
A system trigger can also fired on DDL operations such as table creation.
System triggers, on the other hand, fire on two different kinds of events :
DDL or database.
DDL events include CREATE, ALTER, or DROP statements, whereas database events include
startup/shutdown of the server, logon/logoff of a user, and a server error.

CREATE [OR REPLACE] TRIGGER [schema.] trigger-name


{BEFORE/ AFTER}
{ddl_event_list/ database_event_list}
ON {DATABASE/ [schema.] SCHEMA}
[when_clause]
trigger_body;

You must have the ADMINISTER DATABASE TRIGGER system privilege in order to create a system
trigger.
What are the system DDL and DATABASE Events?
STARTUP
--AFTER
--Fired when an instance is started up.
SHUTDOWN
--BEFORE
--Fired when an instance is shutdown. This event may not fire if the database is shutdown abnormally (as in
a shutdown abort).
SERVERERROR
--AFTER
--Fired whenever an error occurs.
LOGON
--AFTER
--Fired after a user has successfully connected to the database.
LOGOFF
--BEFORE
--Fired at the start of a user logoff.
CREATE
--BEFORE, AFTER
--Fired before or after a schema object is created.
DROP
--BEFORE, AFTER
--Fired before or after a schema object is dropped.
ALTER
--BEFORE, AFTER
--Fired before or after a schema object is altered.
STARTUP and SHUTDOWN triggers are relevant only at database level it is not illegal to create them at
the schema level but they will not fire.

Distinguish between Database versus Schema Triggers?


A database-level trigger will fire whenever the triggering event occurs, whereas a schema-level trigger will
fire only when the triggering event occurs for the specified schema. The DATABASE and SCHEMA
keywords determine the level for a given system trigger. If the schema is not specified with the SCHEMA
keyword, it defaults to the schema that owns the trigger.

What are event attribute function?


This functions allow a trigger body to get information about the triggering event.
These functions are legal to call from PL/SQL blocks.
They will not always return a valid result.
Attribute function:
SYSEVENT – varchar2(20) – for all events – Retrun the system event that fired the trigger.
INSTANCE_NUM – NUMBER – for all events – return the current instance number
DATABASE_NAME – varchar2(50) All events – returns the current database name.
SERVER_ERROR – NUMBER – SERVERERROR – returns the error at the position on the error stack.
IS_SERVERERROR – BOOLEAN – SERVERERROR – takes an error number and returns true if error
occurs.
LOGIN_USER – varchar2(30) – all events – returns the user id of the user that fired the trigger.
DICTIONARY_OBJ_TYPE – varcahr2(20) – CREATE/ALTER/DROP – Return the type of dictionary
object on which the DDL operation that fired the trigger occurred.
DICTIONARY_OBJ_NAME – varchar2(30) – CREATE/DROP/ALTER – Returns the name of the
dictionary object on which the DDL operation that fired the trigger occurred.
DICTIONARY_OBJ_OWNER – varcahr2(30) – CREATE/DROP/ALTER – returns the owner of the
dictionary object on which the DDL operation that fired the trigger occurred.

What is SERVERERROR event?


It is used to track errors that occurs in the database.
The error code is available inside the trigger through the SERVER_ERROR attribute.

Distinguish between System Triggers and Transaction


A system trigger will either fire as a separate transaction that is committed upon successful completion of
the trigger, or it will fire as part of the current user transaction. STARTUP,SERVERERROR, and LOGON
triggers all fire as separate transactions, while LOGOFF and DDL triggers fire as part of the current
transaction.
It is important to note, that the work done by the trigger will generally be committed regardless. In the case
of a DDL trigger, the current transaction (namely the CREATE, ALTER, or DROP statement) is
automatically committed, which commits the work in the trigger. The work in a LOGOFF trigger will also
be committed as part of the final transaction in the session.
Because system triggers are generally committed anyway, declaring them as autonomous will not have any
effect.

System Triggers and the WHEN clause


Just like DML triggers, system triggers can use the WHEN clause to specify a condition on the trigger
firing. However, there are restrictions on the types of conditions that can be specified for each type of
system trigger, namely
(1) STARTUP and SHUTDOWN triggers cannot have any conditions.
(2) SERVERERROR triggers can use the ERRNO test to check for a specific error only.
(3) LOGON and LOGOFF triggers can check the userid or username with the USERID or USERNAME
tests.
(4) DDL triggers can check the type and name of the object being modified, and can check the userid or
username.

What are the restriction of Trigger Names?


A trigger can have the same name as a table or procedure. Within one schema, however, a given name can
be used for only one trigger.

What are the Restrictions on Triggers:


(1) A trigger may not issue any transaction control statements- COMMIT, ROLLBACK, SAVEPOINT, or
SET TRANSACTION. The PL/SQL compiler will allow a trigger to be created that contains one of these
statements, but you will receive an error when the trigger is fired. This is because it is fired as part of the
execution of the triggering statement and is in the same transaction as the triggering statement. When the
triggering statement is committed or rolled back, the work in the trigger is committed or rolled back as
well. (In Oracle8i and higher, you can create a trigger that executes as an autonomous transaction, in which
case the work in the trigger can be committed or rolled back independent of the state of the triggering
statement. See chapter 4 for more information about autonomous transactions.)
(2) Likewise, any procedures or functions that are called by the trigger body cannot issue any transaction
control statements (unless they are also declared as autonomous in Oracle8i and higher).
(3) The trigger body cannot declare any LONG or LONG RAW variables. Also, new and : old cannot refer
to a LONG or LONG RAW column in the table for which the trigger is defined.
(4) In Oracle8 and higher, code in a trigger body may reference and use LOB (Large OBject) columns, but
it may not modify the values of the columns. This is also true for object columns.

What is Trigger Privilege?


There are five system privileges that apply to triggers.
CREATE TRIGGER
Allows the grantee to create a trigger in his or her own schema.
CREATE ANY TRIGGER
Allows the grantee to create triggers in any schema except SYS. It is not recommended to create triggers on
data dictionary tables.
ALTER ANY TRIGGER
Allows the grantee to enable, disable, or compile database triggers in any schema except SYS. Note that if
the grantee does not have CREATE ANY TRIGGER, he or she cannot change trigger code.
DROP ANY TRIGGER
Allows the grantee to drop database triggers in any schema except SYS.
ADMINISTER DATABASE TRIGGER
Allows the grantee to create or alter a system trigger on the database (as opposed to the current schema).
The grantee must also have either CREATE TRIGGER or CREATE ANY TRIGGER.

Triggers and the Data Dictionary:


When a trigger is created, its source code is stored in the data dictionary view user-triggers.
There are also two additional views: all-triggers contains information about the triggers which are
accessible to the current user and dba-triggers contains information about all triggers in the database.

Dropping and Disabling Triggers


DROP TRIGGER triggername;
ALTER TRIGGER triggername {DISABLE/ ENABLE};
All triggers for a particular table can be enabled or disabled using the ALTER TABLE command as well, by
adding the ENABLE ALL TRIGGERS or the DISABLE ALL TRIGGERS clause.

ALTER TABLE students


ENABLE ALL TRIGGERS;

ALTER TABLE students


DISABLE ALL TRIGGERS;

What is Mutating Tables?


A mutating table is a table that is currently being modified by a DML statement. For a trigger, this is the
table on which the trigger is defined. Tables that may need to be updated as a result of DELETE
CASCADE referential integrity constraints are also mutating. A constraining table is a table that might need
to be read from for a referential integrity constraint.

SQL statements in a trigger body may not


Read from or modify any mutating table of the triggering statement. This includes the triggering table itself.
Read from or modify the primary-, unique-, or foreign-key columns of a constraining table of the triggering
table. They may, however, modify the other columns if desired.
These restrictions apply to all row-level triggers. They apply for statement triggers only when the statement
trigger would be fired as a result of a DELETE CASCADE operation.

If an INSERT statement affects only one row, the before and after row triggers for that row do not treat the
triggering table as mutating. This is the only case where a row-level trigger may read from or modify the
triggering table. Statements such as INSERT INTO table SELECT... always treat the triggering table as
mutating, even if the subquery returns only one row.

Can you use a commit statement within a database trigger?


What is an UTL_FILE. What are different procedures and functions associated with it?
What is OCI. What are its uses?
What are ORACLE PRECOMPILERS?
What is syntax for dropping a procedure and a function? Are these operations possible?
Can a function take OUT parameters. If not why?
Can the default values be assigned to actual parameters?
What is difference between a formal and an actual parameter?
What are different modes of parameters used in functions and procedures?
Difference between procedure and function.
Can cursor variables be stored in PL/SQL tables.If yes how. If not why?
How do you pass cursor variables in PL/SQL?
How do you open and close a cursor variable.Why it is required?
What should be the return type for a cursor variable.Can we use a scalar data type as return type?
What is use of a cursor variable? How it is defined?
What is a cursor for loop?
What are cursor attributes?
Difference between an implicit & an explicit cursor.
What is the purpose of a cluster?
How do you find the numbert of rows in a Table ?
Display the number value in Words?
How you will avoid your query from using indexes?
What is a OUTER JOIN?
Which is more faster - IN or EXISTS?
When do you use WHERE clause and when do you use HAVING clause?
There is a % sign in one field of a column. What will be the query to find it?
What is difference between SUBSTR and INSTR?
Which datatype is used for storing graphics and images?
What is difference between SQL and SQL*PLUS?
What is difference between UNIQUE and PRIMARY KEY constraints?
What is difference between Rename and Alias?
What are various joins used while writing SUBQUERIES?

project related questions?


1)tell about ur self?
2)name few packages procedures and functions used in ur project?
3)explain any module in ur package?
4)how many tables,procedures,packages and functions used in ur project?

You might also like