Monday, July 8, 2019

30 Most Important PL/SQL Interview Questions And Answers

Question #1) Differentiate PL/SQL and SQL?
Answer: Difference between SQL and PL/SQL can be categorized as follows
SQLPL/SQL
SQL is a natural language which is very useful for interactive processing.PL/SQL is a procedural extension of Oracle - SQL.
No procedural capabilities like condition testing, looping is offered by SQL.PL/SQL supports procedural capabilities as well as high language features such as conditional statements, looping statements, etc.
All SQL statements are executed by the database server one at a time, thus it is a time-consuming process.PL/SQL statements send the entire block of statements to the database server at the same time, thus network traffic is reduced considerably.
No error handling procedures are there in SQL.PL/SQL supports customized error handling.
Question #2) Enlist the characteristics of PL/SQL?
Answer: Characteristics of PL/SQL are as follows
  • PL/SQL allows access and sharing of the same sub programs by multiple applications.
  • PL/SQL is known for portability of code as code can be executed on any operating system provided Oracle is loaded on it.
  • With PL/SQL user can write their own customized error handling routines.
  • Improved transaction performance with integration to Oracle data dictionary.
Question #3) What are the data types available in PL/SQL?
Answer: Data types define the ways to identify the type of data and their associated operations. There are 4 types of predefined data types explained as follows
  • Scalar Data Types: A scalar data type is an atomic data type that does not have any internal components.
  • For example
    • CHAR (fixed length character value between 1 and 32,767 characters)
    • VARCHAR2 (variable length character value between 1 and 32,767 characters)
    • NUMBER ( fixed-decimal, floating-decimal or integer values)
    • BOOLEAN ( logical data type for TRUE FALSE or NULL values)
    • DATE (stores date and time information)
    • LONG (character data of variable length)
  • Composite Data Types: A composite data type is made up of other data types and internal components that can be easily used and manipulated. For example RECORD, TABLE, and VARRAY.
  • Reference Data Types: A reference data types holds values, called pointers that designate to other program items or data items. For example REF CURSOR.
  • Large Object Data Types: A Large Object datatype holds values, called locators, that defines the location of large objects( such as video clips, graphic image, etc) stored out of line.
  • For example
    • BFILE (Binary file)
    • BLOB (Binary large object)
    • CLOB ( Character large object)
    • NCLOB( NCHAR type large object)
Question #4) Explain the purpose of %TYPE and %ROWTYPE data types with the example?
Answer: PL/SQL uses %TYPE declaration attribute for anchoring. This attribute provides the datatype of a variable, constant or column. %TYPE attribute is useful while declaring a variable that has the same datatype as a table column.
For example, the variable m_empno has the same data type and size as the column empno in table emp.
m_empno emp.empno%TYPE;
%ROWTYPE attribute is used to declare a variable to be a record having the same structure as a row in a table. The row is defined as a record and its fields have the same names and data types as the columns in the table or view.
For example: dept_rec dept%ROWTYPE;
This declares a record that can store an entire row for DEPT table.
Question #5) What do you understand by PL/SQL packages?
Answer: PL/SQL packages are schema objects that groups functions, stored procedures, cursors and variables at one place. Packages have 2 mandatory parts
  • Package Specifications
  • Package body
Question #6) What do you understand by PL/SQL cursors?
Answer: PL/SQL requires a special capability to retrieve and process more than one row and that resource is known as Cursors. A cursor is a pointer to the context area, which is an area of memory containing SQL statements and information for processing the statements.
PL/SQL Cursor is basically a mechanism under which multiple rows of the data from the database are selected and then each row is individually processed inside a PL/SQL program.
Question #7) Explain cursor types?
Answer: There are two types of cursors. They are explained as follows
1) Explicit Cursors: For queries that return more than one row, an explicit cursor is declared and named by a programmer. In order to use explicit cursor in PL/SQL, 4 steps are followed
Declare the cursor
Syntax: CURSOR <cursor_name> is
SELECT statement;
Where <cursor_name> is the name assigned to the cursor and SELECT statement is the query that returns rows to the cursor active set.
Open the cursor
Syntax: OPEN <cursor_nam>;
Where, <cursor_name> is the name of the previously defined cursor.
Fetch rows from the cursor
Syntax: FETCH <cursor_name> INTO <record_list>;
Where <cursor_name> refers to the name of the previously defined cursor from which rows are being fetched.
<record_list> represents the list of variables that will receive the data being fetched.
Closing the cursor
Syntax: CLOSE <cursor_name>;
Where <cursor_name> is the name of the cursor being closed.
2) Implicit cursors: When any SQL statement is executed, PL/SQL automatically creates a cursor without defining such cursors are known as implicit cursors.
For following statements, PL/SQL employs implicit cursors
  • INSERT
  • UPDATE
  • DELETE
  • SELECT ( queries that return exactly one row)
Question #8) When do we use triggers?
Answer: The word ‘Trigger’ means to activate. In PL/SQL, the trigger is a stored procedure that defines an action taken by the database when database related event is performed. Triggers are mainly required for the following purposes
  • To maintain complex integrity constraints
  • Auditing table information by recording the changes
  • Signaling other program actions when changes are made to table
  • Enforcing complex business rules
  • Preventing invalid transactions
Question #9) Explain the difference in execution of triggers and stored procedures?
Answer: A stored procedure is executed explicitly by issuing procedure call statement from another block via a procedure call with arguments.
The trigger is executed implicitly whenever any triggering event like the occurrence of DML statements happens.
Question #10) Explain the difference between Triggers and Constraints?
Answer: Triggers are different from constraints in the following ways
TriggersConstraints
Only affect those rows added after the trigger is enabled.Affect all rows of the table including that already exist when the constraint is enabled.
Triggers are used to implement complex business rules which cannot be implemented using integrity constraints.Constraints maintain the integrity of the database.
Question #11) What is a PL/SQL block?
Answer: In PL/SQL, statements are grouped into units called Blocks. PL/SQL blocks can include constants, variables, SQL statements, loops, conditional statements, exception handling. Blocks can also build a procedure, a function or a package.
Broadly, PL/SQL blocks are two types
1) Anonymous blocks: PL/SQL blocks without header are known as anonymous blocks. These blocks do not form the body of a procedure, function or triggers.
Example:
1DECLARE
2num NUMBER(2);
3sq NUMBER(3);
4BEGIN
5num:= &Number1;
6sq := num*num;
7DBMS_OUTPUT.PUT_LINE(‘Square:’ ||sq);
8END;
2) Named blocks: PL/SQL blocks having header or labels are known as Named blocks. Named blocks can either be subprograms (procedures, functions, packages) or Triggers.
Example:
1FUNCTION sqr (num IN NUMBER)
2RETURN NUMBER is sq NUMBER(2);
3BEGIN
4sq:= num*num;
5RETURN sq;
6END;
Question #12) Differentiate between syntax and runtime errors?
Answer: Syntax errors are the one which can be easily identified by a PL/SQL compiler. These errors can be the spelling mistake, etc.
Runtime errors are those errors in PL/SQL block for which exception handling section is to be included for handling the errors. These errors can be SELECT INTO statement which does not return any rows.
Question #13) What are COMMIT, ROLLBACK, and SAVEPOINT?
Answer: COMMIT, SAVEPOINT, and ROLLBACK are three transaction specifications available in PL/SQL.
COMMIT statement: When DML operation is performed, it only manipulates data in database buffer and the database remains unaffected by these changes. To save/store these transaction changes to the database, we need to COMMIT the transaction. COMMIT transaction saves all outstanding changes since the last COMMIT and the following process happens
  • Affected rows locks are released
  • Transaction marked as complete
  • Transaction detail is stored in the data dictionary.
Syntax: COMMIT;
 ROLLBACK statement: When we want to undo or erase all the changes that have occurred in the current transaction so far, we require rolling back of the transaction. In other words, ROLLBACK erases all outstanding changes since the last COMMIT or ROLLBACK.
Syntax to rollback a transaction fully
ROLLBACK;
SAVEPOINT statement: The SAVEPOINT statement gives a name and marks a point in the processing of the current transaction. The changes and locks that have occurred before the SAVEPOINT in the transaction are preserved while those that occur after the SAVEPOINT are released.
Syntax:
SAVEPOINT <savepoint_name>;
Question #14) What is the mutating table and constraining table?
Answer: A table which is currently being modified by a DML statement like defining triggers in a table is known as a Mutating table.
A table that might need to be read from for a referential integrity constraint is known as constraining table.
Question #15) What are actual parameters and formal parameters?
Answer: The variables or an expression referred to as parameters that appear in the procedure call statement is known as Actual parameters.
For example: raise_sal(emp_num, merit+ amount);
Here in the above example, emp_num and amount are the two actual parameters.
The variables that are declared in the procedure header and are referenced in the procedure body are called as Formal parameters.
For example:
PROCEDURE raise_sal( emp_id INTEGER) IS
curr_sal REAL:
………..
BEGIN
SELECT sal INTO cur_sal FROM emp WHERE empno = emp_id;
…….
END raise_sal;
Here in the above example, emp_id acts as a formal parameter.
Question #16) What is the difference between ROLLBACK and ROLLBACK TO statements?
Answer: The transaction is completely ended after ROLLBACK statement i.e. ROLLBACK command completely undoes a transaction and release all locks.
On the other hand, a transaction is still active and running after ROLLBACK TO command as it undoes a part of the transaction up till the given SAVEPOINT.
Question #17) Write a PL/SQL script to display the following series of numbers: 99,96,93……9,6,3?
Answer
1SET SERVER OUTPUT ON
2DECLARE
3BEGIN
4FOR IN REVERSE 1..99
5LOOP
6IF Mod(i,3) = 0 THEN
7DBMS_OUTPUT.PUT_LINE(i);
8END IF;
9END LOOP;
10END;
11/
Question #18) What are the 3 modes of parameter?
Answer: 3 modes of the parameter are IN, OUT, IN OUT. These can be explained as follows
IN parameters: IN parameters allow you to pass values to the procedure being called and can be initialized to default values. IN parameters acts like a constant and cannot be assigned any value.
OUT parameters: OUT parameters return value to the caller and they must be specified. OUT parameters act like an uninitialized variable and cannot be used in an expression.
IN OUT parameters: IN OUT parameters passes initial values to a procedure and returns updated values to the caller. IN OUT parameters act like an initialized variable and should be assigned a value.
Question #19) Why is %ISOPEN always false for an implicit cursor?
Answer: An implicit cursor, SQL%ISOPEN attribute is always false because the implicit cursor is opened for a DML statement and is closed immediately after the execution of DML statement.
Question #20) When a DML statement is executed, in which cursor attributes, the outcome of the statement is saved?
Answer: The outcome of the statement is saved in 4 cursor attributes. These are
  • SQL%FOUND
  • SQL%NOTFOUND
  • SQL%ROWCOUNT
  • SQL%ISOPEN
Question #21) What are the ways on commenting in a PL/SQL code?
Answer: Comments are the text which is included with the code to enhance readability and for the understanding of the reader. These codes are never executed. There are two ways to comment in PL/SQL
1) Single line comment: This comment starts with double –.
Example:
DECLARE
num NUMBER(2);        — it is a local variable.
BEGIN
2) Multi-line comment: This comment starts with /* and ends with */.
Example:
BEGIN
num := &p_num;         /* This is a host variable used in program body */
……….
END
Question #22) What do you understand by Exception handling in PL/SQL?
Answer: When an error occurs in PL/SQL, the exception is raised. In other words, to handle undesired situations where PL/SQL scripts terminated unexpectedly, an error handling code is included in the program. In PL/SQL, all exception handling code is placed in EXCEPTION section.
There are 3 types of EXCEPTION:
  • Predefined Exceptions: Common errors with predefined names.
  • Undefined Exceptions: Less common errors with no predefined names.
  • User-defined Exceptions: Do not cause runtime error but violate business rules.
Question #23) Enlist some predefined exceptions?
Answer: Some of the predefined exceptions are
  • NO_DATA_FOUND: Single row SELECT statement where no data is returned.
  • TOO_MANY_ROWS: Single row SELECT statement where more than one rows are returned.
  • INVALID_CURSOR: Illegal cursor operation occurred.
  • ZERO_DIVIDE: Attempted to divide by zero.
Question #24) What are PL/SQL cursor exceptions?
Answer: The exceptions related to PL/SQL cursors are
  • CURSOR_ALREADY_OPEN
  • INVALID_CURSOR
Question #25) Explain the difference between cursor declared in procedures and cursors declared in the package specification?
Answer: The cursor declared in the procedure is treated as local and thus cannot be accessed by other procedures.
The cursor declared in the package specification is treated as global and thus can be accessed by other procedures.
Question #26) What are INSTEAD of triggers?
Answer: The INSTEAD OF triggers are the triggers written especially for modifying views, which cannot be directly modified through SQL DML statements.
Question #27) What are expressions?
Answer: Expressions are represented by a sequence of literals and variables that are separated by operators. In PL/SQL, operations are used to manipulate, compare and calculate some data. An expression is a composition of ‘Operators’ and ‘Operands’.
  • Operands: These are an argument to the operators. Operands can be a variable, function call or constant.
  • Operators: These specify the actions to be performed on operators. E.g. ‘+’, ‘*’, etc.
Question #28) List different type of expressions with the example.
Answer: Expressions can be as mentioned below
  • Numeric or Arithmetic expressions : e.g. 20* 10+ 15
  • Boolean expressions: e.g. ‘spot’ LIKE ‘sp%t’
  • String expressions: e.g. LENGTH (‘NEW YORK’|| ‘NY’)
  • Date expressions: e.g. SYSDATE>TO_DATE(’15-NOV-16’, “dd-mm-yy”)
Question #29) Write a program that shows the usage of WHILE loop to calculate the average of user entered numbers and entry of more numbers are stopped by entering number 0?
Answer
1DECLARE
2n NUMBER;
3avg NUMBER :=0 ;
4sum NUMBER :=0 ;
5count NUMBER :=0 ;
6BEGIN
7n := &enter_a_number;
8WHILE(n<>0)
9LOOP
10count := count+1;
11sum := sum+n;
12n := &enter_a_number;
13END LOOP;
14avg := sum/count;
15DBMS_OUTPUT.PUT_LINE(‘the average is’||avg);
16END;
Question #30) What do you understand by PL/SQL Records?
Answer: A PL/SQL records can be referred as a collection of values or say, a group of multiple pieces of information, each of which is of simpler types and can be related to one another as fields.
There are three types of records supported in PL/SQL
  • Table based records
  • Programmer based records
  • Cursor based records

No comments:

Post a Comment

Get max value for identity column without a table scan

  You can use   IDENT_CURRENT   to look up the last identity value to be inserted, e.g. IDENT_CURRENT( 'MyTable' ) However, be caut...