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.

51.

What is DBMS_OUTPUT package in PL/SQL

Answer»

At each iteration in a BASIC loop in PL/SQL, sequence of statements is executed. After the execution, the control resumes at the top of the loop. The EXIT STATEMENT is a must in the execution part to exit from the loop. The keyword LOOP begins the execution. It ENDS with the keyword END LOOP.

The following is an example:

DECLARE   a number := 2; BEGIN   LOOP      dbms_output.put_line(a);      a := a + 2;      IF a > 10 THEN         exit;      END IF;   END LOOP;   dbms_output.put_line('After exit, the value of a = ' || a); END; /

The output:

2 4 6 8 10 After exit, the value of a = 12
52.

What is the %FOUND and %NOTFOUND cursor attributes in PL/SQL?

Answer»

To display output, PL/SQL has an in-built package known as DBMS_OUTPUT. With this package, we can also display debugging information.

The following is an example:

DECLARE    one varchar2(20) := 'Website';    two varchar2(20) := ' World!'; BEGIN    dbms_output.put_line(one || two); END; /

The output:

Website World!

Let us see the subprograms of DBMS_OUTPUT:

  • DBMS_OUTPUT.DISABLE; 

Disables message output.

  • DBMS_OUTPUT.ENABLE(buffer_size IN INTEGER DEFAULT 20000);

Enables message output. A NULL value of buffer_size represents unlimited buffer size.

  • DBMS_OUTPUT.GET_LINE (LINE OUT VARCHAR2, status OUT INTEGER);

Retrieves a SINGLE line of buffered information.

  • DBMS_OUTPUT.GET_LINES (lines OUT CHARARR, numlines IN OUT INTEGER);

Retrieves an array of lines from the buffer.

  • DBMS_OUTPUT.NEW_LINE;

Puts an end-of-line marker.

  • DBMS_OUTPUT.PUT(item IN VARCHAR2);

Places a PARTIAL line in the buffer.

  • DBMS_OUTPUT.PUT_LINE(item IN VARCHAR2);

Places a line in the buffer.

53.

What are the Schema Objects created with PL/SQL?

Answer»
  • %FOUND

The %FOUND cursor attribute returns TRUE if record was fetched successfully, FALSE otherwise. Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows or a SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE.

  • %NOTFOUND

The %NOTFOUND cursor attribute returns TRUE if record was not fetched successfully, FALSE otherwise. It returns TRUE if an INSERT, UPDATE, or DELETE statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it returns FALSE.

Cursor attributes are used like this in PL/SQL:

sql%attribute_name

Above, set any attribute name under “attribute_name”. Here we are LEARNING about %FOUND and %NOTFOUND attribute names.

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      | +----------+------------------+------------------+--------------+
54.

What is a Case Statement in PL/SQL?

Answer»

The schema objects CREATED with PL/SQL is Packages, Triggers, Cursors, etc.

  • Packages

Packages are the schema objects that groups LOGICALLY related PL/SQL types and variables.

  • Triggers

Triggers are used to enforce referential integrity, auditing, or EVEN applying security authorizations. It prevents invalid transactions and gather statistics on table access.

  • Cursors

Cursors has information about processing the statement. It holds the rows (one or more) RETURNED by a SQL statement.

55.

Can we label a PL/SQL Loop?

Answer»

The CASE STATEMENT in PL/SQL selects one sequence of statements to execute. The statement USES a selector instead multiple Boolean expression.

The FOLLOWING is the syntax:

CASE selector   WHEN 'value1' THEN Statement1;   WHEN 'value2' THEN Statement2;   WHEN 'value3' THEN Statement3;   ...   ELSE Sn;  -- default case END CASE;

The following is an example:

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

The output:

Rank1... Topper
56.

The searched CASE statement has no selector in PL/SQL? Is this TRUE?

Answer»

Yes, we can label PL/SQL loops. Here are some key points about LABELS in a loop:

  • The label is enclosed by << and >> and appears at the BEGINNING of the LOOP statement.
  • The label name can also be included at the END of the LOOP statement.

Let us see an example:

DECLARE   i number(1);   j number(1); BEGIN   << outer >>   FOR i IN 1..5 LOOP      << inner >>      FOR j IN 1..2 LOOP         dbms_output.put_line('i = '|| i || ', j = ' || j);      END loop inner;   END loop outer; END; /

The output:

i = 1, j = 1 i = 1, j = 2 i = 2, j = 1 i = 2, j = 2 i = 3, j = 1 i = 3, j = 2 i = 4, j = 1 i = 4, j = 2 i = 5, j = 1 i = 5, j = 2
57.

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

Answer»

Yes, this is correct. Here, the WHEN CLAUSE is used for conditions, which are from top to bottom. The SEQUENCE of statements with the WHEN clause whose condition evaluates to TRUE is executed. Only the FIRST statement executes, if more than ONE condition evaluates to TRUE.

The following is the syntax:

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
58.

Index-By Table in PL/SQL

Answer»

The TIMESTAMP WITH TIME ZONE datatype is USED for DATE information across geographic regions.

It has a time zone region name or a time zone offset in its VALUE. TIME ZONE offset = difference in hours and minutes between LOCAL time and UTC.

59.

How to access the fields of a record in PL/SQL?

Answer»

One of the Collection types in PL/SQL is Index-By table. These are also called Associative Arrays. It gets created only in the PL/SQL block. The subscript TYPE for Associative Array is a string or integer.

Associative Array is a set of key-value pair. The key here can be an Integer or String. The following is the syntax:

TYPE type_name IS TABLE OF element_type [NOT NULL] INDEX BY subscript_type; name_of_table type_name;

Here, index-by table is the name_of_table. The keys of the subscript_type. The associated VALUES will be of the element_type i.e. NUMBER, etc.

The following is an example:

DECLARE   TYPE budget IS TABLE OF NUMBER INDEX BY VARCHAR2(15);   dept_budget budget ;   dept_name VARCHAR2(20); BEGIN   dept_budget ('Operations') := 30000;   dept_budget ('Finance') := 25000;   dept_budget ('ACCOUNTS') := 45000;     dept_name := dept_budget.FIRST;   WHILE dept_name IS NOT null LOOP      dbms_output.put_line      ('Budget - ' || dept_name || ' Department = ' || TO_CHAR(dept_budget (dept_name )));      dept_name := dept_budget .NEXT(dept_name );   END LOOP; END; /

The OUTPUT:

Budget - Accounts Department = 45000 Budget - Finance Department = 25000 Budget - Operations Department = 30000
60.

When COLLECTION_IS_NULL exception raised in PL/SQL?

Answer»

The dot(.) operator is to be used in PL/SQL to access the fields of a record. This is between the record variable and the field.

Let US take an example of a record. This is how you can DECLARE:

DECLARE TYPE laptop IS RECORD (brand varchar(50),   RAM  number,   SNO  number, ); l1 laptop; l1 laptop;

You can now access the fields using the dot(.) operator.

The following is the example WHEREIN we have created user-define records and accesses the fields:

DECLARE TYPE laptop IS RECORD (brand varchar(50),   RAM  number,   SNO  number ); lp1 laptop; lp2 laptop; lp3 laptop; 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;  -- Laptop 1 record   dbms_output.put_line('Laptop 1 Brand = '|| lp1.brand);   dbms_output.put_line('Laptop 1 RAM = '|| lp1.RAM);   dbms_output.put_line('Laptop 1 SNO = ' || lp1.SNO); -- Laptop 2 record   dbms_output.put_line('Laptop 2 Brand = '|| lp2.brand);   dbms_output.put_line('Laptop 2 RAM = '|| lp2.RAM);   dbms_output.put_line('Laptop 2 SNO = ' || lp2.SNO); -- Laptop 3 record   dbms_output.put_line('Laptop 3 Brand = '|| lp3.brand);   dbms_output.put_line('Laptop 3 RAM = '|| lp3.RAM);   dbms_output.put_line('Laptop 2 SNO = ' || lp3.SNO); END;

The output:

Laptop 1 Brand = Dell Laptop 1 RAM = 4 Laptop 1 SNO = 87667 Laptop 2 Brand = Lenevo Laptop 2 RAM = 4 Laptop 2 SNO = 47656 Laptop 3 Brand = HP Laptop 3 RAM = 8 Laptop 2 SNO = 98989
61.

What is a COMMIT statement in PL/SQL?

Answer»

The COLLECTION_IS_NULL exception is raised when a PROGRAM attempts to apply COLLECTION METHODS other than EXISTS to an uninitialized nested table or VARRAY, or the program attempts to assign values to the elements of an uninitialized nested table or varray.

62.

What is a SAVEPOINT statement in PL/SQL?

Answer»

The COMMIT STATEMENT is used to commit a transaction in PL/SQL, use the:

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.

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;
63.

What is a ROLLBACK statement in PL/SQL?

Answer»

The SAVEPOINT statement forms a savepoint. This allows in performing partial ROLLBACKs.
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.

64.

sum = sum + 10;

Answer»

The ROLLBACK undone all the changes since the last COMMIT or ROLLBACK.
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.

ROLLBACK;
65.

Is the following a correct assignment statement in PL/SQL?

Answer»

No, this is not a correct way to IMPLEMENT assignment in PL/SQL. In PL/SQL, the assignment STATEMENT is the following:

:=

Let us SEE in the example:

sum := sum +10;

The following is another example:

DECLARE   cost NUMBER := 3000; BEGIN     dbms_output.put_line(cost); END; /

The output:

3000
66.

How can we create Nested Tables in PL/SQL?

Answer»

Nested tables are one of the collection types in PL/SQL. They are created EITHER in PL/SQL block or at schema level. These are LIKE a 1D array, but its size can GET increased dynamically.

The following is the syntax:

TYPE type_name IS TABLE OF element_type [NOT NULL]; name_of_table type_name;

The following is an example:

DECLARE   TYPE deptname IS TABLE OF VARCHAR2(10);   TYPE budget IS TABLE OF INTEGER;     names deptname;   deptbudget budget; BEGIN   names := deptname ('Finance', 'Sales', 'MARKETING');   deptbudget := budget (89899, 67879, 98999);   FOR i IN 1 .. names.count LOOP      dbms_output.put_line('Department = '||names(i)||', Budget = ' || deptbudget(i));   end loop; END; /  

The output:

Department = Finance, Budget = 89899 Department = Sales, Budget = 67879 Department = Marketing, Budget = 98999
67.

Scope of Variables in PL/SQL?

Answer»

Variable Scope defines that if you DECLARE a variable within an inner bloc, it is not accessible for the outer. On the contrary, if a variable is declared in outer BLOCK, then it is accessible in the ENTIRE program whether its outer, inner, NESTED inner blocks.

The following are the scope of variables in PL/SQL:

Local variables

  • Declaration: Variables declared in an inner block
  • Accessible: Not accessible to outer blocks

Global variables

  • Declaration: Variables declared in the outermost block
  • Accessible: Accessible to outer blocks, inner block, nested inner block.

Let us now see an example to learn the role of local and global variables in scope of variables in PL/SQL:

DECLARE   -- Global variables     a number := 5;   BEGIN     dbms_output.put_line('Outer Variable a = ' || a);   DECLARE        -- Local variables      a number := 10;     BEGIN        dbms_output.put_line('Inner Variable a = ' || a);   END;   END; /

The output:

Outer Variable a = 5 Inner Variable a = 10
68.

How to handle exceptions in PL/SQL?

Answer»

Like any other language, PL/SQL also provides a functionality to handle exceptions. This is done using the EXCEPTION block. To raise exceptions explicitly, use the RAISE command.

To handle exceptions in PL/SQL, here is the syntax:

DECLARE   <declarations section&GT; BEGIN   <executable command(s)> EXCEPTION   <exception handling >   WHEN exception1 THEN        exception1-handling-statements     WHEN exception2  THEN      exception2-handling-statements     WHEN exception3 THEN        exception3-handling-statements   ........   WHEN others THEN      exception-handling-statements END;

Above, WHEN is used for exceptions like:

WHEN no_data_found THEN

With that, the following is to be used for default exception:

WHEN others THEN

Before beginning our example, LET’s say we have the following 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 our example wherein we are handling exceptions. The dept

DECLARE  d_id deptbudget.deptid%type := 20;  d_ name deptbudget.deptname%type;  d_loc deptbudget.deptloc%type;   BEGIN      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 no_data_found THEN      dbms_output.put_line('No such department in the company!');   WHEN others THEN      dbms_output.put_line('Error!');   END; /

The output:

No such department in the company
69.

Why INSTRB used in PL/SQL?

Answer»

The INSTRB is a function used in PL/SQL to RETURN the location of a string within ANOTHER string. The value is RETURNED in bytes.

An example:

INSTR('Jack SPARROW', 'c')

The above returns the OUTPUT in bytes:

3
70.

What are the valid DateTime values for seconds in PL/SQL?

Answer»

The valid values for seconds:

71.

PL/SQL handles how many types of records?

Answer»

A record is a data structure in PL/SQL to hold data items of different kinds.

For our examples on records in PL/SQL, we have the following 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      | +----------+------------------+------------------+--------------+

PL/SQL handles the following types of records:

  • Table-based records

To create table-based records, you need to use the %ROWTYPE attribute. Using the same we will fetch the records of a department with id = 3:

DECLARE   rec_dept deptbudget%rowtype; BEGIN   SELECT * into rec_dept   FROM customerdeptbudgets   WHERE deptid = 3;     dbms_output.put_line('Department ID =' || rec_dept.deptd);   dbms_output.put_line('Department Name = ' || rec_dept.deptname);   dbms_output.put_line('Department Location = ' || rec_dept.deptloc);   dbms_output.put_line('Department Budget = ' || rec_dept.budget); END; /

The output:

Department ID = 3 Department Name = Operations Department Location = WEST Department Budget = 98979 PL/SQL PROCEDURE successfully completed.
  • Cursor-based records

In PL/SQL, use the %ROWTYPE attribute with an explicit cursor or cursor variable where each field corresponds to a column in the cursor SELECT statement.

The following is an example:

DECLARE   CURSOR cur_dept is      SELECT deptid, deptname, deptloc      FROM deptbudget;   rec_dept cur_dept %rowtype; BEGIN   OPEN cur_dept ;   LOOP      FETCH cur_dept into rec_dept;      EXIT WHEN cur_dept %notfound;      DBMS_OUTPUT.put_line(rec_dept.deptid || ' ' || rec_dept.deptname || ' ' || rec_dept.deptloc);   END LOOP; END; /

The output:

1 Finance NORTH 2 Marketing EAST 3 Operations WEST 4 Technical SOUTH 5 Accounting NORTHWEST PL/SQL procedure successfully completed.
  • User-defined records

In PL/SQL, it is possible to create your own records i.e. user-defined. With that, you can set the different record structures.

Let us take an example of a Laptop’s record. Here is how you can declare:

DECLARE TYPE laptop IS RECORD (brand varchar(50),   RAM  number,   SNO  number, ); l1 laptop; l1 laptop;

You can now ACCESS the fields using the dot(.) operator.

The following is the example wherein we have created user-define records and accesses the fields:

DECLARE TYPE laptop IS RECORD (brand varchar(50),   RAM  number,   SNO  number ); lp1 laptop; lp2 laptop; lp3 laptop; 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;  -- Laptop 1 record   dbms_output.put_line('Laptop 1 Brand = '|| lp1.brand);   dbms_output.put_line('Laptop 1 RAM = '|| lp1.RAM);   dbms_output.put_line('Laptop 1 SNO = ' || lp1.SNO); -- Laptop 2 record   dbms_output.put_line('Laptop 2 Brand = '|| lp2.brand);   dbms_output.put_line('Laptop 2 RAM = '|| lp2.RAM);   dbms_output.put_line('Laptop 2 SNO = ' || lp2.SNO); -- Laptop 3 record   dbms_output.put_line('Laptop 3 Brand = '|| lp3.brand);   dbms_output.put_line('Laptop 3 RAM = '|| lp3.RAM);   dbms_output.put_line('Laptop 2 SNO = ' || lp3.SNO); END;

The output:

Laptop 1 Brand = Dell Laptop 1 RAM = 4 Laptop 1 SNO = 87667 Laptop 2 Brand = Lenevo Laptop 2 RAM = 4 Laptop 2 SNO = 47656 Laptop 3 Brand = HP Laptop 3 RAM = 8 Laptop 2 SNO = 98989
72.

How to perform concatenation in PL/SQL?

Answer»

To join two or more strings i.e. concatenation, PL/SQL COMES with concatenation operator (||). This operator returns a string value.

The following is the syntax:

str1 || str2 [ || str_n ]

Here,

  • str1 = String 1
  • str2 = String 2
  • str_n = nth string

The following is an example:

DECLARE   ONE VARCHAR2(20) := 'Website';   two varchar2(20) := ' World!'; BEGIN   dbms_output.put_line(one || two); END; /

The output:

Website World!
73.

What are the modes of parameters in PL/SQL?

Answer»

The MODES of parameters in a PL/SQL subprogram includes the following:

  • IN

The IN parameter is a read-only parameter that allows you to PASS a value to the subprogram.

It acts as a constant in the subprogram. A constant, LITERAL, initialized variable, or expression can be PASSED as an IN parameter.

  • OUT

The OUT parameter acts like a variable in a subprogram. Its value can be changed unlike the IN parameter.The value can be reference after assignment.

  • IN OUT

The actual parameter is passed by value. The initial value is passed to a subprogram. The updated value is returned to the caller.

Let us see an example:

DECLARE   val number; PROCEDURE display(n IN OUT number) IS BEGIN  n := n * n; END;   BEGIN   val:= 42;   display(val);   dbms_output.put_line('Square of 42 = ' || val); END; /

The output:

Square of 42 = 1764
74.

How to use an explicit cursor in PL/SQL?

Answer»

Explicit cursors are custom DEFINED i.e. programmer defined cursors that gives more control over the context area. Oracle FORMS a memory area, when an SQL statement is processed, which is called context area.

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,

  • Cursor Declaration

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.

  • Open the 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;
  • Fetch the Cursor

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;
  • Close the Cursor

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 to work with explicit cursors in PL/SQL:

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
75.

What are PL/SQL Delimiters?

Answer»

A delimiter is a compound symbol with a special meaning to PL/SQL. For example, you USE delimiters to represent ARITHMETIC operations such division. For example, a delimiter symbol is also the assignment OPERATOR used in PL/SQL:

:=

An example would be:

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

The following are the symbols of Delimiters:

Symbol
Meaning
+
addition operator
%
attribute indicator
'
character string delimiter
.
component selector
/
division operator
(
expression or list delimiter
)
expression or list delimiter
:
host variable indicator
,
item separator
*
multiplication operator
"
quoted identifier delimiter
=
relational operator
<
relational operator
&GT;
relational operator
@
remote access indicator
;
statement terminator
-
subtraction/negation operator
:=
assignment operator
=>
association operator
||
concatenation operator
**
exponentiation operator
<<
label delimiter (begin)
>>
label delimiter (end)
/*
multi-line COMMENT delimiter (begin)
*/
multi-line comment delimiter (end)
..
range operator
<>
relational operator
!=
relational operator
~=
relational operator
^=
relational operator
<=
relational operator
>=
relational operator
--
single-line comment indicator
76.

Usage of Timestamp Datatype in PL/SQL?

Answer»

The data type TIMESTAMP stores the year, month, DAY, hour, minute, and second. TIMESTAMP extends the data type DATE.

The FOLLOWING is the syntax:

TIMESTAMP[(precision)

Here,

Precision: The number of digits in the fractional part of the seconds field. Optional.

The following is an example:

DECLARE  mydate TIMESTAMP(2);  BEGIN    mydate := '20-Dec-2018 07:48:53.275';    DBMS_OUTPUT.PUT_LINE( TO_CHAR(mydate )); END; /

The output:

20-DEC-18 07.48.53.28 AM 

In PL/SQL, you can also find a datatype: 

TIMESTAMP WITH TIME ZONE

The above datatype includes a time-zone displacement. The time-zone displacement is the difference between LOCAL time and COORDINATED Universal Time (UTC,) formerly Greenwich Mean Time (GMT). This difference is in hours and minutes.

The following is the syntax:

TIMESTAMP[(precision)] WITH TIME ZONE

Here,

Precision: The number of digits in the fractional part of the seconds field. Optional.

Let us see an example:

DECLARE  mydate TIMESTAMP(2) WITH TIME ZONE;  BEGIN    mydate := '10-Dec-2018 11:28:55.114 AM +03:00';    DBMS_OUTPUT.PUT_LINE( TO_CHAR(mydate )); END; /

The output:

10-DEC-18 11.28.55.11 AM +03:00
77.

What are the Datetime Interval Data Types available in PL/SQL?

Answer»

The Datetime Interval DATA type stores and MANIPULATE DATES, times, and intervals.

A variable with date and time data type stores values called datetimes. A variable with interval data type stores values called intervals.

Here are the field NAMES:

YEAR

  • Valid Datetime Value: 4712 to 9999 (excluding year 0)
  • Valid Interval Value: Any non-zero integer

MONTH

  • Valid Datetime Value: 01 to 12
  • Valid Interval Value: 0 to 11

DAY 

  • Valid Datetime Value: 01 to 31
  • Valid Interval Value: Any non-zero integer

HOUR

  • Valid Datetime Value: 00 to 23
  • Valid Interval Value: 0 to 23

MINUTE

  • Valid Datetime Value: 00 to 59
  • Valid Interval Value: 0 to 59

SECOND

  • Valid Datetime Value: 00 to 59.9(n), where 9(n) is the precision of time fractional seconds
  • Valid Interval Value: 0 to 59.9(n), where 9(n) is the precision of interval fractional seconds

TIMEZONE_HOUR

  • Valid Datetime Value: -12 to 14 (range accommodates daylight savings time changes)
  • Valid Interval Value: Not Applicable

TIMEZONE_MINUTE

  • Valid Datetime Value: 00 to 59
  • Valid Interval Value: Not Applicable

TIMEZONE_REGION

  • Valid Datetime Value: Found in the dynamic performance view V$TIMEZONE_NAMES
  • Valid Interval Value: Not Applicable

TIMEZONE_ABBR

  • Valid Datetime Value: Found in the dynamic performance view V$TIMEZONE_NAMES
  • Valid Interval Value: Not Applicable
78.

How to declare and initialize Variables in PL/SQL

Answer»

PL/SQL allocates memory for the variable's value when a variable is declared. The storage location is IDENTIFIED by the variable name.

Declaration

The following is the syntax:

variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]

Here,

  • variable_name: Name of the variable
  • datatype: The datatype

Example for a string variable:

name varchar2(15);

Let us see an example for a number precision limit. This is called CONSTRAINT declaration that needs less memory:

a number(5, 2)

Initialization

To INITIALIZE a variable, you can use the DEFAULT keyword as well as 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

79.

What are the predefined numeric datatypes in C#?

Answer»

The predefined numeric datatypes are subtypes of the SCALAR Data Types.

The following are the subtypes of the numeric datatypes:

  • 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)

80.

What are Cursor-based records in PL/SQL?

Answer»

In PL/SQL, use the %ROWTYPE ATTRIBUTE with an explicit cursor or cursor variable where each field corresponds to a column in the cursor SELECT statement.

The following is an example:

DECLARE   CURSOR cur_dept is      SELECT deptid, deptname, deptloc      FROM deptbudget;   rec_dept cur_dept %rowtype; BEGIN   OPEN cur_dept ;   LOOP      FETCH cur_dept into rec_dept;      EXIT WHEN cur_dept %notfound;      DBMS_OUTPUT.put_line(rec_dept.deptid || ' ' || rec_dept.deptname || ' ' || rec_dept.deptloc);   END LOOP; END; /

The output: 

1 Finance NORTH 2 Marketing EAST 3 Operations WEST 4 Technical SOUTH 5 Accounting NORTHWEST PL/SQL PROCEDURE successfully completed.
81.

How to commit a transaction in PL/SQL?

Answer»

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

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

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.

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;
82.

What are Implicit Cursors in PL/SQL

Answer»

Implicit cursors in PL/SQL are created AUTOMATICALLY by Oracle when an SQL statement is executed. This occurs when there is no explicit cursor for the statement.

An implicit cursor is associated, when INSERT, UPDATE and DELETE is issued. The attributes include %FOUND, %ISOPEN, %NOTFOUND, etc. With the attributes, you can check which all rows got affected by the operation.

The attributes:

  • %FOUND: It returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows or a SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE.
  • %NOTFOUND: The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it returns FALSE.
  • %ISOPEN: It returns FALSE for implicit cursors, because Oracle closes the SQL cursor automatically after executing its associated SQL statement.
  • %ROWCOUNT: It 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      | +----------+------------------+------------------+--------------+
83.

How many types of Exceptions occur in PL/SQL?

Answer»

There are two types of EXCEPTIONS that exist in PL/SQL:

System Defined Exceptions

The predefined exceptions in PL/SQL are System Defined Exceptions. If a PL/SQL program violate the rule of Oracle, then an exception is raised. The exceptions are handled by name, for example, DUP_VAL_ON_INDEX exceptions are raised when an attempt is MADE to store DUPLICATE values in a database column constrained by a unique index.

Let us learn about the predefined exceptions in PL/SQL:

  • ACCESS_INTO_NULL: This exception is raised when an attempt is made to the attributes of an uninitialized object.
  • CASE_NOT_FOUND: This exception is raised when none of the choices in the WHEN clause of a CASE statement is selected and there is no ELSE clause.
  • COLLECTION_IS_NULL: This exception is raised when an attempt is made to apply collection methods other than EXISTS to an uninitialized nested table or varray.
  • DUP_VAL_ON_INDEX: This exception is raised when duplicate values are attempted to be stored in a column with unique index.
  • INVALID_CURSOR: This exception is raised when attempts are made to make a cursor operation that is not allowed, such as closing an unopened cursor.
  • INVALID_NUMBER: This exception is raised when the conversion of a character string into a number fails because the string does not represent a valid number.
  • LOGIN_DENIED: This exception is raised when a program attempts to log on to the database with an invalid username or password.
  • NO_DATA_FOUND: This exception is raised when a SELECT INTO statement returns no rows.
  • NOT_LOGGED_ON: This exception is raised when a database call is issued without being connected to the database.
  • PROGRAM_ERROR: This exception is raised when there is an internal problem.
  • ROWTYPE_MISMATCH: This exception is raised when a cursor fetches value in a variable having incompatible data type.
  • SELF_IS_NULL: This exception is raised when a member method is invoked, but the instance of the object type was not initialized.
  • STORAGE_ERROR: This exception is raised when PL/SQL ran out of memory.
  • TOO_MANY_ROWS: This exception is raised when SELECT INTO statement returns more than one row.
  • VALUE_ERROR: This exception is raised when arithmetic, conversion, or truncation error occurs.
  • ZERO_DIVIDE: This exception is raised when an attempt is made to divide a number by zero.

User-Defined Exceptions

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   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!
84.

PL/SQL provides a user-defined record type. What is that?

Answer»

In PL/SQL, it is possible to create your own RECORDS i.e. user-defined. With that, you can set the different record structures.

Let us take an example of a Laptop’s record. Here is how you can declare:

DECLARE TYPE laptop IS RECORD (brand varchar(50),   RAM  number,   SNO  number, ); l1 laptop; l1 laptop;

You can now access the fields using the dot(.) operator.
The following is the example wherein we have created user-define records and accesses the fields:

DECLARE TYPE laptop IS RECORD (brand varchar(50),   RAM  number,   SNO  number ); lp1 laptop; lp2 laptop; lp3 laptop; 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;  -- Laptop 1 record   dbms_output.put_line('Laptop 1 Brand = '|| lp1.brand);   dbms_output.put_line('Laptop 1 RAM = '|| lp1.RAM);   dbms_output.put_line('Laptop 1 SNO = ' || lp1.SNO); -- Laptop 2 record   dbms_output.put_line('Laptop 2 Brand = '|| lp2.brand);   dbms_output.put_line('Laptop 2 RAM = '|| lp2.RAM);   dbms_output.put_line('Laptop 2 SNO = ' || lp2.SNO); -- Laptop 3 record   dbms_output.put_line('Laptop 3 Brand = '|| lp3.brand);   dbms_output.put_line('Laptop 3 RAM = '|| lp3.RAM);   dbms_output.put_line('Laptop 2 SNO = ' || lp3.SNO); END;

The OUTPUT

Laptop 1 Brand = Dell Laptop 1 RAM = 4 Laptop 1 SNO = 87667 Laptop 2 Brand = Lenevo Laptop 2 RAM = 4 Laptop 2 SNO = 47656 Laptop 3 Brand = HP Laptop 3 RAM = 8 Laptop 2 SNO = 98989
85.

What are the types of Literals in PL/SQL?

Answer»

Literals are syntactic representation of NUMERIC, character, string, or BOOLEAN value. The literals in PL/SQL are case-sensitive.

The FOLLOWING are the literals in PL/SQL:

  • Numeric Literals
    Examples: 20 -20 0
  • Character Literals
    Examples: 'A', '%', '9'
  • String Literals
'Mystring!' 'Web!'
  • BOOLEAN Literals

Examples: TRUE, FALSE

  • Date and TIME Literals
DATE '2018-12-20'; TIMESTAMP '2018-12-15 11:10:30';
86.

Predefined Exceptions in PL/SQL

Answer»

If a PL/SQL program violate the rule of Oracle, then an exception is raised. The exceptions are handled by name, for example, DUP_VAL_ON_INDEX exceptions is raised when an attempt is MADE to store duplicate VALUES in a database column CONSTRAINED by a unique index.

Let us learn about the predefined exceptions in PL/SQL:

  • ACCESS_INTO_NULL

This exception is raised when an attempt is made to the attributes of an uninitialized object.

  • CASE_NOT_FOUND

This exception is raised when none of the choices in the WHEN clause of a CASE statement is selected and there is no ELSE clause.

  • COLLECTION_IS_NULL

This exception is raised when an attempt is made to apply collection methods other than EXISTS to an uninitialized nested table or varray.

  • DUP_VAL_ON_INDEX

This exception is raised when duplicate values are ATTEMPTED to be stored in a column with unique index.

  • INVALID_CURSOR

This exception is raised when attempts are made to make a cursor operation that is not allowed, such as closing an unopened cursor.

  • INVALID_NUMBER

This exception is raised when the CONVERSION of a character string into a number fails because the string does not represent a valid number.

  • LOGIN_DENIED

This exception is raised when a program attempts to log on to the database with an invalid username or password.

  • NO_DATA_FOUND

This exception is raised when a SELECT INTO statement returns no rows.

  • NOT_LOGGED_ON

This exception is raised when a database call is issued without being connected to the database.

  • PROGRAM_ERROR

This exception is raised when there is an internal problem.

  • ROWTYPE_MISMATCH

This exception is raised when a cursor fetches value in a variable having incompatible data type.

  • SELF_IS_NULL

This exception is raised when a member method is invoked, but the instance of the object type was not initialized.

  • STORAGE_ERROR

This exception is raised when PL/SQL ran out of memory.

  • TOO_MANY_ROWS

This exception is raised when SELECT INTO statement returns more than one row.

  • VALUE_ERROR

This exception is raised when arithmetic, conversion, or truncation error occurs.

  • ZERO_DIVIDE

This exception is raised when an attempt is made to divide a number by zero.

87.

What are the types of Datatypes in PL/SQL?

Answer»

The types of Datatypes are categorized as the following:

1. Scalar DATA Type

The Data Types that have SINGLE values with no internal components. Here are the predefined Scalar Data Types with the description about its data:

  • Numeric: Numeric values. It includes the following sub-types: PLS_INTEGER, BINARY_INTEGER, BINARY_FLOAT, BINARY_DOUBLE, DOUBLE PRECISION, FLOAT, INT, INTEGER, SMALLINT, REAL, etc.
  • CHARACTER: Single characters or strings of characters. It includes the following sub-types: CHAR, VARCHAR2, NCHAR, NVARCHAR2, LONG, LONG RAW, ROWID, UROWID, etc.
  • Boolean: Logical values
  • Datetime: Date and Time
  • Interval: Time Interval

2. Composite Data Type

Data items that have internal components that can be accessed individually

3. Reference Data Type

Pointers to other data items

4. Large Object Data Types (LOB)

These 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.
88.

State the advantages of 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 strongly integrated with SQL and supports both static and dynamic SQL.  

The following are the advantages of PL/SQL:

  • Static and Dynamic SQL

PL/SQL has both static and dynamic SQL. Static SQL with DML operations and transaction control from PL/SQL block. SQL allows embedding DDL statements in PL/SQL blocks in Dynamic SQL.

  • Exception Handling

PL/SQL has exception handling that helps in EASIER debugging.

  • For Programmers

PL/SQL allows faster update of database. Therefore, beneficial for programmers.

  • Faster Execution

With PL/SQL, we can easily perform faster execution of queries.

  • Block of Statements

PL/SQL executes as a whole block i.e. sends entire block of statements to the database at once.

  • Extension of SQL

Since PL/SQL is an extension of SQL, you get access to predefined SQL packages.

  • Triggers

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).

  • Optimal Efficiency

PL/SQL and SQL brings optimal efficiency since it runs within the same server process.

  • Error Management

Error Management in PL/SQL brings in internally defined, predefined, and user-define exceptions and process to handle them with error codes and messages. With that, PL/SQL also has RAISE statement for your own defined exceptions.

89.

What are Triggers in PL/SQL? When do we use them?

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).

Triggers are used to enforce referential integrity, auditing, or even applying security authorizations. It prevents invalid transactions and gather statistics on table access.

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
90.

How can we use comments in a PL/SQL code?

Answer»

A code with a comment helps the developers in reading the source code properly. Like other programming languages, in PL/SQL, you can easily add comment to the code. Compiler IGNORES the content under the comment.

The single-LINE comments under PL/SQL begin with the DELIMITER:

-- (double HYPHEN)

The multi-line comments are enclosed by:

/* and */

Let us see both the comments in the following code:

DECLARE   -- Variable declaration and initialization   car varchar2(15) := 'Bentley'; BEGIN   /*   * UPPER() method in PL/SQL   */   dbms_output.put_line(UPPER(car)); END; /

Above, we have used both the single line and multi-line comment. The output:

BENTLEY
91.

Why the EXIT WHEN statement used in PL/SQL?

Answer»

The EXIT WHEN statement has a condition under the WHEN clause. The statement acts like NULL before the condition is TRUE.

The following is the syntax:

EXIT WHEN condition;

Here is an example: 

DECLARE   val NUMBER(2) := 2; BEGIN   WHILE val < 10 LOOP      dbms_output.put_line ('VALUE = ' || val);      val := val + 1;         EXIT WHEN val = 5;   END LOOP; END; /

The output: 

Value = 2 Value = 3 Value = 4
92.

Why do we use Cursors in PL/SQL?

Answer»

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. A PL/SQL cursor holds the rows (one or more) returned by a SQL statement.

The following are the two forms of cursors:

  • Implicit Cursors (Automatic)

Implicit cursors in PL/SQL are created automatically by Oracle when an SQL statement is executed. This OCCURS when there is no explicit cursor for the statement.

An implicit cursor is associated, when INSERT, UPDATE and DELETE is issued. The attributes include %FOUND, %ISOPEN, %NOTFOUND, etc. With the attributes, you can check which all rows got affected by the operation.

The attributes:

  • %FOUND: It returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows or a SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE.
  • %NOTFOUND: The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it returns FALSE.
  • %ISOPEN: It returns FALSE for implicit cursors, because Oracle closes the SQL cursor automatically after executing its associated SQL statement.
  • %ROWCOUNT: It 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, 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      | +----------+------------------+------------------+--------------+
  • Explicit Cursors (Programmer Defined)

Explicit cursors are custom defined i.e. programmer defined cursors that gives more control over the context area. Oracle forms a memory area, when an SQL statement is processed, which is called context area.

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,

  • Cursor Declaration

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.

  • Open the 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;
  • Fetch the Cursor

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;
  • Close the Cursor

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 to work with explicit cursors in PL/SQL:

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
93.

What are the characteristics of 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 strongly integrated with SQL and supports both static and DYNAMIC SQL.

The following are the characteristics of PL/SQL:

  • PL/SQL is a procedural language that extends SQL.
  • PL/SQL has a built-in interpreted PROGRAMMING environment.
  • PL/SQL's syntax is shaped ADA and Pascal programming language.
  • It is an Extension to SQL
  • 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.
  • Provides High PERFORMANCE for Applications
  • 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).
  • Productivity to Programmers
  • 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.
  • PL/SQL also comes with the functionality of Triggers.
94.

PL/SQL vs 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.

SQL is a domain-specific language used in programming. It is a Structured Query Language for database creation, deletion, fetching rows, modifying rows, etc. relational database management system

The following are the differences:

Basis
PL/SQL
SQL
Embed
Can have SQL embedded in it.
Cannot have PL/SQL code embedded in it.
Interaction with database server
There is no interaction with the database server.
Interaction with the database server.
How/What
PL/SQL defines how it needs to be done.
Defines what needs to be done.
Writing program/functions/procedures
PL/SQL is used to write program blocks,
functions, procedures TRIGGERS, etc.
SQL is used to write queries, DDL and DML statements.
Execution
Executes as a whole block.
Issue a SINGLE query or execute a single insert/update/delete. Executes one statement at a time.
95.

PL/SQL vs T/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.

TL/SQL is Transact Structure Query language. T-SQL EXPANDS on the SQL standard to add procedural programming, local variables, etc. It is Microsoft's and Sybase's proprietary extension to the SQL.

The following are the differences:

Basis
PL/SQL
T/SQL
Efficiency
It is more POWERFUL than T/SQL.
T/SQL is less powerful than PL/SQL.
Relation with SQL
PL/SQL is an extension for SQL and Oracle. It enhances the capabilities of SQL.
T-SQL expands on the SQL standard to add procedural programming, local variables, etc.
Full Form
PL SQL is Procedural Language STRUCTURAL Query Language.
TL SQL is Transact Structure Query language.
Compatibility
PL-SQL works best with Oracle database Server.
T-SQL works best with Microsoft SQL Server
Easier/ Complex
PL/SQL is considered complex to learn than
T/SQL
It is easier to learn and work with T/SQL.
Developer
It is DEVELOPED and owned by Oracle.
T/SQL is Microsoft's and Sybase's proprietary extension to the SQL.


96.

What is 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.