Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1.

What are the programming constructs supported by PL/SQL?

Answer»

PL/SQL is an extension for SQL and Oracle. It enhances the capabilities of SQL. Therefore, with every release of the Oracle Database, the feature and functionalities of PL/SQL is enhanced.

It is available in Oracle Database since version 6. However, PL/SQL is also available in TimesTen in-memory database since version 11.2.1 and IBM DB2 since version 9.7.

PL/SQL is strongly integrated with SQL and supports both static and dynamic SQL.

The following are the FEATURES in PL/SQL:

  • PL/SQL is a procedural language that extends SQL.
  • PL/SQL has a built-in interpreted programming environment.
  • PL/SQL's syntax has SHAPED ADA and PASCAL programming language.
  • Structured programming is possible with PL/SQL through functions and procedures.
  • It has Block Structures as well as nest block structures. Executes as a whole block.
  • PL/SQL has object-oriented features in it.
  • PL/SQL also comes with the functionality of Triggers. Triggers are stored in a database and fired when some event occurs. The event here can be a Database Manipulation statement i.e. DELETE, INSERT, or UPDATE, or a Database Definition statement (CREATE, ALTER, or DROP).
  • PL/SQL is a standard language for Oracle development.
  • PL/SQL is USED to write program blocks, functions, procedures triggers, etc.
  • It has cursors. Oracle forms a memory area, when an SQL statement is processed. This memory area is called context area. A cursor in PL/SQL is a pointer to this context area. It has INFORMATION about processing the statement.
2.

Why do we use VSIZE() function in PL/SQL?

Answer»

The PL/SQL PROGRAMMING CONSTRUCTS INCLUDE:

  1. EMBEDDED SQL support
  2. Stored procedures
  3. Packages
  4. Triggers
  5. Exception Handling
  6. Cursors
3.

How to pad a string with zeros on the right in PL/SQL?

Answer»

The VSIZE() function RETURNS the number of bytes in the INTERNAL REPRESENTATION of an EXPRESSION. An example:

VSIZE('Selection DAY')

The output:

13
4.

What are the types of Strings in PL/SQL?

Answer»

To pad a string with zeros, you can use RPAD or LPAD function in PL/SQL. Let us see how to pad the right SIDE of a string with zeros:

RPAD(tom, 6)

The output would have a WIDTH of 6 characters now. SINCE the string is of 3 characters, therefore REST of the space would be filled with 0S:

tom000

5.

Does VARRAY exist in PL/SQL?

Answer»

Sequence of characters are called STRINGS. Just like any other language, a string can be letters, numbers, special characters, etc.

The following are the three types of strings in PL/SQL:

  • Fixed-length strings

In fixed-length strings, the length is to be specified while DECLARING a string. The string is right-padded with spaces to the length so specified.

A maximum length up to 32,767 for the string is specified and no padding TAKES place.

  • Character large objects (CLOBs)

CLOBs are variable-length strings that can be up to 128 terabytes.

Let us see how we can declare a String variable. We have a lot of string datatypes, such as CHAR, NCHAR, VARCHAR2, NVARCHAR2, CLOB, and NCLOB in PL/SQL.

The declaration:

DECLARE    cars varchar2(25) := 'Bentley;

Let us see an example where we have two variables:

DECLARE   CAR varchar2(15) := 'Bentley';   device varchar2(11) := 'Laptop'; BEGIN   dbms_output.put_line(UPPER(car));   dbms_output.put_line(LOWER(car));   dbms_output.put_line(device);   dbms_output.put_line(UPPER(device)); END; /

The output:

BENTLEY bentley Laptop LAPTOP
6.

What are the guidelines to be used before creating a PL/SQL Package?

Answer»

VARRARY data STRUCTURE store a fixed-size sequential collection of elements of the same type. It has contiguous memory locations with the lowest address as the FIRST element and the highest address as the last element.

The CREATE TYPE statement is used to create a varray type. The following is the syntax for creating a VARRAY type within a PL/SQL block:

TYPE name_of_varray_type IS VARRAY(n) of <type_of_element>

Here,

n is the number of elements, name_of_varray_type is a valid attribute name, and type_of_element is the data type of the elements of the array

The following is an example:

Type marks IS VARRAY(10) OF INTEGER;

Let us see an example wherein we are DISPLAYING the appraisal points for employees according to their IDs:

DECLARE   type points IS VARRAY(10) OF INTEGER;   appraisal_points points;   total integer; BEGIN   appraisal_points:= points(76, 79, 89, 96, 99, 86, 89, 97);   total := appraisal_points.count;   FOR i in 1 .. total LOOP      dbms_output.put_line('Appraisal Points for Employee ' || i || ' = ' || appraisal_points(i));   END LOOP; END; /

The output:

Appraisal Points for Employee 1 = 76 Appraisal Points for Employee 2 = 79 Appraisal Points for Employee 3 = 89 Appraisal Points for Employee 4 = 96 Appraisal Points for Employee 5 = 99 Appraisal Points for Employee 6 = 86 Appraisal Points for Employee 7 = 89 Appraisal Points for Employee 8 = 97
7.

What is the use of WHEN clause in PL/SQL?

Answer»

In PL/SQL, packages are the schema objects that groups logically related PL/SQL types and variables. A Package has the following two PARTS:

  • Package Specification

The specification has the information about the package content. It declares the types, variables, constant, cursors, etc. It EXCLUDES the CODE for subprograms. The objects in the specification are the public OBJECT, however, a subprogram not part of the specification is a private object.

  • Package Body

The Package Body has the implementation of subprogram declared in the specification. To create Package Body, use the CREATE PACKAGE BODY statement.

The following are the guidelines:

  • You need to design and define the package specifications before the package bodies.
  • Declare public cursors in package specifications and define them in package bodies.
  • Assign initial values in the initialization part of the package body. Avoid this in declarations.
8.

How to create a user-defined SUBTYPE in PL/SQL?

Answer»

The WHEN clause has SEARCH conditions that output BOOLEAN values in a searched CASE statement.

The following is the syntax of searched CASE that has the WHEN conditions:

CASE WHEN condition_1 THEN statements_1 WHEN condition_2 THEN statements_2 ... WHEN condition_n THEN statements_n [ ELSE  else_statements ] END CASE;]

Let us see an example:

DECLARE   points number := 100; BEGIN   case        when points = 20 then dbms_output.put_line('Rank 4');      when points = 50 then dbms_output.put_line('Rank 3');      when points = 75 then dbms_output.put_line('Rank 2');      when points = 100 then dbms_output.put_line('Rank1... Topper');      else dbms_output.put_line('No RANKING!');   end case; END; /

The output:

Rank1... Topper
9.

Can a %ROWCOUNT attribute returns the total number of rows returned by the FETCH command?

Answer»

With PL/SQL, we can create a user-defined subtype. It already has PREDEFINED subtypes in STANDARD package.

Let us now SEE how to create an INTEGER subtype:

DECLARE   SUBTYPE info IS varchar2(50);   car info; BEGIN   car:= 'I LOVE cars!';   dbms_output.put_line(car); END; /

The output:

I love cars!
10.

Why do we use the TIMESTAMP datatype in PL/SQL?

Answer»

Yes, a %ROWCOUNT ATTRIBUTE returns the total NUMBER of rows RETURNED by the FETCH command.

11.

What are Named and Mixed Notation in PL/SQL?

Answer»

The TIMESTAMP datatype stores the YEAR, MONTH, and day of the DATE datatype. It also ALLOWS you to store HOUR, minute, and second values.

12.

What is a RAISE Statement in PL/SQL?

Answer»

ACTUAL parameters can be passed as Positional notation, Named notation as well as MIXED notation. In Positional Notation, the same parameters in the same order as they are declared in the procedure are specified.

The actual parameter is associated with the formal parameter in named notation using the arrow symbol ( => ) like:

x => a

The procedure call for this would be:

myFunction(x => a, y => b, z => c);

In PL/SQL, you can mix both notations in procedure call with n mixed notation. REMEMBER, the positional notation should precede the named notation.

myFunction(x, y, z => c);

The following is an example:

Let’s say we have below given table:

<DEPTBUDGET> +-----------+-----------------+---------------+------------------+ | DEPTID | DEPTNAME  | DEPTLOC | BUDGET       | +-----------+-----------------+---------------+------------------+ |  1 | Finance          | NORTH | 56678      | |  2 | Marketing     | EAST |      87687 | |  3 | Operations   | WEST |      98979 | |  4 | Technical      | SOUTH |    76878 | |  5 | Accounting   | NORTHWEST| 86767      | +----------+------------------+------------------+--------------+

Now, we will call with Positional, mixed and named notations:

DECLARE  d_id NUMBER(6) := 2;  d_budget NUMBER(6) := 500;  PROCEDURE new_budget (id NUMBER, amount_add NUMBER) IS    BEGIN      UPDATE employees SET budget = budget + amount_add WHERE deptid = id;  END new_budget ; BEGIN  new_budget (did, d_budget ); -- positional procedure call for actual parameters  new_budget (amount_add => d_budget , id=> d_id); -- named parameters  new_budget (d_id, amount_add => d_budget ); -- mixed parameters END;

Above, you can see we have a procedure “new_budget”. We are updating the budget here:

PROCEDURE new_budget (id NUMBER, amount_add NUMBER) IS    BEGIN      UPDATE employees SET budget = budget + amount_add WHERE deptid = id; END new_budget ;

We are calling one by one with positional, mixed and named notation:

new_budget (did, d_budget ); -- positional procedure call for actual parameters new_budget (amount_add => d_budget , id=> d_id); -- named parameters new_budget (d_id, amount_add => d_budget ); -- mixed parameters
13.

How do we use BETWEEN operation in PL/SQL?

Answer»

The RAISE statement is used in PL/SQL to raise exceptions. Through this a user can raise exceptions explicitly.

The following is the SYNTAX to display how to use raise exceptions with RAISE statement:

DECLARE   exception_name EXCEPTION; BEGIN   IF condition THEN      RAISE exception_name;   END IF; EXCEPTION   WHEN exception_name THEN   statement; END;

An EXAMPLE can be if the ID is less than zero, the raise an exception:

IF d_id <= 0 THEN      RAISE my_exception;

Above “my_exception” is the following we set above:

my_exception EXCEPTION;

Let us see an example wherein we are raising exceptions. The following is the table we are taking into consideration:

<DEPTBUDGET> +-----------+-----------------+---------------+------------------+ | DEPTID | DEPTNAME  | DEPTLOC | BUDGET| +----------+------------------+---------------+------------------+ |  1 | Finance          | NORTH | 56678      | |  2 | Marketing     | EAST |      87687 | |  3 | Operations   | WEST |      98979 | |  4 | TECHNICAL      | SOUTH |    76878 | |  5 | Accounting   | NORTHWEST| 86767      | +----------+------------------+------------------+--------------+

Let’s say we created the following procedure and a user-defined exception in it:

DECLARE   id deptbudget.id%type := &d_id;   deptname deptbudget.deptname%type;   deptloc deptbudget.deptloc%type;     my_exception  EXCEPTION; BEGIN   IF d_id <= 0 THEN      RAISE my_exception;   ELSE      SELECT  deptname, deptloc INTO deptname, deptloc      FROM deptbudget      WHERE id = d_id;      DBMS_OUTPUT.PUT_LINE ('Name: '||  deptname);      DBMS_OUTPUT.PUT_LINE ('Address: ' || deptloc);   END IF; EXCEPTION   WHEN my_exception THEN      dbms_output.put_line('ID is always greater than zero!');   WHEN no_data_found THEN      dbms_output.put_line('No such department in the company!');   WHEN others THEN      dbms_output.put_line('Error!');   END; /

On executing the above procedure, the following output is visible. Let’s say our input is department id as “-2”, yes, a negative number. When execution, it raises the following user-defined error:

ID is always greater than zero!
14.

How to include single quotes in a string literal in PL/SQL?

Answer»

The BETWEEN operator in PL/SQL checks whether a value lies in a specified RANGE or not.

For example, the value a BETWEEN x AND y says that a >= x and a <= y.

Let US see an example:

DECLARE   val NUMBER(2) := 3; BEGIN   IF (val between 1 and 5) THEN      dbms_output.put_line('True');   ELSE      dbms_output.put_line('False');   END IF; END; /

The output:

True

Let us see another example:

DECLARE     val number(2) := 15;  BEGIN     IF (val between 1 and 10) THEN        dbms_output.put_line('True');     ELSE        dbms_output.put_line('False');     END IF;  END;  /

The output:

False
15.

PL/SQL Script to find the factorial of a number

Answer»

To include single QUOTES in a string literal, you NEED to use it like:

“That wasn’’t a big blow to the team”

Above, we have SET TWO single quotes to display one single quote.

Let us see an example.

Our string is:

It's my life

The following is the code to include single quotes:

DECLARE   a varchar2(15):= 'It''s my life!'; BEGIN     dbms_output.put_line(a); END; /

The output:

It's my life!
16.

Why do we use %ROWCOUNT cursor attribute in PL/SQL?

Answer»

To FIND the FACTORIAL of a NUMBER, the FOLLOWING is the code:

DECLARE a number :=1;     n number := 5;     BEGIN while n > 0 loop    a:=n*a;          n:=n-1;             end loop;           dbms_output.put_line(a);    end;

The output:

120
17.

What are Large Object (LOB) data types in PL/SQL?

Answer»

The %ROWCOUNT cursor attribute returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or returned by a SELECT INTO statement.

To use any of the above attribute, use the following syntax:

sql%attribute_name

Above, set any attribute name under “attribute_name”.

LET us consider the following table for our example:

<DEPTBUDGET> +-----------+-----------------+---------------+------------------+ | DEPTID | DEPTNAME  | DEPTLOC | BUDGET     | +----------+------------------+---------------+------------------+ |  1 | Finance          | NORTH | 56678      | |  2 | MARKETING     | EAST |      87687 | |  3 | Operations   | WEST |      95979 | |  4 | Technical      | SOUTH |    76878 | |  5 | Accounting   | NORTHWEST| 86767      | +----------+------------------+------------------+--------------+

Now, we will update the budget of all the departments and then check what all rows got affected using the implicit cursor attribute. With that we will use other attributes as well:

DECLARE     rows_count number(2); BEGIN   UPDATE deptbudget   SET budget = budget + 3000;   IF sql%notfound THEN      dbms_output.put_line('Nothing selected!');   ELSIF sql%found THEN      rows_count := sql%rowcount;      dbms_output.put_line( rows_count || ' rows affected! ');   END IF;   END; /  

The output:

5 rows affected!

Since we updated the budget for all the departments above, therefore our table rows would look like this:

<DEPTBUDGET> +-----------+-----------------+---------------+------------------+ | DEPTID | DEPTNAME  | DEPTLOC | BUDGET| +----------+------------------+---------------+------------------+ |  1 | Finance          | NORTH | 59678      | |  2 | Marketing     | EAST |      90687 | |  3 | Operations   | WEST |      98979 | |  4 | Technical      | SOUTH |    79878 | |  5 | Accounting   | NORTHWEST| 89767      | +----------+------------------+------------------+--------------+
18.

How to create own exceptions in PL/SQL

Answer»

The LARGE OBJECT Data Types are pointers to large objects that are stored separately from other data items, like text, graphic images, video clips, etc. The following are the data types:

  • BFILE: Store large binary objects in operating system files OUTSIDE the DATABASE. The size is system-dependent and exceed 4 GB.
  • BLOB: Store large binary objects in the database. The size is 8 to 128 TB.
  • CLOB: Store large blocks of character data in the database. The size is 8 to 128 TB.
  • NCLOB: Store large blocks of NCHAR data in the database. The size is 8 to 128 TB.
19.

How to refer to the objects and subprograms declared within a package?

Answer»

Like other programming languages, PL/SQL ALSO allow users to create own exceptions. Use the RAISE statement or the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR to declare and raise the user-defined exception explicitly.

To create own exception, firstly consider the following table <DEPTBUDGET>:

<DEPTBUDGET> +-----------+-----------------+---------------+------------------+ | DEPTID | DEPTNAME  | DEPTLOC | BUDGET| +----------+------------------+---------------+------------------+ |  1 | FINANCE          | NORTH | 56678      | |  2 | Marketing     | EAST |      87687 | |  3 | Operations   | WEST |      98979 | |  4 | Technical      | SOUTH |    76878 | |  5 | Accounting   | NORTHWEST| 86767      | +----------+------------------+------------------+--------------+

Let’s say we created the following procedure and a user-defined exception in it:

DECLARE   d_id deptbudget.id%type := &dd_id;   d_name deptbudget.deptname%type;   d_loc deptbudget.deptloc%type;     my_exception  EXCEPTION; BEGIN   IF d_id <= 0 THEN      RAISE my_exception;   ELSE      SELECT  deptname, deptloc INTO d_name, d_loc      FROM deptbudget      WHERE deptid = d_id;      DBMS_OUTPUT.PUT_LINE ('Name: '||  d_name);      DBMS_OUTPUT.PUT_LINE ('Address: ' || d_loc);   END IF; EXCEPTION   WHEN my_exception THEN      dbms_output.put_line('ID is always greater than zero!');   WHEN no_data_found THEN      dbms_output.put_line('No such department in the company!');   WHEN others THEN      dbms_output.put_line('Error!');   END; /

On executing the above procedure, the following output is VISIBLE. Let’s say our input is department id as “-2”, yes, a negative number. When execution, it raises the following user-defined error:

ID is always greater than zero!
20.

How to pass record as a subprogram parameter in PL/SQL?

Answer»

Within a PACKAGE, you can refer the OBJECTS and SUBPROGRAMS LIKE this:

  • name_of_package.object_name
  • name_of_package.subprogram_name
21.

What does each PL/SQL subprogram consist of?

Answer»

With PL/SQL, you can easily pass a record as a subprogram parameter in the same way pass any other variable.

The following is an example:

DECLARE TYPE LAPTOP IS RECORD (brand varchar(50),   RAM  number,   SNO  number ); lp1 laptop; lp2 laptop; lp3 laptop; PROCEDURE myDevice(lpt laptop) IS BEGIN  -- Laptop record   dbms_output.put_line('Laptop Brand = '|| lpt.brand);   dbms_output.put_line('Laptop RAM = '|| lpt.RAM);   dbms_output.put_line('Laptop SNO = ' || lpt.SNO); END; BEGIN   -- Laptop 1 SPECIFICATION   lp1.brand:= 'Dell';   lp1.RAM:= 4;     lp1.SNO:=  87667;   -- Laptop 2 specification   lp2.brand:= 'Lenevo';   lp2.RAM:= 4;     lp2.SNO:=  47656;   -- Laptop 3 specification   lp3.brand:= 'HP';   lp3.RAM:= 8;     lp3.SNO:=  98989;   myDevice(lp1);   myDevice(lp2);   myDevice(lp3); END; /

The output:

Laptop Brand = Dell Laptop RAM = 4 Laptop SNO = 87667 Laptop Brand = Lenevo Laptop RAM = 4 Laptop SNO = 47656 Laptop Brand = HP Laptop RAM = 8 Laptop SNO = 98989
22.

Why do we use the optional argument [OR REPLACE] in a CREATE TRIGGER command?

Answer»

Each subprogram in PL/SQL has a name and a list of parameters. With that, it is having the following parts:

  • Declaration
  • Executable
  • Exception Handling

Let us now see them one by one:

  • Declaration

It contains declarations of cursors, constants, variables, exceptions, etc.

  • Executable

Had STATEMENTS that perform actions.

  • Exception Handling

The code that handles run-time errors.

The following is the syntax to create a subprogram (procedure):

CREATE [OR REPLACE] PROCEDURE name_of_procedure [(parameter_name [IN | OUT | IN OUT] type [, ...])] {IS | AS} BEGIN  &LT; procedure_body &GT; END name_of_procedure;

Here,

  • CREATE [OR REPLACE] means a new procedure is created or MODIFIES the existing one.
  • name_of_procedure is the procedure name.
  • procedure_body is the executable part.
23.

Why INVALID_NUMBER exception raised in PL/SQL?

Answer»

The EXISTING trigger is recreated by the optional ARGUMENT [OR REPLACE] in a CREATE TRIGGER command.

24.

Why HEXTORAW introduced in PL/SQL?

Answer»

The INVALID_NUMBER EXCEPTION is raised when the conversion of a CHARACTER STRING into a number fails because the string does not represent a VALID number.

25.

Why to use NOT INSTANTIABLE clause in PL/SQL?

Answer»

The HEXTORAW in PL/SQL introduced to convert a hexadecimal VALUE into a raw value. An EXAMPLE here DISPLAYS the same:

HEXTORAW('7E')

The output:

7E
26.

What are the schema objects that groups logically related PL/SQL types and variables using PL/SQL?

Answer»

With NOT INSTANTIABLE clause in PL/SQL, you can declare an abstract object. To WORK with it, you need to CREATE a SUBTYPE of such objects to USE its functionalities.

27.

Block Structure in PL/SQL

Answer»

In PL/SQL, packages are the schema objects that groups logically RELATED PL/SQL types and variables. A Package has the following TWO parts:

  • Package Specification

The specification has the information about the package content. It declares the types, variables, constant, cursors, etc. It excludes the code for subprograms. The objects in the specification are the public object, however, a subprogram not part of the specification is a private object.

  • Package Body

The Package Body has the implementation of subprogram declared in the specification. To create Package Body, use the CREATE PACKAGE BODY statement.

The following is our sample table:

<DEPTBUDGET> +-----------+-----------------+---------------+------------------+ | DEPTID | DEPTNAME  | DEPTLOC | BUDGET| +----------+------------------+---------------+------------------+ |  1 | Finance          | NORTH | 56678      | |  2 | MARKETING     | EAST |      87687 | |  3 | Operations   | WEST |      98979 | |  4 | Technical      | SOUTH |    76878 | |  5 | Accounting   | NORTHWEST| 86767      | +----------+------------------+------------------+--------------+

The following is an example wherein we have a package “dept_pck”:

CREATE OR REPLACE PACKAGE BODY dept_pck AS     PROCEDURE get_budget(d_id deptbudget.id%TYPE) IS   d_budget deptbudget.budget%TYPE;   BEGIN      SELECT budget INTO d_budget      FROM deptbudget      WHERE id = d_id;      dbms_output.put_line('Department Budget: '|| d_budget);   END get_budget; END dept_pck; /

On executing the above code, the following is VISIBLE:

Package body created.

Now, to access the package variable, procedures, ett, you can use the dot operator as shown below:

package_name.element_name;

Continuing our example:

DECLARE   myid deptbudget.id%type := &dd_id; BEGIN   dept_pck. get_budget (myid); END; /

When you will run the above code, you need to input the department id. Let’s say your input is department id 3, the output would be:

Department Budget: 98979
28.

How to close a CURSOR in PL/SQL?

Answer»

PL/SQL Block Structures and it executes as a whole block.

The block structure can be understood with the concept of subprograms in PL/SQL. A block structure has the following PARTS:

  • Declarative

It contains declarations of cursors, CONSTANTS, VARIABLES, exceptions, etc. Variables are declared here.

  • Executable

Had statements that perform actions. It must have atleast one statement.

  • Exception Handling

The code that handles run-time errors. It use EXCEPTION keyword. 

The following is the syntax to create a subprogram (procedure):

CREATE [OR REPLACE] PROCEDURE name_of_procedure [(parameter_name [IN | OUT | IN OUT] type [, ...])] {IS | AS} BEGIN  < procedure_body > END name_of_procedure;

Here,

  • CREATE [OR REPLACE] MEANS a new procedure is created or modifies the EXISTING one.
  • name_of_procedure is the procedure name.
  • procedure_body is the executable part.

Here is an example of a subprogram (procedure):

CREATE OR REPLACE PROCEDURE one AS BEGIN   dbms_output.put_line('Welcome!'); END; /

The output displays the procedure created successfully:

Procedure created.
29.

How to trim characters in PL/SQL

Answer»

When a CURSOR is closed, then the allocate memory is released.  To close a cursor, you need to use the CLOSE CLAUSE with the name of cursor you want to close.

CLOSE name_of_cursor;

Let us first see how to create a cursor, open and fetch the cursor. After that we will close it. This is all part of Explicit cursors since they are custom defined i.e. PROGRAMMER defined cursors.

The following is the syntax to create explicit cursor:

CURSOR name_of_cursor IS select_statement;

Here,
“name_of_cursor” is the cursor name

As you can see above, an explicit cursor is created on a SELECT statement. Let us now see how to work with Explicit Cursors,

Let us declare a cursor and set a cursor name with the SELECT statement:

CURSOR d_deptbudget IS   SELECT deptid, DEPTNAME, deptloc, budget FROM deptbudget;

Above, “d_deptbudget” is our cursor.

The memory gets allocated for the cursor when it is opened in PL/SQL. Opening the cursor allocates the memory for the cursor and makes it ready for FETCHING the rows returned by the SQL statement into it

OPEN d_deptbudget;

Access one row at a time when a cursor is fetched in PL/SQL.

The following is when you fetch a cursor which is already opened:

FETCH d_deptbudget INTO d_deptid, d_deptname, d_deptloc, d_budget;

When a cursor is closed, then the allocate memory is released. To close the above created cursor:

CLOSE d_deptbudget;

Let us now see an example:

DECLARE     d_deptid deptbudget.deptid%type;     d_deptname deptbudget.deptname%type;       CURSOR d_deptbudget IS        SELECT deptid, deptname FROM deptbudget; BEGIN     OPEN d_deptbudget;     LOOP        FETCH d_deptbudget into d_deptid, d_deptname;        EXIT WHEN d_deptbudget%notfound;        dbms_output.put_line(d_deptid || ' ' || d_deptname);     END LOOP;     CLOSE d_deptbudget;   END;   /  

The output display department id and name:

1 Finance 2 Marketing 3 Operations 4 Technical 5 Accounting
30.

How to use LIKE operator in PL/SQL?

Answer»

The FOLLOWING are the methods AVAILABLE in PL/SQL to TRIM characters:

MethodDescription
LTRIM(x [, trim_string]);Trims characters from the left of x.
RTRIM(x [, trim_string]);Trims characters from the RIGHT of x.
TRIM([trim_char FROM) x);Trims characters from the left and right of x.

The following is how you can use LTRIM() in PL/SQL to trim characters from the left:

DECLARE   cars VARCHAR2(30) := '......Bentley.....'; BEGIN  dbms_output.put_line(LTRIM(cars,'.')); END; /

The output:

Bentley.....

The following is how you can use RTRIM() in PL/SQL to trim characters from the right:

DECLARE   cars varchar2(30) := '......Bentley.....'; BEGIN  dbms_output.put_line(RTRIM(cars,'.')); END; /

The output:

......Bentley

The following is how you can use TRIM() in PL/SQL to trim characters from the right and left:

DECLARE   cars varchar2(30) := '......Bentley.....'; BEGIN  dbms_output.put_line(TRIM(cars,'.')); END; /

The output:

Bentley
31.

What are Transactions in PL/SQL?

Answer»

The LIKE operator is a comparison operator in PL/SQL through which compares a character, string, or CLOB value to a pattern. The operator RETURNS TRUE if the value matches the pattern and FALSE if it does not.

For an example, we will take a procedure here and check for values:

DECLARE PROCEDURE compare (myvalue  varchar2, pattern varchar2 ) is BEGIN   IF myvalue LIKE pattern THEN      dbms_output.put_line ('True');   ELSE      dbms_output.put_line ('False');   END IF; END;   BEGIN   compare('John', 'J%n');   compare('Jack', 'Ja_k');   compare('Amit', 'Am%');   compare('Sac', 'Sac_'); END; /

The OUTPUT displays the following:

True True True False Statement processed. 0.00 seconds

Above we have used the following wildcards:

%
It allows to MATCH any string of any length
_
It allows to match only a single character

For example, above we used J%n for “John”, the output was true, since the % wildcard matches any string of any length.

32.

How to fetch a cursor in PL/SQL?

Answer»

A transaction in PL/SQL is an ATOMIC unit that may consist of one or more related SQL statements.

There is a difference between an executed SQL statement and a committed transaction. On successful execution of SQL statement, if transaction CONTAINING the statement is not committed, then it can be rolled back and the changes made by the statement can be undone. Here, committed means permanent in the database. However, rolled back means the changes can be undone.

Beginning with transactions, let us understand its concepts:

  • COMMIT

The COMMIT statement saves all the changes SINCE the last COMMIT or ROLLBACK. An explicit or implicit request is made to commit a transaction.

  • ROLLBACK

The Rollback undone all the changes since the last COMMIT or ROLLBACK.

  • ROLLBACK TO SAVEPOINT

Undone all the changes made since the specified savepoint was made.

  • SAVEPOINT

The SAVEPOINT statement forms a savepoint. This allows in performing partial ROLLBACKs. A transaction begins when the first SQL statement is encountered after connecting to the database.

To commit a transaction in PL/SQL, use the COMMIT command:

COMMIT;

Let’s say the following is the INSERT in the table. At the end, execute the COMMIT command if you want to commit the transaction:

INSERT INTO DEPTBUDGET (DEPTID,DEPTNAME,DEPTLOC) VALUES (1, 'Finance', 'NORTH'); INSERT INTO DEPTBUDGET (DEPTID,DEPTNAME,DEPTLOC) VALUES (2, 'Marketing', 'EAST'); INSERT INTO DEPTBUDGET (DEPTID,DEPTNAME,DEPTLOC) VALUES (3, 'Operations', 'WEST'); COMMIT;

To rollback the transactions, use the ROOLBACK command. The changes you made to the database without COMMIT can be undone with ROLLBACK.

The syntax:

ROLLBACK [TO SAVEPOINT < name_of_savepoint>];

Here, name_of_savepoint is the name of the savepoint.

If savepoint is not used, then simply use the “ROLLBACK” statement to rollback all the changes.

Savepoints splits a LONG transaction into smaller UNITS. This is simply done using checkpoints. These checkpoints allow you to roll back to a checkpoint in a long transaction using the following command:

SAVEPOINT name_of_savepoint;

Let us see an example of SAVEPOINT:

INSERT INTO DEPTBUDGET (DEPTID,DEPTNAME,DEPTLOC, BUDGET) VALUES (1, 'Finance', 'NORTH', 20000); INSERT INTO DEPTBUDGET (DEPTID,DEPTNAME,DEPTLOC, BUDGET) VALUES (2, 'Marketing', 'EAST', 30000); SAVEPOINT s1; UPDATE DEPTBUDGET SET BUDGET = BUDGET - 4500; ROLLBACK TO s1; UPDATE DEPTBUDGET SET BUDGET = BUDGET - 4500;   WHERE DEPTNAME = 'MARKETING'; COMMIT;

Above, we have created a SAVEPOINT s1, which will allow us to rollback.

33.

How to create triggers in PL/SQL?

Answer»

ACCESS one row at a time when a cursor is fetched in PL/SQL.

The following is when you FETCH a cursor which is already opened. Here, d_deptbudget is the cursor name:

FETCH d_deptbudget INTO d_deptid, d_deptname, d_deptloc, d_budget;

Let us first see how to create a cursor, open and fetch the cursor. After that we will close it. This is all part of Explicit cursors since they are custom defined i.e. programmer defined cursors.

The following is the syntax to create explicit cursor:

CURSOR name_of_cursor IS select_statement;

Here,
“name_of_cursor” is the cursor name

As you can see above, an explicit cursor is created on a SELECT statement. Let us now see how to work with Explicit Cursors,

Let us declare a cursor and set a cursor name with the SELECT statement:

CURSOR d_deptbudget IS   SELECT deptid, DEPTNAME, deptloc, budget FROM deptbudget;

Above, “d_deptbudget” is our cursor.

The memory gets allocated for the cursor when it is opened in PL/SQL. Opening the cursor allocates the memory for the cursor and makes it ready for fetching the rows returned by the SQL statement into it

OPEN d_deptbudget;

Access one row at a time when a cursor is fetched in PL/SQL.

The following is when you fetch a cursor which is already opened:

FETCH d_deptbudget INTO d_deptid, d_deptname, d_deptloc, d_budget;

When a cursor is closed, then the allocate memory is released. To close the above created cursor:

CLOSE d_deptbudget;

Let us now see an example:

DECLARE     d_deptid deptbudget.deptid%type;     d_deptname deptbudget.deptname%type;       CURSOR d_deptbudget IS        SELECT deptid, deptname FROM deptbudget; BEGIN     OPEN d_deptbudget;     LOOP        FETCH d_deptbudget into d_deptid, d_deptname;        EXIT WHEN d_deptbudget%notfound;        dbms_output.put_line(d_deptid || ' ' || d_deptname);     END LOOP;     CLOSE d_deptbudget;   END;   /  

The output display department id and name:

1 Finance 2 Marketing 3 Operations 4 Technical 5 ACCOUNTING
34.

How to declare a constant in PL/SQL?

Answer»

Triggers are stored in a DATABASE and fired when some event occurs. The event here can be a Database Manipulation statement i.e. DELETE, INSERT, or UPDATE, or a Database Definition statement (CREATE, ALTER, or DROP). It can even be a database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).

Syntax

The CREATE TRIGGER statement is used in PL/SQL to create a trigger. The syntax:

CREATE [OR REPLACE ] TRIGGER name_of_trigger   {BEFORE | AFTER | INSTEAD OF }   {INSERT [OR] | UPDATE [OR] | DELETE}   [OF col_name]   ON table_name   [REFERENCING OLD AS o NEW AS n]   [FOR EACH ROW]   WHEN (condition)    DECLARE   Declaration-statements BEGIN     Executable-statements EXCEPTION   Exception-handling-statements END;

Here,

  • CREATE [OR REPLACE] TRIGGER name_of_trigger – The statement creates or replaces existing trigger with the name_of_trigger.
  • {BEFORE | AFTER | INSTEAD OF} – The BEFORE or AFTER specifies when the trigger will get executed. The INSTEAD OF is for creating trigger on a view.
  • {INSERT [OR] | UPDATE [OR] | DELETE} – These clauses specify the DML operation.
  • [OF col_name] − The column name that will be updated.
  • [ON table_name] – The name of the table associated with the trigger.
  • [REFERENCING OLD AS o NEW AS n] − Refer new and old values for various DML statements.
  • [FOR EACH ROW] − A row-level trigger, i.e. the trigger will be executed for each row being affected.
  • WHEN (condition) − A condition for rows for which the trigger would fire.

Let us now take an example wherein we will create a trigger, trigger it, and even delete it.

For that, we are considering the FOLLOWING table <DEPTBUDGET>:

<DEPTBUDGET> +-----------+-----------------+---------------+------------------+ | DEPTID | DEPTNAME  | DEPTLOC | BUDGET| +----------+------------------+---------------+------------------+ |  1 | Finance          | NORTH | 56678      | |  2 | Marketing     | EAST |      87687 | |  3 | Operations   | WEST |      98979 | |  4 | Technical      | SOUTH |    76878 | |  5 | Accounting   | NORTHWEST| 86767      | +----------+------------------+------------------+--------------+

Create Trigger

Now we will create a row-level trigger that gets fired for INSERT or UPDATE or DELETE operations performed on the table. This is created to display the budget differences between new and old assigned BUDGETS:

CREATE OR REPLACE TRIGGER budget_diff BEFORE DELETE OR INSERT OR UPDATE ON deptbudget FOR EACH ROW WHEN (NEW.ID > 0) DECLARE   budget_diff number; BEGIN   budget_diff := :NEW.budget  - :OLD.budget;   dbms_output.put_line('Old Budget Assigned =' || :OLD.budget);   dbms_output.put_line('New Budget Assigned = ' || :NEW.budget);   dbms_output.put_line('Differences in Budget = ' || budget); END; /

The above trigger it will fire before any DELETE or INSERT or UPDATE operation on the table, since we added the following above:

BEFORE DELETE OR INSERT OR UPDATE ON deptbudget

We will now perform a DML operation on the DEPTBUDGET table i.e. the UPDATE statement.

The statement would update an existing record in the table:

UPDATE budget SET  = budget + 4500 WHERE id = 4;

We updated the record in the DEPTBUDGET table. When we will fire the “budget_diff”, it displays the following:

Old Budget Assigned = 76878 New Budget Assigned = 81378 Differences in Budget = 4500
35.

Why the EXIT statement used in PL/SQL?

Answer»

Once a value is DECLARED in PL/SQL, you cannot change it. The CONSTANT keyword is used in PL/SQL to DECLARE a constant.

The following is a query to FIND the area of circle, wherein we have SET the constant pi as:

pi constant number := 3.141592654;

Above, we have declared a constant.

Let us see the COMPLETE code:

DECLARE   pi constant number := 3.141592654;   radius number(5,2);     d number(5,2);     area number (10, 2); BEGIN     radius := 3;     d:= radius * 2;     area := pi * radius * radius;   dbms_output.put_line('Radius = ' || radius);   dbms_output.put_line('Diameter = ' || d);   dbms_output.put_line('Area = ' || area); END; /

The output displays the area of circle:

Radius = 3 Diameter = 6 Area = 28.27 Statement processed. 0.01 seconds
36.

Name some predefined exceptions in PL/SQL?

Answer»

The EXIT statement is used to immediately terminate a loop. With this, the program control resumes at the next statement FOLLOWING the loop. It can also be used in a NESTED loop to stop the execution of the INNERMOST loop.

When the EXIT statement is encountered inside a loop, the loop is immediately TERMINATED and the program control resumes at the next statement following the loop.

The following is the syntax:

EXIT;

The example code:

DECLARE   val number(2) := 2; BEGIN   WHILE val < 10 LOOP      dbms_output.put_line ('value = ' || val);      val := val + 1;      IF val = 5 THEN         EXIT;      END IF;   END LOOP; END; /

The output:

value = 2 value = 3 value = 4
37.

Does a stored procedure return a value in PL/SQL?

Answer»

Here are some of the PREDEFINED EXCEPTIONS in PL/SQL:

  1. PROGRAM_ERROR
  2. TIMEOUT _ON_RESOURCE
  3. INVALID_CURSOR
  4. LOGON_DENIED
  5. ZERO_DIVIDE
  6. STORAGE_ERROR
  7. NO_DATA_FOUND
  8. TOO_MANY_ROWS
  9. CURSOR_ALREADY_OPEN
  10. INVALID_NUMBER
38.

What is the use of the access operator in PL/SQL?

Answer»

No, STORED PROCEDURE in PL/SQL does not return a value. Stored Procedure CALL USING CALL keyword.

39.

What does the DBMS_TRACE package consist of?

Answer»

The access operator (.) is used in PL/SQL to access the attributes and METHODS of the OBJECT USING the instance name and the (.). The EXAMPLE shows the usage:

40.

What are SIMPLE_INTEGER, SIMPLE_FLOAT, and SIMPLE_DOUBLE Data Types in PL/SQL?

Answer»

The DBMS_TRACE package has the INTERFACE to trace PL/SQL FUNCTIONS, procedures, and exceptions. The package provides subprograms to start and STOP PL/SQL TRACING in a session.

The FOLLOWING are the constants of the DBMS_TRACE package:

  • TRACE_ALL_CALLS: Traces calls or returns
  • TRACE_ALL_EXCEPTIONS: Traces exceptions
  • TRACE_ENABLED_EXCEPTIONS: Traces exceptions and handlers
  • TRACE_LIMIT: Save only the last few records.
  • TRACE_ALL_SQL: Traces SQL statements
  • TRACE_ENABLED_SQL: Traces SQL statements at PL/SQL level.
  • TRACE_ALL_LINES: Traces each line
  • TRACE_PAUSE: Pauses trancing
  • TRACE_RESUME: Resume tracing
  • TRACE_STOP: Stops tracing
41.

How to execute a standalone procedure in PL/SQL?

Answer»

The SIMPLE_INTEGER, SIMPLE_FLOAT, and SIMPLE_DOUBLE Data TYPES introduced in PL/SQL 11g Release 1. These are predefined subtypes of PLS_INTEGER, BINARY_FLOAT, and BINARY_DOUBLE, respectively.

The SIMPLE_FLOAT and SIMPLE_DOUBLE DATATYPES are alike their base types, except for their NOT NULL constraint.

  • SIMPLE_INTEGER:  When the value will never be NULL and overflow checking is unnecessary.
  • SIMPLE_FLOAT: When the value will never be NULL.
  • SIMPLE_DOUBLE: When the value will never be NULL.

The SIMPLE_FLOAT and SIMPLE_DOUBLE has BETTER performance than BINARY_FLOAT and BINARY_DOUBLE.

SIMPLE_INTEGER is a predefined subtype of the PLS_INTEGER data type and differs from it in its overflow semantics. It has the same range as PLS_INTEGER i.e. -2,147,483,648 through 2,147,483,647) and has a NOT NULL constraint.

42.

Why do we use RPAD function in PL/SQL?

Answer»

A subprogram in PL/SQl is a standalone subprogram at the schema level. The CREATE PROCEDURE or the CREATE FUNCTION statement is used in PL/SQL to create a standalone procedure.

  • If you want to execute a standalone procedure, then use the EXECUTE keyword.
  • If you want to delete a standalone procedure in PL/SQL, then you need to use the DROP PROCEDURE or DROP FUNCTION statement.

The FOLLOWING is the syntax to create a procedure:

CREATE [OR REPLACE] PROCEDURE name_of_procedure [(parameter_name [IN | OUT | IN OUT] TYPE [, ...])] {AS} BEGIN  < procedure_body > END name_of_procedure;

Here,

  • CREATE [OR REPLACE] means a new procedure is created or modifies the existing one.
  • name_of_procedure is the procedure name.
  • procedure_body is the EXECUTABLE part.

Here is an example of a procedure:

CREATE OR REPLACE PROCEDURE one AS BEGIN   dbms_output.put_line('Chalk and Duster!!'); END; /

The output displays the procedure created successfully:

  • Procedure created.
  • Now to execute the procedure created above, you need to use the EXECUTE keyword. The name of the above procedure is “one”.
  • To call it:
EXECUTE one;

The above call will give the following output:

Chalk and Duster!
43.

What is NCHR in PL/SQL?

Answer»

The RPAD function is USED to pad the right SIDE of a string with CHARACTERS. An example here pads the string:

RPAD(JACK, 3)

The OUTPUT is:

jac
44.

How to return the ASCII value of a character in PL/SQL?

Answer»

NCHR is a function in PL/SQL that RETURNS the character BASED on the SPECIFIED number, which is an ASCII value. An EXAMPLE:

NCHR(77)

It displays the associated character:

M
45.

Recursive Functions in PL/SQL

Answer»

To RETURN the ASCII value of a character, you need to USE the ASCII() method. It RETURNS a numeric value, which is the ASCII value.

The following is the syntax:

ASCII(myCharacter)

Here, myCharacter is the character you need to MENTION to get the ASCICC value.

The following is an example:

DECLARE   a varchar(1) := 'B'; BEGIN   dbms_output.put_line(ASCII(a)); END; /

The output:

66
46.

What all packages are available for PL SQL developers?

Answer»

Recursion works the same way as we saw in programming languages like C, C++, JAVA, C#, etc.

A program or subprogram calling itself is called a recursive call and the process is recursion.

Let us see an example wherein we are displaying the usage of Recursive call:

DECLARE   N number;   factorial number;   FUNCTION fact(a number) RETURN number   IS   f number; BEGIN   IF a=0 THEN      f := 1;   ELSE      f := a * fact(a-1);   END IF; RETURN f; END;   BEGIN   n:= 3;   factorial := fact(n);   dbms_output.put_line('Value of Factorial '|| n || ' is ' || factorial); END; /

The output:

Value of Factorial 3 is 6
47.

What is a Subtype in PL/SQL?

Answer»

The following are some of the Oracle Database PL/SQL packages:

  • DBMS_ALERT

You can use the database triggers to alert an APPLICATION when a database values change.

  • DBMS_OUTPUT

You may have USED PUL_LINE in this package to display output from PL/SQL blocks, subprograms, packages, and triggers. This also displays debugging information.

  • DBMS_PIPE Package

This package lets different sessions to communicate over NAMED pipes

  • HTF and HTP Packages

This allows the PL/SQL programs to generate HTML tags.

  • UTL_SMTP

Using this package, you can send emails over SMTP (Simple Mail Transfer Protocol).

48.

What is the default value PL/SQL assigns to a variable when it is declared?

Answer»

PL/SQL has subtypes of datatypes. This MEANS subtype is a subset of a datatype. The FOLLOWING are the types and subtypes of Numeric data TYPE in PL/SQL

  • PLS_INTEGER

Signed INTEGER in range -2,147,483,648 through 2,147,483,647, represented in 32 bits

  • BINARY_INTEGER

Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits

  • BINARY_FLOAT

Single-precision IEEE 754-format floating-point number

  • BINARY_DOUBLE

Double-precision IEEE 754-format floating-point number

  • DEC(prec, scale)

ANSI specific fixed-point type with maximum precision of 38 decimal digits

  • DECIMAL(prec, scale)

IBM specific fixed-point type with maximum precision of 38 decimal digits

  • NUMERIC(pre, secale)

Floating type with maximum precision of 38 decimal digits

  • DOUBLE PRECISION

ANSI specific floating-point type with maximum precision of 126 binary digits (APPROXIMATELY 38 decimal digits)

  • SMALLINT

ANSI and IBM specific integer type with maximum precision of 38 decimal digits

  • REAL

Floating-point type with maximum precision of 63 binary digits (approximately 18 decimal digits)

49.

What is a subprogram in PL/SQL

Answer»

The default VALUE is NULL. PL/SQL assigns NULL as the default value of a variable. To assign another value, you can use the DEFAULT keyword or the assignment operator. Let us see them one by one.Initialization with DEFAULT keyword:

DECLARE   msg varchar2(15) DEFAULT 'House'; BEGIN   dbms_output.put_line(msg); END; /

The OUTPUT:

House

Initialization with assignment operator:

DECLARE   device varchar2(11) := 'Laptop'; BEGIN   dbms_output.put_line(device); END; /

The output:

Laptop
50.

What does a basic loop do in PL/SQL?

Answer»

A subprogram in PL/SQL is EITHER a procedure or a function that can be invoked repeatedly. Each subprogram has a name and a LIST of parameters. It performs a specific task and the following two subprograms EXIST in PL/SQL:

  • Functions: RETURN a single value.
  • Procedures: Do not return a value directly.

The following are the parts of a subprogram:

  • Declarative

It contains declarations of cursors, constants, variables, exceptions, etc.

  • Executable

Had statements that perform actions.

  • Exception Handling

The code that handles run-time errors.

The following is the syntax to create a subprogram (procedure):

CREATE [OR REPLACE] PROCEDURE name_of_procedure [(parameter_name [IN | OUT | IN OUT] type [, ...])] {IS | AS} BEGIN  < procedure_body > END name_of_procedure;

Here,

  • CREATE [OR REPLACE] means a new procedure is created or modifies the EXISTING one.
  • name_of_procedure is the procedure name.
  • procedure_body is the executable part.

Here is an example of a subprogram (procedure):

CREATE OR REPLACE PROCEDURE one AS BEGIN   dbms_output.put_line('Welcome!'); END; /

The output displays the procedure created successfully:

Procedure created.