Monday, September 19, 2016

EXCEPTIONS and PRAGMA Interview Questions

What is an Exception ? What are types of Exception ?
A warning or error condition in a PL/SQL program is called an exception. Types of exception are :
  • Internally defined : Oracle Database Error Messages that does not have a name. The runtime system raises them implicitly.
  • Predefined : internally defined exceptions that have predefined names, which PL/SQL declares globally in the package STANDARD. The runtime system raises them implicitly. E.g.: Zero_Divide, No_Data_Found, DUP_VAL_ON_INDEX, TOO_MANY_ROWS etc.
  • User-Defined : declare your own exceptions in the declarative part of any PL/SQL anonymous block, subprogram, or package.
Syntax is : exception_name EXCEPTION;
E.g.: DECLARE
out_of_stock EXCEPTION;
number_on_hand NUMBER(4);
BEGIN
...
IF number_on_hand < 1 THEN
RAISE out_of_stock;
END IF;
EXCEPTION
WHEN out_of_stock THEN
-- handle the error
END;

What is RAISE_APPLICATION_ERROR ?
The procedure RAISE_APPLICATION_ERROR lets you issue user-defined ORA- error messages from stored subprograms. That way, you can report errors to your application and avoid returning unhandled exceptions.

To call RAISE_APPLICATION_ERROR, use the syntax :

raise_application_error(error_number, message[, {TRUE | FALSE}]);

where error_number is a negative integer in the range -20000 .. -20999 and message is a character string up to 2048 bytes long. If the optional third parameter is TRUE, the error is placed on the stack of previous errors. If the parameter is FALSE (the default), the error replaces all previous errors. RAISE_APPLICATION_ERROR is part of package DBMS_STANDARD, and as with package STANDARD, you do not need to qualify references to it.

In the following example, you call raise_application_error if an employee's salary is missing:

CREATE PROCEDURE raise_salary (emp_id NUMBER, amount NUMBER) AS
curr_sal NUMBER;
BEGIN
SELECT sal INTO curr_sal FROM emp WHERE empno = emp_id;
IF curr_sal IS NULL THEN
/* Issue user-defined error message. */
raise_application_error(-20101, 'Salary is missing');
ELSE
UPDATE emp SET sal = curr_sal + amount WHERE empno = emp_id;
END IF;
END raise_salary;

What is the range of the Error Codes for User-Defined Exceptions ?
The range of error code is between -20000 and -20999.

What is the starting oracle error number ?
ORA-00000 normal, successful completion

Explain about SQLERRM and SQLCODE and their importance.
SQLERRM returns the error message for the last error that came across. SQLERRM is useful for WHEN OTHERS Exception. They can be used for Reporting purpose in Error Handling. They can also store the Error in the Code and store it in the Error Log Table. SQLCODE Returns the Value of the Error Number for the previous error.

What is the Difference between Runtime errors and Syntax errors ?
A Runtime Error is handled with the help of Exception Handling Mechanism in a PL/SQL Block whereas a Syntax Error such as a spelling mistake is efficiently detected by the SQL Compiler.

How can you assign a Name to an Un-Named PL/SQL Exception Block ?
You can assign a name to an Un-Named Exception using Pragma, also known as Exception_init.

Explain about Pragma Exception_Init.
To handle error conditions (typically ORA- messages) that have no predefined name, you must use the OTHERS handler or the pragma EXCEPTION_INIT. In PL/SQL, the pragma EXCEPTION_INIT tells the compiler to associate an exception name with an Oracle error number.

Syntax : PRAGMA EXCEPTION_INIT(exception_name, -Oracle_error_number);

where exception_name is the name of a previously declared exception and the number is a negative value corresponding to an ORA- error number. The pragma must appear somewhere after the exception declaration in the same declarative section, as shown in the following example:

DECLARE
deadlock_detected EXCEPTION;
PRAGMA EXCEPTION_INIT(deadlock_detected, -60);
BEGIN
... -- Some operation that causes an ORA-00060 error
EXCEPTION
WHEN deadlock_detected THEN
-- handle the error
END;


What is PRAGMA ? What are the different types of PRAGMA ?
PRAGMA refers to a compiler directive or "hint" it is used to provide an instruction to the compiler. Pragma tells Oracle to use specific rules other than the default rules for a particular object. They are processed at compile time, not at run time.

Differnt types of PRAGMA are:

RESTRICTED_REFERENCES : To check for violations of the rules at compile time, you can use the compiler directive PRAGMA RESTRICT_REFERENCES. This pragma asserts that a function does not read and/or write database tables and/or package variables. Functions that do any of these read or write operations are difficult to optimize, because any call might produce different results or encounter errors.

EXCEPTION_INIT : This pragma is used to associates an exception name with an Oracle error number.

Declare MyExcep exception;
PRAGMA EXCEPTION_INIT(MyExcep,10001);
begin
..…

exception
when I then
dbms_output.put_line( 'Duplicate value');
end;

AUTONOMOUS_TRANSACTION : this pragma changes the way a subprogram works within a transaction. A subprogram marked with this pragma can do SQL operations and commit or roll back those operations, without committing or rolling back the data in the main transaction.

Eg : When you declare a trigger as AUTONOMOUS_TRANSACTION, then you can commit inside the trigger, irrespective of the calling procedure.

CREATE OR REPLACE TRIGGER audit_sal
AFTER UPDATE OF salary ON employees FOR EACH ROW
DECLARE
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
-- bind variables are used here for values
INSERT INTO emp_audit VALUES( :old.employee_id, SYSDATE,
:new.salary, :old.salary );
COMMIT;
END;

SERIALLY_REUSABLE : indicates that the package state is needed only for the duration of one call to the server. This pragma is appropriate for packages that declare large temporary work areas that are used once and not needed during subsequent database calls in the same session. You can mark a bodiless package as serially reusable. If a package has a spec and body, you must mark both.

INLINE : (introduced in 11g) specifys that a subprogram call is, or is not, to be inlined. Inlining replaces a subprogram call (to a subprogram in the same program unit) with a copy of the called subprogram.

E.g.: PROCEDURE p1 (x PLS_INTEGER) IS ...
...
PRAGMA INLINE (p1, 'YES');
x:= p1(1) + p1(2) + 17; -- These 2 calls to p1 will be inlined
...
x:= p1(3) + p1(4) + 17; -- These 2 calls to p1 will not be inlined




Thursday, September 8, 2016

Collections & Record Interview Questions

What is a collection in pl/sql ?
A collection is an ordered group of elements, all of the same type. It is a general concept that encompasses lists, arrays, and other datatypes used in classic programming algorithms. Each element is addressed by a unique subscript.

PL/SQL has three collection types:

An associative array (also called an index-by table) is a set of key-value pairs. Each key is unique, and is used to locate the corresponding value. The key can be either an integer or a string. Using a key-value pair for the first time adds that pair to the associative array. Using the same key with a different value changes the value.

Example : Declaring and Using an Associative Array

SQL> DECLARE
2 -- Associative array indexed by string:
3
4 TYPE population IS TABLE OF NUMBER -- Associative array type
5 INDEX BY VARCHAR2(64);
6
7 city_population population; -- Associative array variable
8 i VARCHAR2(64);
9
10 BEGIN
11 -- Add new elements to associative array:
12
13 city_population('Agra') := 2000;
14 city_population('Noida') := 750000;
15 city_population('Delhi') := 1000000;
16
17 -- Change value associated with key 'Agra':
18
19 city_population('Agra') := 2001;
20
21 -- Print associative array:
22
23 i := city_population.FIRST;
24
25 WHILE i IS NOT NULL LOOP
26 DBMS_Output.PUT_LINE
27 ('Population of ' || i || ' is ' || TO_CHAR(city_population(i)));
28 i := city_population.NEXT(i);
29 END LOOP;
30 END;
31 /
Population of Delhi is 1000000
Population of Noida is 750000
Population of Agra is 2001
PL/SQL procedure successfully completed.
SQL>

An associative array is intended for temporary data storage. To make an associative array persistent for the life of a database session, declare the associative array (the type and the variable of that type) in a package, and assign values to its elements in the package body.


A nested table is like a one-dimensional array with an arbitrary number of elements. Within the database, a nested table is a column type that holds a set of values.

Example : Declaring and Using a nested table:

SQL> DECLARE
2 TYPE names_table IS TABLE OF VARCHAR2(10);
3 TYPE grades IS TABLE OF INTEGER;
4
5 names names_table;
6 marks grades;
7 total integer;
8 BEGIN
9 names := names_table('Jitendra', 'Chinmay', 'Ankit', 'Abhinav', 'Vivek');
10 marks:= grades(98, 97, 78, 87, 92);
11 total := names.count;
12 dbms_output.put_line('Total '|| total || ' Students');
13 FOR i IN 1 .. total LOOP
14 dbms_output.put_line('Student:'||names(i)||', Marks:' || marks(i));
15 end loop;
16 END;
17 /
Total 5 Students
Student:Jitendra, Marks:98
Student:Chinmay, Marks:99
Student:Ankit, Marks:78
Student:Abhinav, Marks:87
Student:Vivek, Marks:92

PL/SQL procedure successfully completed.

SQL>

Elements of a nested table could also be a %ROWTYPE of any database table or %TYPE of any database table field.

Example:
TYPE DocIndex_TYPE IS TABLE OF ISDoc.DocIndex%TYPE;
doc_type DocIndex_TYPE;
doc_size DocIndex_TYPE;

A varray is a variable-size array of a datatype which has a maximum size, which you specify in its type definition. A varray can contain a varying number of elements, from zero (when empty) to the maximum size. To access an element of a varray, you use standard subscripting syntax.

Example :
      DECLARE
         TYPE Calendar IS VARRAY(366) OF DATE;


What is the difference between varray and nested table ?
  • A varray has a declared number of elements, but a nested table does not. The size of a nested table can increase dynamically.
  • An varray is always dense (that is, it always has consecutive subcripts). A nested table is dense initially, but it can become sparse, because you can delete elements from it.


What is a Record in pl/sql ?
A record is a group of related data items stored in fields, each with its own name and datatype. You can think of a record as a variable that can hold a table row, or some columns from a table row.

DECLARE
-- Declare a record type with 3 fields.
TYPE rec1_t IS RECORD (field1 VARCHAR2(16), field2 NUMBER, field3 DATE);


What is difference between % ROWTYPE and TYPE RECORD ?
% ROWTYPE is to be used whenever query returns a entire row of a table or view.

TYPE rec RECORD is to be used whenever query returns columns of different table or views and variables.

E.g. TYPE r_emp is RECORD (eno emp.empno% type,ename emp ename %type);
         e_rec emp% ROWTYPE
         cursor c1 is select empno,deptno from emp;
         e_rec c1 %ROWTYPE.




Friday, September 2, 2016

Transactions Interview Questions

What is Transaction ?
A transaction is a logical, atomic unit of work that contains one or more SQL statements. A transaction groups SQL statements so that they are either all committed, which means they are applied to the database, or all rolled back, which means they are undone from the database. Oracle Database assigns every transaction a unique identifier called a transaction ID. All Oracle transactions obey the ACID properties.

What is autonomous transaction ?
An autonomous transaction is an independent transaction that can be called from another transaction, which is the main transaction. You can suspend the calling transaction, perform SQL operations and commit or undo them in the autonomous transaction, and then resume the calling transaction.

Autonomous transactions have the following characteristics:
  • Does not see uncommitted changes made by the main transaction and does not share locks or resources with the main transaction.
  • Changes in an autonomous transaction are visible to other transactions upon commit of the autonomous transactions. Thus, users can access the updated information without having to wait for the main transaction to commit.
  • Autonomous transactions can start other autonomous transactions. There are no limits, other than resource limits, on how many levels of autonomous transactions can be called.

What is Commit ?
The COMMIT statement makes permanent any changes made to the database during the current transaction. A commit also makes the changes visible to other users. The COMMIT statement releases all row and table locks, and erases any savepoints you marked since the last commit or rollback.

What is Rollback ?
The ROLLBACK statement undoes some or all database changes made during the current transaction. All savepoints marked after the savepoint to which you roll back are erased. The savepoint to which you roll back is not erased.

What is Set Transaction ?
SET TRANSACTION statement is used to establish the current transaction as read-only or read/write, establish its isolation level, or assign it to a specified rollback segment. The operations performed by a SET TRANSACTION statement affect only your current transaction, not other users or other transactions.

Syntax for the SET TRANSACTION statement:

SET TRANSACTION [ READ ONLY | READ WRITE ]
[ ISOLATION LEVEL [ SERIALIZE | READ COMMITED ]
[ USE ROLLBACK SEGMENT 'segment_name' ]
[ NAME 'transaction_name' ];

What are transaction isolation levels in oracle ?
Oracle provides following transaction isolation levels:

Read Committed : In the read committed isolation level, which is the default, every query executed by a transaction sees only data committed before the query—not the transaction—began.
Serializable : In the serializable isolation level, a transaction sees only changes committed at the time the transaction—not the query—began and changes made by the transaction itself.
Read-Only : The read-only isolation level is similar to the serializable isolation level, but read-only transactions do not permit data to be modified in the transaction unless the user is SYS.

What are savepoints ?
The SAVEPOINT statement names and marks the current point in the processing of a transaction.

What will happen after commit statement ?
Committing a transaction means making permanent the changes performed by the SQL statements within the transaction.

Before a transaction that modifies data is committed, the following has occurred:

  • Oracle has generated undo information. The undo information contains the old data values changed by the SQL statements of the transaction.
  • Oracle has generated redo log entries in the redo log buffer of the SGA. The redo log record contains the change to the data block and the change to the rollback block. These changes may go to disk before a transaction is committed.
  • The changes have been made to the database buffers of the SGA. These changes may go to disk before a transaction is committed.

When a transaction is committed, the following occurs:

  • The internal transaction table for the associated undo tablespace records that the transaction has committed, and the corresponding unique system change number (SCN) of the transaction is assigned and recorded in the table.
  • The log writer process (LGWR) writes redo log entries in the SGA's redo log buffers to the redo log file. It also writes the transaction's SCN to the redo log file. This atomic event constitutes the commit of the transaction.
  • Oracle releases locks held on rows and tables.
  • Oracle marks the transaction complete.


What is Locking ? What are different modes of locking ?
Locking is the mechanisms that prevent destructive interaction between transactions accessing the same resource — either user objects such as tables and rows or system objects not visible to users, such as shared data structures in memory and data dictionary rows.
Modes of Locking are Exclusive lock mode and Share lock mode.

What is Deadlock ?
Deadlock is a situation that can occur when two or more users are waiting for data locked by each other. Deadlocks prevent some transactions from continuing to work. Oracle automatically detects deadlock situations and resolves them by rolling back one of the statements involved in the deadlock, thereby releasing one set of the conflicting row locks.

How can you Rollback a particular part of a procedure or any PL/SQL Program ?
It can be done using Savepoints during definition of a PL/SQL program.

What is the difference between Autonomous Transaction and Nested Transaction ?
As in case of Nested Transaction, Autonomous Transaction :

1. Do not share trasaction resources like variables with main transaction.
2. Have to be commited or rolled back separately.
3. It does not depend on main transaction. When main transaction rolls back, nested transaction also rolls back but autonomous transaction does not.
4. Exceptions raised in autonomous transaction are transaction-level and not statement-level.