logo
Product
Product Tour Science
Aptitude Tests Coding Tests Psychometric Tests Personality Tests
Campus Hiring Features Proctoring Enterprise
Test Library Questions Pricing
Resources
Blog Case studies Books Tools
About us
Login
Log In

Search test library by skills or roles
⌘ K
logo
Assessment Platform Aptitude Tests Coding Tests Psychometric Tests Personality Tests

TRY FOR FREE

PL/SQL Interview Questions For Freshers
  1. What is the difference between a stored procedure and a function?
  2. How do you declare variables in PL/SQL?
  3. What are the different types of loops available in PL/SQL?
  4. How do you handle exceptions in PL/SQL?
  5. What is a cursor in PL/SQL and how do you use it?
  6. How do you pass parameters to a PL/SQL procedure or function?
  7. What is the difference between IN and OUT parameters in PL/SQL?
  8. How do you create a package in PL/SQL?
  9. What is a trigger in PL/SQL and what are the different types?
  10. What is the difference between a sequence and an identity column in PL/SQL?
  11. How do you use the CASE statement in PL/SQL?
  12. What is a record in PL/SQL and how do you use it?
  13. What is the difference between a local and global temporary table in PL/SQL?
  14. How do you use the NVL function in PL/SQL?
  15. How do you use the DECODE function in PL/SQL?
  16. What is the difference between an exception and an error in PL/SQL?
  17. How do you use the %TYPE and %ROWTYPE attributes in PL/SQL?
  18. How do you use the DBMS_OUTPUT package in PL/SQL?
  19. What is the difference between a standalone procedure and a package procedure in PL/SQL?
PL/SQL Intermediate Interview Questions
  1. What is the difference between a primary key and a unique key?
  2. How do you optimize PL/SQL performance?
  3. How do you debug PL/SQL code?
  4. What is the difference between a view and a materialized view?
  5. How do you create and use PL/SQL collections?
  6. What are the different types of joins in PL/SQL?
  7. How do you use FORALL to improve performance in PL/SQL?
  8. What is a pragma in PL/SQL and how do you use it?
  9. How do you use the ROWID datatype in PL/SQL?
  10. What is a subquery in PL/SQL and how do you use it?
  11. What is the difference between a LEFT JOIN and a RIGHT JOIN in PL/SQL?
  12. How do you use the RAISE_APPLICATION_ERROR function in PL/SQL?
  13. What is the difference between a database and a schema in PL/SQL?
  14. How do you use the DBMS_XPLAN package in PL/SQL?
  15. How do you use the BULK COLLECT statement in PL/SQL?
  16. What is the difference between a trigger and a stored procedure in PL/SQL?
  17. How do you use the DBMS_LOCK package in PL/SQL?
  18. What is the difference between an anonymous block and a stored procedure in PL/SQL?
  19. How do you use the DBMS_SQLTUNE package in PL/SQL?
  20. What is the difference between a temporary table and a materialized view in PL/SQL?
PL/SQL Interview Questions For Experienced
  1. What is the difference between a function-based index and a normal index?
  2. How do you use the UTL_FILE package in PL/SQL?
  3. How do you use dynamic SQL in PL/SQL?
  4. What is the difference between a trigger and a constraint in PL/SQL?
  5. How do you use the DBMS_SQL package in PL/SQL?
  6. How do you use the DBMS_METADATA package in PL/SQL?
  7. What is the difference between a procedure and a package in PL/SQL?
  8. How do you use the DBMS_APPLICATION_INFO package in PL/SQL?
  9. What is the difference between a static and dynamic cursor in PL/SQL?
  10. How do you use the DBMS_SCHEDULER package in PL/SQL?
  11. How do you use the UTL_HTTP package in PL/SQL?
  12. What is the difference between a schema and a database user in PL/SQL?
  13. How do you use the DBMS_SESSION package in PL/SQL?
  14. How do you use the DBMS_SQLDIAG package in PL/SQL?
  15. How do you use the DBMS_METADATA_DIFF package in PL/SQL?
  16. What is the difference between a materialized view and a summary table in PL/SQL?
  17. How do you use the DBMS_PROFILER package in PL/SQL?
  18. What is the difference between a database trigger and a table trigger in PL/SQL?
  19. How do you use the DBMS_DATAPUMP package in PL/SQL?
  20. What is the difference between a weak and strong entity in PL/SQL?


Interview Questions

PL/SQL interview questions with detailed answers

Most important PL/SQL interview questions for freshers, intermediate and experienced candidates. The important questions are categorized for quick browsing before the interview or to act as a detailed guide on different topics PL/SQL interviewers look for.

PL/SQL Online Test

PL/SQL Interview Questions For Freshers

What is the difference between a stored procedure and a function?

View answer

Hide answer

Stored procedures and functions are both database objects that can be created using SQL. The main difference between the two is that a stored procedure is used to perform an action, while a function is used to return a value.

Here's an example of a stored procedure that inserts data into a table:

CREATE PROCEDURE insert_data (p_name VARCHAR2, p_age NUMBER) AS
BEGIN
   INSERT INTO my_table (name, age) VALUES (p_name, p_age);
   COMMIT;
END;
/

This stored procedure takes two input parameters, p_name and p_age, and inserts them into the my_table table.

Here's an example of a function that calculates the average of two numbers:

CREATE FUNCTION avg_num (a NUMBER, b NUMBER) RETURN NUMBER AS
   c NUMBER;
BEGIN
   c := (a + b) / 2;
   RETURN c;
END;
/

This function takes two input parameters, a and b, and returns the average of the two numbers. The RETURN statement is used to return a value from the function.

How do you declare variables in PL/SQL?

View answer

Hide answer

In PL/SQL, variables can be declared using the DECLARE keyword followed by the variable name, data type, and an optional initial value.

Here's an example of declaring a variable a of type NUMBER with an initial value of 10:

DECLARE
   a NUMBER := 10;
BEGIN
   -- code to use the variable goes here
END;
/

Variables can also be declared without an initial value, like this:

DECLARE
   b VARCHAR2(50);
BEGIN
   -- code to use the variable goes here
END;
/

In this example, the variable b is declared as a VARCHAR2 data type with a maximum length of 50 characters, but no initial value is assigned.

Variables can be used to store data within a PL/SQL block and can be referenced multiple times throughout the block. They can also be used in conditional statements, loops, and other programming constructs.

What are the different types of loops available in PL/SQL?

View answer

Hide answer

In PL/SQL, there are three types of loops: FOR, WHILE, and LOOP.

Here's an example of a FOR loop that iterates over a collection of numbers:

FOR i IN 1..10 LOOP
   DBMS_OUTPUT.PUT_LINE(i);
END LOOP;

In this example, the loop iterates from 1 to 10, and the DBMS_OUTPUT.PUT_LINE statement is executed for each iteration, displaying the value of i in the output.

Here's an example of a WHILE loop that continues to execute as long as a condition is true:

DECLARE
   i NUMBER := 1;
BEGIN
   WHILE i <= 10 LOOP
      DBMS_OUTPUT.PUT_LINE(i);
      i := i + 1;
   END LOOP;
END;
/

In this example, the loop continues to execute as long as the value of i is less than or equal to 10. The DBMS_OUTPUT.PUT_LINE statement is executed for each iteration, displaying the value of i in the output.

Here's an example of a LOOP that continues to execute until a condition is met:

DECLARE
   i NUMBER := 1;
BEGIN
   LOOP
      DBMS_OUTPUT.PUT_LINE(i);
      i := i + 1;
      EXIT WHEN i > 10;
   END LOOP;
END;
/

In this example, the loop continues to execute until the value of i is greater than 10. The DBMS_OUTPUT.PUT_LINE statement is executed for each iteration, displaying the value of i in the output. The EXIT WHEN statement is used to exit the loop when the condition is met.

How do you handle exceptions in PL/SQL?

View answer

Hide answer

In PL/SQL, exceptions are handled using the EXCEPTION block. When an error occurs, the exception block is executed, allowing you to handle the error and take appropriate action.

Here's an example of a PL/SQL block that includes an EXCEPTION block to handle an error:

DECLARE
   x NUMBER := 0;
BEGIN
   -- code that may raise an exception goes here
   IF x = 0 THEN
      RAISE_APPLICATION_ERROR(-20001, 'Value of x cannot be zero.');
   END IF;
EXCEPTION
   WHEN OTHERS THEN
      DBMS_OUTPUT.PUT_LINE('An error occurred: ' || SQLERRM);
END;
/

In this example, the code raises an exception if the value of x is zero. The RAISE_APPLICATION_ERROR statement is used to raise the exception and provide a custom error message. The EXCEPTION block catches the exception and displays the error message using the DBMS_OUTPUT.PUT_LINE statement and the SQLERRM function, which returns the error message associated with the error code.

You can also handle specific exceptions using the EXCEPTION block. For example:

DECLARE
   x NUMBER := 0;
BEGIN
   -- code that may raise an exception goes here
   IF x = 0 THEN
      RAISE_ZERO_DIVIDE;
   END IF;
EXCEPTION
   WHEN ZERO_DIVIDE THEN
      DBMS_OUTPUT.PUT_LINE('Cannot divide by zero.');
   WHEN OTHERS THEN
      DBMS_OUTPUT.PUT_LINE('An error occurred: ' || SQLERRM);
END;
/

In this example, the RAISE_ZERO_DIVIDE statement is used to raise a ZERO_DIVIDE exception if the value of x is zero. The EXCEPTION block includes two handlers: one for the ZERO_DIVIDE exception and one for all other exceptions. If a ZERO_DIVIDE exception occurs, the handler displays a custom error message. If any other exception occurs, the handler displays the error message using the SQLERRM function.

What is a cursor in PL/SQL and how do you use it?

View answer

Hide answer

In PL/SQL, a cursor is a mechanism for traversing the records in a result set. You can use a cursor to retrieve and process multiple rows of data returned from a query.

Here's an example of how to declare and use a cursor in PL/SQL:

DECLARE
   cursor_name CURSOR IS
      SELECT column1, column2, column3 FROM table_name;
   var1 datatype1;
   var2 datatype2;
   var3 datatype3;
BEGIN
   OPEN cursor_name;
   LOOP
      FETCH cursor_name INTO var1, var2, var3;
      EXIT WHEN cursor_name%NOTFOUND;
      -- do something with var1, var2, and var3
      DBMS_OUTPUT.PUT_LINE(var1 || ' ' || var2 || ' ' || var3);
   END LOOP;
   CLOSE cursor_name;
END;
/

In this example, the cursor cursor_name is declared to select three columns from a table. The OPEN statement is used to open the cursor, and the LOOP is used to fetch and process each row of data. The FETCH statement retrieves the next row of data into the variables var1, var2, and var3. The EXIT WHEN statement is used to exit the loop when there are no more rows to fetch. Finally, the CLOSE statement is used to close the cursor. Inside the loop, you can perform any desired operations on the fetched values, such as displaying them using DBMS_OUTPUT.PUT_LINE.

How do you pass parameters to a PL/SQL procedure or function?

View answer

Hide answer

In PL/SQL, you can pass parameters to a procedure or function using the IN, OUT, and IN OUT keywords.

Here's an example of how to declare and use parameters in a PL/SQL procedure:

CREATE OR REPLACE PROCEDURE my_procedure (
   param1 IN VARCHAR2,
   param2 OUT NUMBER,
   param3 IN OUT DATE
) AS
BEGIN
   -- do something with the parameters
   param2 := param2 + 1;
   param3 := param3 + 1;
END;
/

In this example, the procedure my_procedure has three parameters: param1 is an input parameter of type VARCHAR2, param2 is an output parameter of type NUMBER, and param3 is an input/output parameter of type DATE. Inside the procedure, you can perform any desired operations on the parameters, such as modifying the value of param2 and param3.

Here's an example of how to call the my_procedure procedure with parameters:

DECLARE
   v_param1 VARCHAR2(10) := 'foo';
   v_param2 NUMBER;
   v_param3 DATE := SYSDATE;
BEGIN
   my_procedure(v_param1, v_param2, v_param3);
   DBMS_OUTPUT.PUT_LINE('param2 = ' || v_param2);
   DBMS_OUTPUT.PUT_LINE('param3 = ' || v_param3);
END;
/

In this example, the my_procedure procedure is called with the values of v_param1, v_param2, and v_param3. After the procedure call, the values of v_param2 and v_param3 are displayed using DBMS_OUTPUT.PUT_LINE. Note that the value of v_param2 is modified inside the procedure and returned as an output parameter.

What is the difference between IN and OUT parameters in PL/SQL?

View answer

Hide answer

In PL/SQL, the IN and OUT parameter modes are used to define how a parameter is passed to a procedure or function.

An IN parameter is used to pass values into a procedure or function. The value of an IN parameter cannot be modified inside the procedure or function.

An OUT parameter is used to pass values out of a procedure or function. The value of an OUT parameter must be set inside the procedure or function and can be accessed after the procedure or function returns.

Here's an example of how to declare and use IN and OUT parameters in a PL/SQL procedure:

CREATE OR REPLACE PROCEDURE my_procedure (
   param1 IN VARCHAR2,
   param2 OUT NUMBER
) AS
BEGIN
   -- do something with the parameters
   param2 := LENGTH(param1);
END;
/

In this example, the procedure my_procedure has two parameters: param1 is an input parameter of type VARCHAR2, and param2 is an output parameter of type NUMBER. Inside the procedure, the value of param2 is set to the length of param1.

Here's an example of how to call the my_procedure procedure with parameters:

DECLARE
   v_param1 VARCHAR2(10) := 'foo';
   v_param2 NUMBER;
BEGIN
   my_procedure(v_param1, v_param2);
   DBMS_OUTPUT.PUT_LINE('Length of ' || v_param1 || ' = ' || v_param2);
END;
/

In this example, the my_procedure procedure is called with the values of v_param1 and v_param2. After the procedure call, the value of v_param2 is displayed using DBMS_OUTPUT.PUT_LINE. Note that the value of v_param2 is set inside the procedure and returned as an output parameter.

How do you create a package in PL/SQL?

View answer

Hide answer

In PL/SQL, a package is a collection of related procedures, functions, and other program objects that are stored together in the database. To create a package, you use the CREATE PACKAGE statement to define the package specification and the CREATE PACKAGE BODY statement to define the package implementation.

Here's an example of how to create a package in PL/SQL:

CREATE OR REPLACE PACKAGE my_package AS
   PROCEDURE my_procedure(param1 IN VARCHAR2);
   FUNCTION my_function(param1 IN NUMBER) RETURN NUMBER;
END my_package;
/

CREATE OR REPLACE PACKAGE BODY my_package AS
   PROCEDURE my_procedure(param1 IN VARCHAR2) AS
   BEGIN
      -- do something with param1
   END my_procedure;

   FUNCTION my_function(param1 IN NUMBER) RETURN NUMBER AS
   BEGIN
      RETURN param1 + 1;
   END my_function;
END my_package;
/

In this example, the my_package package has two program objects: the my_procedure procedure and the my_function function. The package specification defines the program objects and their parameters, while the package body provides the implementation for each program object.

After you create the package, you can use its program objects by prefixing the object name with the package name, like this:

BEGIN
   my_package.my_procedure('foo');
   DBMS_OUTPUT.PUT_LINE(my_package.my_function(42));
END;
/

In this example, the my_procedure procedure and the my_function function are called using the package name my_package.

What is a trigger in PL/SQL and what are the different types?

View answer

Hide answer

In PL/SQL, a trigger is a database object that executes automatically in response to specific events, such as a database insert, update, or delete operation.

There are two types of triggers in PL/SQL:

  1. Row-level trigger: Fires once for each row affected by the triggering statement.
  2. Statement-level trigger: Fires only once for each triggering statement, regardless of how many rows are affected.

Here's an example of how to create a row-level trigger in PL/SQL:

CREATE OR REPLACE TRIGGER my_trigger
AFTER INSERT OR UPDATE OR DELETE ON my_table
FOR EACH ROW
BEGIN
   -- do something when a row is inserted, updated, or deleted
END;
/

In this example, the my_trigger trigger is defined to execute after an insert, update, or delete operation is performed on the my_table table. The FOR EACH ROW clause specifies that the trigger is a row-level trigger.

Here's an example of how to create a statement-level trigger in PL/SQL:

CREATE OR REPLACE TRIGGER my_trigger
AFTER INSERT OR UPDATE OR DELETE ON my_table
BEGIN
   -- do something when a row is inserted, updated, or deleted
END;
/

In this example, the my_trigger trigger is defined to execute after an insert, update, or delete operation is performed on the my_table table. The absence of the FOR EACH ROW clause specifies that the trigger is a statement-level trigger.

What is the difference between a sequence and an identity column in PL/SQL?

View answer

Hide answer

In PL/SQL, a sequence is a database object that generates a sequence of unique numbers, while an identity column is a column that automatically generates unique values when a new row is inserted into a table.

The main difference between a sequence and an identity column is that a sequence is a separate database object that can be used across multiple tables and columns, while an identity column is tied to a specific table and column.

Here's an example of how to create a sequence in PL/SQL:

CREATE SEQUENCE my_sequence
START WITH 1
INCREMENT BY 1
CACHE 20;

In this example, the my_sequence sequence is defined to start with 1 and increment by 1. The CACHE option specifies that the sequence should cache 20 values in memory for better performance.

Here's an example of how to create an identity column in PL/SQL:

CREATE TABLE my_table (
   id NUMBER GENERATED ALWAYS AS IDENTITY,
   name VARCHAR2(50),
   age NUMBER
);

In this example, the id column is defined as an identity column using the GENERATED ALWAYS AS IDENTITY clause. This means that whenever a new row is inserted into the my_table table, a unique value will be automatically generated for the id column.

How do you use the CASE statement in PL/SQL?

View answer

Hide answer

In PL/SQL, the CASE statement is used to conditionally execute code based on a specific value. It can be used in both SQL queries and PL/SQL code blocks.

Here's an example of how to use the CASE statement in a SQL query:

SELECT name, age,
   CASE
      WHEN age < 18 THEN 'Minor'
      WHEN age >= 18 AND age < 65 THEN 'Adult'
      ELSE 'Senior'
   END AS age_group
FROM my_table;

In this example, the CASE statement is used to determine the age group for each person in the my_table table based on their age.

Here's an example of how to use the CASE statement in a PL/SQL code block:

DECLARE
   grade VARCHAR2(10);
BEGIN
   grade := CASE
               WHEN score >= 90 THEN 'A'
               WHEN score >= 80 THEN 'B'
               WHEN score >= 70 THEN 'C'
               WHEN score >= 60 THEN 'D'
               ELSE 'F'
            END;
   DBMS_OUTPUT.PUT_LINE('Grade: ' || grade);
END;

In this example, the CASE statement is used to determine the grade for a given score in a PL/SQL code block. The result is then printed using the DBMS_OUTPUT.PUT_LINE procedure.

What is a record in PL/SQL and how do you use it?

View answer

Hide answer

In PL/SQL, a record is a composite data type that contains a set of related fields or columns. It is similar to a row in a database table.

Here's an example of how to declare a record in PL/SQL:

DECLARE
   TYPE employee_type IS RECORD (
      emp_id NUMBER,
      emp_name VARCHAR2(50),
      emp_salary NUMBER
   );
   emp_record employee_type;
BEGIN
   emp_record.emp_id := 1234;
   emp_record.emp_name := 'John Smith';
   emp_record.emp_salary := 50000;
END;

In this example, a record type called employee_type is declared with three fields: emp_id, emp_name, and emp_salary. A variable called emp_record is then declared using this record type, and its fields are assigned values.

Records can also be used to retrieve values from a database query, like this:

DECLARE
   emp_record my_table%ROWTYPE;
BEGIN
   SELECT * INTO emp_record FROM my_table WHERE id = 1234;
   DBMS_OUTPUT.PUT_LINE('Employee Name: ' || emp_record.name);
END;

In this example, a record called emp_record is declared using the %ROWTYPE attribute to match the structure of the my_table table. The SELECT INTO statement retrieves a row from the table with id equal to 1234 and assigns its values to emp_record. The DBMS_OUTPUT.PUT_LINE procedure then prints the value of the name field in the record.

What is the difference between a local and global temporary table in PL/SQL?

View answer

Hide answer

In PL/SQL, a local temporary table is created for a session and is automatically dropped at the end of the session. A global temporary table, on the other hand, is created once and can be shared across sessions, but its data is only visible to the session that inserted it and is automatically deleted when the session ends.

Here's an example of how to create a local temporary table:

CREATE GLOBAL TEMPORARY TABLE my_temp_table (
   id NUMBER,
   name VARCHAR2(50)
) ON COMMIT PRESERVE ROWS;

In this example, the my_temp_table temporary table is created with two columns. The ON COMMIT PRESERVE ROWS clause ensures that the data in the table is not deleted at the end of a transaction.

Here's an example of how to create a global temporary table:

CREATE GLOBAL TEMPORARY TABLE my_temp_table (
   id NUMBER,
   name VARCHAR2(50)
) ON COMMIT DELETE ROWS;

In this example, the ON COMMIT DELETE ROWS clause ensures that the data in the table is deleted at the end of the transaction.

Both types of temporary tables can be used to store data temporarily and share data between sessions, but they have different lifetimes and persistence behaviors.

How do you use the NVL function in PL/SQL?

View answer

Hide answer

The NVL function in PL/SQL is used to replace a NULL value with a specified value. It takes two arguments - the first is the value to be checked for NULL, and the second is the value to replace NULL.

Here's an example of how to use the NVL function:

SELECT NVL(product_name, 'Not Available') AS name
FROM products;

In this example, the NVL function is used to replace any NULL values in the product_name column of the products table with the string 'Not Available'. The result of the query will include all products, with NULL values replaced by 'Not Available'.

How do you use the DECODE function in PL/SQL?

View answer

Hide answer

The DECODE function in PL/SQL is used to conditionally transform values based on comparison results. It takes three or more arguments, with the first being the value to compare, and the remaining pairs of arguments representing the value to return if the comparison is true and the value to return if the comparison is false, respectively.

Here's an example of how to use the DECODE function:

SELECT product_name,
       DECODE(product_type, 'A', 'Accessories', 'B', 'Books', 'Other')
       AS category
FROM products;

In this example, the DECODE function is used to transform the product_type column of the products table into a categorical category column. If product_type is 'A', the category value will be 'Accessories', if it is 'B', the category value will be 'Books', and if it is anything else, the category value will be 'Other'.

What is the difference between an exception and an error in PL/SQL?

View answer

Hide answer

In PL/SQL, an error refers to a problem that prevents the execution of a program or a piece of code, such as a syntax error or a database connection failure. An exception, on the other hand, is an event that occurs during the execution of a program, such as a division by zero or a constraint violation.

In PL/SQL, errors are typically handled using error handling techniques such as RAISE_APPLICATION_ERROR, while exceptions are handled using EXCEPTION blocks.

Here's an example of how to handle an error and an exception:

BEGIN
   -- Error handling
   SELECT * FROM non_existent_table;
EXCEPTION
   WHEN NO_DATA_FOUND THEN
      DBMS_OUTPUT.PUT_LINE('Table does not exist.');

   -- Exception handling
   DECLARE
      result NUMBER;
   BEGIN
      result := 10 / 0;
   EXCEPTION
      WHEN ZERO_DIVIDE THEN
         DBMS_OUTPUT.PUT_LINE('Cannot divide by zero.');
   END;
END;

In this example, the error handling block attempts to select data from a non-existent table, while the exception handling block attempts to divide a number by zero. If an error occurs, it will trigger the EXCEPTION block for error handling, while if an exception occurs, it will trigger the EXCEPTION block for exception handling.

How do you use the %TYPE and %ROWTYPE attributes in PL/SQL?

View answer

Hide answer

The %TYPE attribute is used to declare a variable with the same datatype as a specified column, while %ROWTYPE is used to declare a variable with the same structure as a specified table row.

For example, to declare a variable "my_variable" with the same datatype as the "salary" column in the "employees" table, we can use %TYPE as follows:

DECLARE
  my_variable employees.salary%TYPE;
BEGIN
  -- code here
END;

To declare a variable "my_row" with the same structure as a row in the "employees" table, we can use %ROWTYPE as follows:

DECLARE
  my_row employees%ROWTYPE;
BEGIN
  -- code here
END;

Using these attributes helps to ensure data consistency and simplifies maintenance of the code.

How do you use the DBMS_OUTPUT package in PL/SQL?

View answer

Hide answer

The DBMS_OUTPUT package in PL/SQL is used for displaying debugging information and messages from PL/SQL code. The package provides a PUT_LINE procedure that outputs a string to the console or a buffer. Here's an example:

DECLARE
   message VARCHAR2(50) := 'Hello, world!';
BEGIN
   DBMS_OUTPUT.PUT_LINE(message);
END;

In this example, the PUT_LINE procedure is used to output the string "Hello, world!" to the console. To view the output, you may need to enable the DBMS_OUTPUT feature in your SQL client or tool by using the SET SERVEROUTPUT ON command or a similar command.

What is the difference between a standalone procedure and a package procedure in PL/SQL?

View answer

Hide answer

A standalone procedure in PL/SQL is a procedure that is defined separately from other procedures or functions, whereas a package procedure is defined within a PL/SQL package. A package is a collection of related procedures, functions, variables, and other program objects that can be used in multiple parts of an application.

Here is an example of a standalone procedure:

CREATE OR REPLACE PROCEDURE my_standalone_proc AS
BEGIN
   -- procedure code goes here
END;

And here is an example of a package that contains a procedure:

CREATE OR REPLACE PACKAGE my_package AS
   PROCEDURE my_package_proc;
END my_package;

CREATE OR REPLACE PACKAGE BODY my_package AS
   PROCEDURE my_package_proc AS
   BEGIN
      -- procedure code goes here
   END;
END my_package;

In the package example, the procedure my_package_proc is defined within the package my_package and can be called from any part of the application that has access to the package.

PL/SQL Intermediate Interview Questions

What is the difference between a primary key and a unique key?

View answer

Hide answer

Both primary keys and unique keys are used to enforce data integrity and ensure that each row in a table is unique.

A primary key is a column or set of columns that uniquely identifies each row in a table, and is used as a reference for foreign keys in related tables. A primary key cannot contain NULL values, and there can only be one primary key per table.

A unique key is also a column or set of columns that ensures each row in a table is unique, but it does not have the same constraints as a primary key. A unique key can contain NULL values, and a table can have multiple unique keys.

Here is an example of defining a primary key and a unique key in SQL:

CREATE TABLE my_table (
   id NUMBER PRIMARY KEY,
   name VARCHAR2(50) NOT NULL,
   email VARCHAR2(50) UNIQUE
);

In this example, id is defined as the primary key, which means each row must have a unique value for id and it cannot contain NULL values. email is defined as a unique key, which means each value in the column must be unique, but it can contain NULL values.

How do you optimize PL/SQL performance?

View answer

Hide answer

There are several ways to optimize PL/SQL performance, including:

  • Minimizing context switches between SQL and PL/SQL
  • Reducing the number of SQL statements executed
  • Avoiding redundant or unnecessary code
  • Properly indexing tables and using bind variables
  • Using bulk processing instead of row-by-row processing

Here is an example of using bulk processing with the FORALL statement to improve performance:

DECLARE
  TYPE id_tabtype IS TABLE OF employees.employee_id%TYPE INDEX BY PLS_INTEGER;
  id_tab id_tabtype;
BEGIN
  SELECT employee_id BULK COLLECT INTO id_tab FROM employees WHERE department_id = 10;

  FORALL i IN 1..id_tab.COUNT
    UPDATE employees SET salary = salary * 1.1 WHERE employee_id = id_tab(i);
END;

How do you debug PL/SQL code?

View answer

Hide answer

PL/SQL code can be debugged using various tools such as SQL Developer, PL/SQL Developer, and TOAD. One can use breakpoints, watches, and stepping through the code to locate errors. Also, using DBMS_OUTPUT.PUT_LINE statements to output the values of variables can help to understand the flow of the code. For example:

DECLARE
  a NUMBER := 10;
  b NUMBER := 0;
BEGIN
  b := 10 / 0; -- This line will throw a division by zero error
EXCEPTION
  WHEN OTHERS THEN
    DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
END;

Running the above code in a debugging tool with a breakpoint on the line that throws the error can help to identify the issue.

What is the difference between a view and a materialized view?

View answer

Hide answer

A view is a virtual table created by a SQL query that provides a way to access and manipulate data from one or more tables, while a materialized view is a physical copy of the data returned by a query. The data in a materialized view is stored in a table-like structure, which makes it faster to access and query than a regular view. Materialized views must be refreshed manually or automatically to ensure their data is up-to-date. Here are examples of creating a view and a materialized view:

Creating a view:

CREATE VIEW employee_info AS
SELECT first_name, last_name, hire_date, salary
FROM employees
WHERE department_id = 50;

Creating a materialized view:

CREATE MATERIALIZED VIEW employee_info_mv AS
SELECT first_name, last_name, hire_date, salary
FROM employees
WHERE department_id = 50;

Refreshing a materialized view:

REFRESH MATERIALIZED VIEW employee_info_mv;

How do you create and use PL/SQL collections?

View answer

Hide answer

PL/SQL collections are used to store multiple values in a single variable. They include associative arrays, nested tables, and VARRAYs. To create a collection, you need to define a type for it first, then declare a variable of that type. Here's an example of creating and using a nested table:

-- Creating a type for nested table
CREATE TYPE test_type AS TABLE OF VARCHAR2(50);

-- Declaring a variable of test_type
DECLARE
  test_variable test_type := test_type('value1', 'value2', 'value3');
BEGIN
  -- Accessing elements of test_variable
  DBMS_OUTPUT.PUT_LINE(test_variable(1)); -- Output: value1
  DBMS_OUTPUT.PUT_LINE(test_variable(2)); -- Output: value2
  DBMS_OUTPUT.PUT_LINE(test_variable(3)); -- Output: value3
END;

In the above example, we first created a type called test_type as a table of VARCHAR2 values. We then declared a variable test_variable of that type and assigned it three string values. Finally, we accessed the elements of the test_variable using their indices and printed them using DBMS_OUTPUT.PUT_LINE().

What are the different types of joins in PL/SQL?

View answer

Hide answer

In PL/SQL, the different types of joins are:

  1. INNER JOIN: returns only the rows that match in both tables.
SELECT *
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
  1. LEFT JOIN (or LEFT OUTER JOIN): returns all the rows from the left table and the matched rows from the right table. If there is no match in the right table, NULL values are returned.
SELECT *
FROM table1
LEFT JOIN table2
ON table1.column = table2.column;
  1. RIGHT JOIN (or RIGHT OUTER JOIN): returns all the rows from the right table and the matched rows from the left table. If there is no match in the left table, NULL values are returned.
SELECT *
FROM table1
RIGHT JOIN table2
ON table1.column = table2.column;
  1. FULL JOIN (or FULL OUTER JOIN): returns all the rows from both tables. If there is no match in one of the tables, NULL values are returned.
SELECT *
FROM table1
FULL JOIN table2
ON table1.column = table2.column;
  1. CROSS JOIN (or CARTESIAN JOIN): returns the combination of all rows from both tables.
SELECT *
FROM table1
CROSS JOIN table2;

How do you use FORALL to improve performance in PL/SQL?

View answer

Hide answer

The FORALL statement is used in PL/SQL to perform bulk operations on collections, which can significantly improve performance compared to traditional looping constructs. It allows you to perform multiple DML statements in a single operation, reducing the overhead associated with context switching between SQL and PL/SQL engines. Here's an example that demonstrates how to use FORALL to insert multiple rows into a table:

DECLARE
  TYPE id_tab IS TABLE OF NUMBER;
  TYPE name_tab IS TABLE OF VARCHAR2(50);
  emp_ids id_tab := id_tab(1, 2, 3);
  emp_names name_tab := name_tab('John', 'Jane', 'Bob');
BEGIN
  FORALL i IN 1..emp_ids.COUNT
    INSERT INTO employees (id, name) VALUES (emp_ids(i), emp_names(i));
END;

In this example, we define two collections, emp_ids and emp_names, each containing three elements. We then use the FORALL statement to loop through each element in the collections and insert a row into the employees table using the corresponding values from the collections. This results in three insert statements being executed in a single operation, improving performance.

What is a pragma in PL/SQL and how do you use it?

View answer

Hide answer

A pragma is a compiler directive that provides additional information to the compiler about how to handle a program unit. It is used to provide information to the compiler or to suppress certain warnings or errors. In PL/SQL, a common use of a pragma is to specify the exception that should be raised when an error occurs. Here's an example:

CREATE OR REPLACE FUNCTION get_employee_salary (emp_id IN NUMBER) RETURN NUMBER IS
   salary NUMBER;
   pragma EXCEPTION_INIT (no_such_employee, -20001);
BEGIN
   SELECT salary INTO salary FROM employees WHERE employee_id = emp_id;
   RETURN salary;
EXCEPTION
   WHEN no_such_employee THEN
      DBMS_OUTPUT.PUT_LINE('Employee does not exist');
      RETURN NULL;
END;
/

In this example, the EXCEPTION_INIT pragma is used to associate the -20001 error code with the no_such_employee exception. When the SELECT statement in the BEGIN block raises an error with this code, the associated exception handler will be invoked.

How do you use the ROWID datatype in PL/SQL?

View answer

Hide answer

The ROWID datatype in PL/SQL is used to store the unique address of a row in a database table. It is a pseudo column that returns the address of the row in the database, and can be used to uniquely identify a row.

Here's an example of using the ROWID datatype in a SELECT statement to retrieve the ROWID of a specific row in a table:

DECLARE
   v_rowid ROWID;
BEGIN
   SELECT ROWID INTO v_rowid FROM employees WHERE employee_id = 100;
   DBMS_OUTPUT.PUT_LINE('ROWID of employee with ID 100 is: ' || v_rowid);
END;

What is a subquery in PL/SQL and how do you use it?

View answer

Hide answer

A subquery is a SQL query embedded within another query to retrieve data. In PL/SQL, subqueries are used in SQL statements such as SELECT, UPDATE, DELETE, and INSERT. The subquery can be used in a variety of ways, such as to filter data based on a condition, retrieve data from multiple tables, or retrieve data for further manipulation. Here is an example of a subquery used in a SELECT statement:

SELECT first_name, last_name
FROM employees
WHERE department_id IN (
    SELECT department_id
    FROM departments
    WHERE location_id = 1700
);

This query retrieves the first and last names of employees who belong to departments located in the specified location ID. The subquery retrieves the department IDs for departments located in the specified location.

What is the difference between a LEFT JOIN and a RIGHT JOIN in PL/SQL?

View answer

Hide answer

In PL/SQL, a LEFT JOIN returns all records from the left table and matching records from the right table. On the other hand, a RIGHT JOIN returns all records from the right table and matching records from the left table. If there is no match, NULL values are returned.

For example, consider the following tables:

Table 1: customers
+----+--------+
| id | name   |
+----+--------+
| 1  | Alice  |
| 2  | Bob    |
| 3  | Carol  |
+----+--------+

Table 2: orders
+----+------------+----------+
| id | order_date | customer |
+----+------------+----------+
| 1  | 2022-01-01 | 1        |
| 2  | 2022-01-02 | 3        |
+----+------------+----------+

A LEFT JOIN of customers and orders on the id column would return the following:

+----+--------+----+------------+----------+
| id | name   | id | order_date | customer |
+----+--------+----+------------+----------+
| 1  | Alice  | 1  | 2022-01-01 | 1        |
| 2  | Bob    | NULL | NULL       | NULL     |
| 3  | Carol  | 2  | 2022-01-02 | 3        |
+----+--------+----+------------+----------+

A RIGHT JOIN of customers and orders on the id column would return the following:

+----+--------+----+------------+----------+
| id | name   | id | order_date | customer |
+----+--------+----+------------+----------+
| 1  | Alice  | 1  | 2022-01-01 | 1        |
| NULL | NULL | 2  | 2022-01-02 | 3        |
+----+--------+----+------------+----------+

How do you use the RAISE_APPLICATION_ERROR function in PL/SQL?

View answer

Hide answer

The RAISE_APPLICATION_ERROR function in PL/SQL is used to raise a custom user-defined exception and display an error message with a user-specified error code. The error message can be caught and handled by the caller program. The syntax for the RAISE_APPLICATION_ERROR function is:

RAISE_APPLICATION_ERROR(error_code, error_message);

Here's an example of using the RAISE_APPLICATION_ERROR function:

IF total > 1000 THEN
   RAISE_APPLICATION_ERROR(-20001, 'Total cannot be greater than 1000');
END IF;

This will raise a custom exception with error code -20001 and the error message "Total cannot be greater than 1000".

What is the difference between a database and a schema in PL/SQL?

View answer

Hide answer

A database is a collection of organized data stored and accessed through a DBMS (Database Management System) such as Oracle, MySQL, or SQL Server. A schema is a logical container for database objects such as tables, views, and procedures within a database.

Here's an example of creating a database and a schema in PL/SQL:

-- Creating a database
CREATE DATABASE my_database;

-- Creating a schema in the database
CREATE SCHEMA my_schema AUTHORIZATION my_user;

In the example above, we first create a database named "my_database". Then, we create a schema called "my_schema" within the database, and assign the schema to the user "my_user". The schema will contain database objects such as tables, views, and procedures that are owned by the user.

How do you use the DBMS_XPLAN package in PL/SQL?

View answer

Hide answer

The DBMS_XPLAN package in PL/SQL is used to format and display the execution plan of a SQL statement. Here's an example of how to use the DBMS_XPLAN package:

-- Set the SQL statement
SELECT * FROM employees WHERE department_id = 10;

-- Generate the execution plan
EXPLAIN PLAN FOR SELECT * FROM employees WHERE department_id = 10;

-- Display the execution plan
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);

In the example above, we first set the SQL statement to be executed. We then generate the execution plan for the statement using the "EXPLAIN PLAN FOR" command. Finally, we display the execution plan using the "DBMS_XPLAN.DISPLAY" function and the "TABLE" operator. This will display the execution plan in a readable format, showing information such as the operations performed, the order in which they are performed, and the estimated cost of each operation.

How do you use the BULK COLLECT statement in PL/SQL?

View answer

Hide answer

The BULK COLLECT statement in PL/SQL is used to retrieve multiple rows of data from a query or a cursor into a collection. Here's an example of how to use the BULK COLLECT statement:

DECLARE
  TYPE employees_type IS TABLE OF employees%ROWTYPE;
  l_employees employees_type;
BEGIN
  -- Query to retrieve employee data
  SELECT * BULK COLLECT INTO l_employees FROM employees WHERE department_id = 10;

  -- Process the retrieved data
  FOR i IN 1..l_employees.COUNT LOOP
    -- do something with each employee record
    NULL;
  END LOOP;
END;

In the example above, we declare a custom type called "employees_type" as a table of the "employees" table rowtype. We then use the BULK COLLECT statement to retrieve all employee records from the "employees" table where the department ID is 10, and store them in the "l_employees" collection. We can then process the retrieved data using a loop. The BULK COLLECT statement is useful for improving the performance of queries that retrieve large amounts of data by reducing the number of context switches between PL/SQL and SQL.

What is the difference between a trigger and a stored procedure in PL/SQL?

View answer

Hide answer

In PL/SQL, a trigger is a type of stored procedure that is automatically executed in response to certain events, such as an INSERT, UPDATE or DELETE operation on a table. Here's an example of a trigger:

CREATE OR REPLACE TRIGGER my_trigger
AFTER INSERT ON my_table
FOR EACH ROW
BEGIN
  -- do something when a row is inserted into the table
  NULL;
END;

In the example above, the trigger "my_trigger" is executed automatically after an insert operation is performed on the "my_table" table. The trigger code, which is enclosed in the "BEGIN" and "END" keywords, can perform any valid PL/SQL operation.

A stored procedure, on the other hand, is a block of code that can be executed on demand, typically by calling it from another program or script. Here's an example of a stored procedure:

CREATE OR REPLACE PROCEDURE my_procedure (p_id IN NUMBER)
IS
BEGIN
  -- do something with the input parameter
  NULL;
END;

In the example above, the stored procedure "my_procedure" takes an input parameter "p_id" of type NUMBER and performs some operation using that parameter. The procedure can be called from another program or script using the "EXECUTE" keyword or as part of a PL/SQL block.

How do you use the DBMS_LOCK package in PL/SQL?

View answer

Hide answer

The DBMS_LOCK package in PL/SQL is used to provide synchronization and serialization of access to shared resources. Here's an example of how to use the DBMS_LOCK package:

DECLARE
  l_lock_handle VARCHAR2(128);
  l_lock_result NUMBER;
BEGIN
  -- Request a lock
  l_lock_handle := DBMS_LOCK.ALLOCATE_UNIQUE('my_lock');

  l_lock_result := DBMS_LOCK.REQUEST(l_lock_handle, DBMS_LOCK.X_MODE, 0, TRUE);

  IF l_lock_result = 0 THEN
    -- Lock acquired successfully
    NULL;
  ELSE
    -- Lock not acquired
    RAISE_APPLICATION_ERROR(-20001, 'Could not acquire lock');
  END IF;

  -- Release the lock
  DBMS_LOCK.RELEASE(l_lock_handle);
END;

In the example above, we first allocate a unique lock handle using the "DBMS_LOCK.ALLOCATE_UNIQUE" function. We then request a lock with exclusive mode using the "DBMS_LOCK.REQUEST" function, which returns a result code indicating whether the lock was acquired successfully. If the lock is acquired, we can proceed to perform some operation. Finally, we release the lock using the "DBMS_LOCK.RELEASE" function. If the lock is not acquired, we raise an error using the "RAISE_APPLICATION_ERROR" function. The DBMS_LOCK package can be used to coordinate access to shared resources in multi-user environments, ensuring that only one user has access to the resource at a time.

What is the difference between an anonymous block and a stored procedure in PL/SQL?

View answer

Hide answer

In PL/SQL, an anonymous block is a section of code that is not stored in the database and can be executed on demand. Here's an example of an anonymous block:

BEGIN
  -- do something
  NULL;
END;

In the example above, the anonymous block consists of a "BEGIN" keyword, some code, and an "END" keyword. The code enclosed in the block can perform any valid PL/SQL operation, but it is not stored in the database and must be executed as a script or as part of another program.

A stored procedure, on the other hand, is a block of code that is stored in the database and can be executed on demand by calling it from another program or script. Here's an example of a stored procedure:

CREATE OR REPLACE PROCEDURE my_procedure (p_id IN NUMBER)
IS
BEGIN
  -- do something with the input parameter
  NULL;
END;

In the example above, the stored procedure "my_procedure" takes an input parameter "p_id" of type NUMBER and performs some operation using that parameter. The procedure is stored in the database and can be called from another program or script using the "EXECUTE" keyword or as part of a PL/SQL block. The main difference between an anonymous block and a stored procedure is that the latter can be reused and called from different programs, while the former is designed to be executed once and discarded.

How do you use the DBMS_SQLTUNE package in PL/SQL?

View answer

Hide answer

The DBMS_SQLTUNE package in PL/SQL is used to capture and tune SQL statements for better performance. Here's an example of how to use the DBMS_SQLTUNE package:

DECLARE
  l_task_name VARCHAR2(30);
  l_sql_text CLOB := 'SELECT * FROM my_table WHERE id = :id';
  l_sql_id VARCHAR2(13);
  l_sql_plan_id VARCHAR2(40);
BEGIN
  -- Create a tuning task
  l_task_name := DBMS_SQLTUNE.CREATE_TUNING_TASK(sql_text => l_sql_text);

  -- Execute the tuning task
  DBMS_SQLTUNE.EXECUTE_TUNING_TASK(task_name => l_task_name);

  -- Get the execution plan for the SQL statement
  SELECT sql_id, plan_hash_value INTO l_sql_id, l_sql_plan_id
  FROM v$sql
  WHERE sql_text = l_sql_text;

  -- Display the execution plan
  DBMS_OUTPUT.PUT_LINE(DBMS_SQLTUNE.REPORT_TUNING_TASK(l_task_name));
END;

In the example above, we first create a tuning task using the "DBMS_SQLTUNE.CREATE_TUNING_TASK" function and passing in the SQL statement as a CLOB parameter. We then execute the tuning task using the "DBMS_SQLTUNE.EXECUTE_TUNING_TASK" procedure, which generates recommendations for optimizing the SQL statement. We then use the "v$sql" dynamic performance view to obtain the SQL_ID and PLAN_HASH_VALUE of the statement. Finally, we display the tuning report using the "DBMS_SQLTUNE.REPORT_TUNING_TASK" function. The DBMS_SQLTUNE package can help optimize SQL statements for better performance in Oracle databases.

What is the difference between a temporary table and a materialized view in PL/SQL?

View answer

Hide answer

In PL/SQL, a temporary table is a database object that is used to store data temporarily during the execution of a session or transaction. Here's an example of how to create a temporary table:

CREATE GLOBAL TEMPORARY TABLE my_temp_table (
  id NUMBER,
  name VARCHAR2(100)
) ON COMMIT PRESERVE ROWS;

In the example above, the temporary table "my_temp_table" is created with two columns and the "ON COMMIT PRESERVE ROWS" option, which preserves the data in the table until the end of the session. Temporary tables are often used for intermediate results or to store data for complex queries.

A materialized view, on the other hand, is a database object that is used to store the result of a query and can be refreshed periodically. Here's an example of how to create a materialized view:

CREATE MATERIALIZED VIEW my_mat_view
REFRESH COMPLETE ON DEMAND
AS SELECT id, name FROM my_table;

In the example above, the materialized view "my_mat_view" is created using the result of a query on the table "my_table". The "REFRESH COMPLETE ON DEMAND" option specifies that the materialized view should be refreshed on demand using the complete refresh method. Materialized views are often used for frequently executed queries to improve performance.

In summary, the main difference between a temporary table and a materialized view in PL/SQL is that the former is used to store temporary data during a session or transaction, while the latter is used to store the result of a query for improved performance and can be refreshed periodically.

PL/SQL Interview Questions For Experienced

What is the difference between a function-based index and a normal index?

View answer

Hide answer

In PL/SQL, a function-based index is an index that is created based on the result of a function applied to the indexed column(s), rather than on the column(s) themselves. Here's an example of how to create a function-based index:

CREATE INDEX my_func_index ON my_table(UPPER(name));

In the example above, the function-based index "my_func_index" is created on the "name" column of "my_table" using the "UPPER" function to convert the values to uppercase before indexing them. Function-based indexes can improve query performance when using functions on indexed columns.

A normal index, on the other hand, is created on one or more columns in a table to improve the performance of queries that use those columns. Here's an example of how to create a normal index:

CREATE INDEX my_index ON my_table(id);

In the example above, the normal index "my_index" is created on the "id" column of "my_table". Normal indexes can improve query performance when querying on the indexed columns.

In summary, the main difference between a function-based index and a normal index in PL/SQL is that the former is created based on the result of a function applied to the indexed column(s), while the latter is created directly on the column(s) themselves. Function-based indexes can improve query performance when using functions on indexed columns, while normal indexes can improve query performance when querying on the indexed columns.

How do you use the UTL_FILE package in PL/SQL?

View answer

Hide answer

In PL/SQL, the UTL_FILE package is used to read from and write to operating system files. Here's an example of how to use the UTL_FILE package to write to a file:

DECLARE
  file_handle UTL_FILE.FILE_TYPE;
BEGIN
  file_handle := UTL_FILE.FOPEN('MY_DIR', 'my_file.txt', 'W');
  UTL_FILE.PUT_LINE(file_handle, 'Hello, world!');
  UTL_FILE.FCLOSE(file_handle);
END;

In the example above, the UTL_FILE.FOPEN function is used to open the file "my_file.txt" in the directory "MY_DIR" for writing, and the UTL_FILE.PUT_LINE procedure is used to write the text "Hello, world!" to the file. Finally, the UTL_FILE.FCLOSE procedure is used to close the file.

Here's an example of how to use the UTL_FILE package to read from a file:

DECLARE
  file_handle UTL_FILE.FILE_TYPE;
  text VARCHAR2(32767);
BEGIN
  file_handle := UTL_FILE.FOPEN('MY_DIR', 'my_file.txt', 'R');
  UTL_FILE.GET_LINE(file_handle, text);
  DBMS_OUTPUT.PUT_LINE(text);
  UTL_FILE.FCLOSE(file_handle);
END;

In the example above, the UTL_FILE.FOPEN function is used to open the file "my_file.txt" in the directory "MY_DIR" for reading, and the UTL_FILE.GET_LINE procedure is used to read the first line of text from the file. The DBMS_OUTPUT.PUT_LINE procedure is used to print the text to the console, and the UTL_FILE.FCLOSE procedure is used to close the file.

In summary, the UTL_FILE package is used to read from and write to operating system files in PL/SQL, and provides functions and procedures for opening, reading from, and writing to files.

How do you use dynamic SQL in PL/SQL?

View answer

Hide answer

Dynamic SQL in PL/SQL allows you to generate and execute SQL statements at runtime. This can be useful in situations where the SQL statement cannot be determined at compile time. Here's an example of how to use dynamic SQL in PL/SQL:

DECLARE
  l_sql_stmt VARCHAR2(4000);
  l_empno NUMBER := 100;
  l_ename VARCHAR2(80);
BEGIN
  l_sql_stmt := 'SELECT ename FROM emp WHERE empno = :1';
  EXECUTE IMMEDIATE l_sql_stmt INTO l_ename USING l_empno;
  DBMS_OUTPUT.PUT_LINE(l_ename);
END;

In the example above, the SQL statement is stored in the variable l_sql_stmt as a string. The EXECUTE IMMEDIATE statement is used to execute the SQL statement stored in l_sql_stmt. The INTO clause is used to retrieve the result of the SQL statement into the variable l_ename. The USING clause is used to pass in the bind variable l_empno to the SQL statement.

Dynamic SQL in PL/SQL can be powerful, but it also introduces some security risks, such as SQL injection attacks. It is important to carefully validate and sanitize any user input used in dynamic SQL statements.

What is the difference between a trigger and a constraint in PL/SQL?

View answer

Hide answer

A trigger is a piece of PL/SQL code that is executed in response to a specific event, such as an insert, update, or delete operation on a table. A constraint is a rule that is defined on a table to enforce some condition, such as a unique or not null constraint.

Here's an example of a trigger that is executed after an insert on a table:

CREATE OR REPLACE TRIGGER my_trigger
AFTER INSERT ON my_table
FOR EACH ROW
BEGIN
  -- code to be executed
END;

Here's an example of a unique constraint on a table:

CREATE TABLE my_table (
  id NUMBER,
  name VARCHAR2(100),
  CONSTRAINT my_constraint UNIQUE (id)
);

The unique constraint ensures that the values in the id column are unique. If an insert or update violates the constraint, an error will be raised.

While both triggers and constraints can be used to enforce business rules and data integrity, triggers are more flexible and can be used to perform more complex logic, such as auditing or logging. Constraints are simpler and easier to manage, and are generally used for simpler rules that can be expressed as a condition on a column or set of columns.

How do you use the DBMS_SQL package in PL/SQL?

View answer

Hide answer

The DBMS_SQL package in PL/SQL allows you to execute dynamic SQL statements and retrieve the results. Here's an example of how to use the DBMS_SQL package:

DECLARE
  l_cursor_id NUMBER;
  l_result_set DBMS_SQL.DESC_TAB;
BEGIN
  l_cursor_id := DBMS_SQL.OPEN_CURSOR;
  DBMS_SQL.PARSE(l_cursor_id, 'SELECT ename, job FROM emp WHERE deptno = :1', DBMS_SQL.NATIVE);
  DBMS_SQL.BIND_VARIABLE(l_cursor_id, 1, 20);
  DBMS_SQL.DESCRIBE_COLUMNS(l_cursor_id, l_result_set);
  FOR i IN 1..l_result_set.COUNT LOOP
    DBMS_OUTPUT.PUT_LINE(l_result_set(i).COL_NAME);
  END LOOP;
  IF DBMS_SQL.EXECUTE(l_cursor_id) > 0 THEN
    WHILE DBMS_SQL.FETCH_ROWS(l_cursor_id) > 0 LOOP
      DBMS_OUTPUT.PUT_LINE(DBMS_SQL.GET_COL_NUMBER(l_cursor_id, 'ENAME') || ': ' || DBMS_SQL.VARCHAR2S(DBMS_SQL.GET_COL_VALUE(l_cursor_id, 1)));
      DBMS_OUTPUT.PUT_LINE(DBMS_SQL.GET_COL_NUMBER(l_cursor_id, 'JOB') || ': ' || DBMS_SQL.VARCHAR2S(DBMS_SQL.GET_COL_VALUE(l_cursor_id, 2)));
    END LOOP;
  END IF;
  DBMS_SQL.CLOSE_CURSOR(l_cursor_id);
END;

In the example above, the DBMS_SQL.OPEN_CURSOR procedure is used to open a cursor. The DBMS_SQL.PARSE procedure is used to parse the SQL statement. The DBMS_SQL.BIND_VARIABLE procedure is used to bind a variable to the SQL statement. The DBMS_SQL.DESCRIBE_COLUMNS procedure is used to describe the result set. The DBMS_SQL.EXECUTE procedure is used to execute the SQL statement. The DBMS_SQL.FETCH_ROWS function is used to fetch rows from the result set, and the DBMS_SQL.GET_COL_NUMBER and DBMS_SQL.GET_COL_VALUE functions are used to retrieve the column values. Finally, the DBMS_SQL.CLOSE_CURSOR procedure is used to close the cursor.

How do you use the DBMS_METADATA package in PL/SQL?

View answer

Hide answer

The DBMS_METADATA package in PL/SQL is used to retrieve metadata information about database objects. Here's an example of how to use the DBMS_METADATA package to retrieve the metadata for a table:

DECLARE
  l_metadata CLOB;
BEGIN
  l_metadata := DBMS_METADATA.GET_DDL('TABLE', 'EMP');
  DBMS_OUTPUT.PUT_LINE(l_metadata);
END;

In the example above, the DBMS_METADATA.GET_DDL function is used to retrieve the DDL for the EMP table. The first parameter specifies the type of object to retrieve, and the second parameter specifies the name of the object. The function returns a CLOB containing the DDL for the object, which is then output to the console using the DBMS_OUTPUT.PUT_LINE procedure.

Similarly, you can use other procedures and functions provided by the DBMS_METADATA package to retrieve metadata for other types of database objects, such as indexes, constraints, views, and procedures.

What is the difference between a procedure and a package in PL/SQL?

View answer

Hide answer

A procedure is a named block of code that performs a specific task, while a package is a collection of procedures, functions, variables, and other items that can be used by other programs. A package provides a modular structure for organizing and reusing code, while a procedure is a standalone unit of code.

Here's an example of a simple procedure:

CREATE OR REPLACE PROCEDURE print_message IS
BEGIN
  DBMS_OUTPUT.PUT_LINE('Hello, world!');
END;

And here's an example of a package that contains a procedure:

CREATE OR REPLACE PACKAGE my_package IS
  PROCEDURE print_message;
END my_package;

CREATE OR REPLACE PACKAGE BODY my_package IS
  PROCEDURE print_message IS
  BEGIN
    DBMS_OUTPUT.PUT_LINE('Hello, world from my_package!');
  END;
END my_package;

To use the procedure in the package, you would call it like this:

BEGIN
  my_package.print_message;
END;

How do you use the DBMS_APPLICATION_INFO package in PL/SQL?

View answer

Hide answer

The DBMS_APPLICATION_INFO package is used in PL/SQL to set and retrieve information about the currently executing application. It can be used to identify and track long-running or expensive queries, for example. To set the module and action information for the currently executing session, the SET_MODULE and SET_ACTION procedures can be used, like this:

BEGIN
  DBMS_APPLICATION_INFO.SET_MODULE('my_module', 'my_action');
END;

To retrieve the module and action information for the currently executing session, the GET_MODULE and GET_ACTION functions can be used, like this:

DECLARE
  l_module VARCHAR2(64);
  l_action VARCHAR2(64);
BEGIN
  DBMS_APPLICATION_INFO.GET_MODULE(l_module, l_action);
  DBMS_OUTPUT.PUT_LINE('Module: ' || l_module);
  DBMS_OUTPUT.PUT_LINE('Action: ' || l_action);
END;

What is the difference between a static and dynamic cursor in PL/SQL?

View answer

Hide answer

In PL/SQL, a cursor is a mechanism used to retrieve data from the database. There are two types of cursors - static and dynamic cursors.

A static cursor is a cursor that is bound to a specific SQL statement at compile-time. The result set for a static cursor is determined at the time the cursor is opened, and any changes made to the underlying data will not be reflected in the result set.

Here's an example of a static cursor:

DECLARE
  CURSOR c_emp IS
    SELECT empno, ename, sal
    FROM emp
    WHERE deptno = 10;
  emp_rec c_emp%ROWTYPE;
BEGIN
  OPEN c_emp;
  LOOP
    FETCH c_emp INTO emp_rec;
    EXIT WHEN c_emp%NOTFOUND;
    -- Process emp_rec
  END LOOP;
  CLOSE c_emp;
END;

A dynamic cursor, on the other hand, is a cursor whose SQL statement is determined at runtime. The result set for a dynamic cursor is determined each time the cursor is opened, so any changes made to the underlying data will be reflected in the result set.

Here's an example of a dynamic cursor:

DECLARE
  TYPE emp_curtype IS REF CURSOR;
  c_emp emp_curtype;
  emp_rec emp%ROWTYPE;
  v_deptno NUMBER := 10;
BEGIN
  OPEN c_emp FOR 'SELECT empno, ename, sal FROM emp WHERE deptno = :deptno' USING v_deptno;
  LOOP
    FETCH c_emp INTO emp_rec;
    EXIT WHEN c_emp%NOTFOUND;
    -- Process emp_rec
  END LOOP;
  CLOSE c_emp;
END;

In the example above, the SQL statement for the cursor is determined at runtime using a bind variable. This allows the same cursor to be reused with different values for the bind variable.

How do you use the DBMS_SCHEDULER package in PL/SQL?

View answer

Hide answer

The DBMS_SCHEDULER package in PL/SQL is used to schedule jobs and automate administrative tasks. The package can be used to create, modify, and delete jobs, as well as to start and stop them. Jobs can be scheduled to run at specific times or on specific intervals, and can be assigned to specific job classes and windows for better control and management. Here is an example of creating a job with DBMS_SCHEDULER:

BEGIN
  DBMS_SCHEDULER.CREATE_JOB(
    job_name        => 'my_job',
    job_type        => 'PLSQL_BLOCK',
    job_action      => 'BEGIN my_procedure(); END;',
    start_date      => SYSTIMESTAMP,
    repeat_interval => 'FREQ=DAILY; INTERVAL=1',
    enabled         => TRUE);
END;
/

This code creates a job called my_job that runs a PL/SQL block every day at a 1-day interval, starting from the current date and time. The job is enabled and will start running immediately after creation.

How do you use the UTL_HTTP package in PL/SQL?

View answer

Hide answer

The UTL_HTTP package is used to make HTTP requests from within PL/SQL code. It can be used to interact with web services, fetch web pages, and more. To use this package, you first need to open an HTTP connection, then use various subprograms to send and receive HTTP requests and responses. Here is an example code snippet that fetches the contents of a web page using UTL_HTTP:

DECLARE
   req UTL_HTTP.REQ;
   res UTL_HTTP.RESP;
   url VARCHAR2(4000) := 'http://www.example.com';
   buffer VARCHAR2(32767);
   amount NUMBER;
BEGIN
   req := UTL_HTTP.BEGIN_REQUEST(url);
   res := UTL_HTTP.GET_RESPONSE(req);
   LOOP
      UTL_HTTP.READ_LINE(res, buffer, TRUE);
      DBMS_OUTPUT.PUT_LINE(buffer);
   END LOOP;
   UTL_HTTP.END_RESPONSE(res);
EXCEPTION
   WHEN UTL_HTTP.END_OF_BODY THEN
      UTL_HTTP.END_RESPONSE(res);
END;

This code snippet opens a connection to http://www.example.com, sends an HTTP GET request, and then reads the response line-by-line and prints it to the console. If an error occurs, it catches the exception and closes the response.

What is the difference between a schema and a database user in PL/SQL?

View answer

Hide answer

In PL/SQL, a schema is a logical container that holds database objects such as tables, views, and procedures. A database user is an account that can connect to the database and access these objects. A user can have one or more schemas associated with it. The main difference between the two is that a schema is a collection of objects, while a user is an account that can access those objects.

For example, creating a schema in PL/SQL:

CREATE SCHEMA my_schema;

Creating a user in PL/SQL:

CREATE USER my_user IDENTIFIED BY my_password;

Assigning a schema to a user in PL/SQL:

ALTER USER my_user DEFAULT TABLESPACE my_schema;

How do you use the DBMS_SESSION package in PL/SQL?

View answer

Hide answer

In PL/SQL, the DBMS_SESSION package is used to set and manage session-level attributes. Here's an example of how to use the package to set a session-level parameter:

BEGIN
  DBMS_SESSION.SET_NLS('NLS_DATE_FORMAT', 'DD-MON-YYYY');
END;

In the example above, the SET_NLS procedure of the DBMS_SESSION package is used to set the NLS_DATE_FORMAT parameter to the value DD-MON-YYYY. This will affect the way that dates are displayed for the current session.

The DBMS_SESSION package also provides procedures for setting and getting the current schema, setting and getting the current module and action, and setting and getting the current client identifier, among other things. These session-level attributes can be used to customize the behavior of the current session, and can be useful in multi-user environments.

How do you use the DBMS_SQLDIAG package in PL/SQL?

View answer

Hide answer

In PL/SQL, the DBMS_SQLDIAG package is used for diagnosing and resolving SQL performance problems. It provides procedures for managing SQL Tuning Sets (STS), which are collections of SQL statements and execution statistics used for SQL tuning.

Here's an example of how to use the DBMS_SQLDIAG package to create an STS:

DECLARE
  l_sqlset_name VARCHAR2(30) := 'MY_SQLSET';
  l_sql_text    CLOB := 'SELECT * FROM my_table WHERE my_column = :1';
BEGIN
  DBMS_SQLDIAG.CREATE_SQLSET(l_sqlset_name);
  DBMS_SQLDIAG.LOAD_SQLSET(l_sqlset_name, l_sql_text);
END;

In the example above, the CREATE_SQLSET procedure is used to create an STS named MY_SQLSET, and the LOAD_SQLSET procedure is used to add the SQL statement specified in l_sql_text to the STS. This STS can then be used for SQL tuning operations, such as finding the best execution plan for the SQL statement.

The DBMS_SQLDIAG package also provides procedures for managing SQL Performance Analyzer (SPA) tasks, which can be used to compare the performance of different execution plans for a given SQL statement, among other things.

How do you use the DBMS_METADATA_DIFF package in PL/SQL?

View answer

Hide answer

The DBMS_METADATA_DIFF package in PL/SQL is used to compare two metadata objects and generate the DDL (Data Definition Language) needed to make them the same. The COMPARE procedure compares two metadata objects and returns a handle to the differences. The FETCH_* procedures fetch the next object difference from the handle. The COMPARE_AND_DIFFERENCES procedure compares two metadata objects and writes the differences to a specified buffer. The following example shows how to use DBMS_METADATA_DIFF package to compare two tables:

DECLARE
  diff_handle    NUMBER;
  num_diffs      INTEGER;
  diff_clob      CLOB;
BEGIN
  diff_handle := DBMS_METADATA_DIFF.COMPARE(
                    object_type => 'TABLE',
                    name1       => 'table1',
                    schema1     => 'schema1',
                    name2       => 'table2',
                    schema2     => 'schema2'
                 );
  num_diffs := DBMS_METADATA_DIFF.GET_NUM_DIFFS(diff_handle);
  DBMS_METADATA_DIFF.FETCH_CLOB(diff_handle, num_diffs, diff_clob);
  DBMS_OUTPUT.PUT_LINE(diff_clob);
END;
/

What is the difference between a materialized view and a summary table in PL/SQL?

View answer

Hide answer

In PL/SQL, a materialized view and a summary table serve a similar purpose of providing pre-computed results, but they differ in their implementation and usage.

A materialized view is a table that is pre-populated with results from a query, while a summary table is typically a regular table that is populated using INSERT, UPDATE, or DELETE statements based on the changes to the base table. Materialized views are typically used to improve the performance of frequently executed queries, while summary tables are used for more ad-hoc reporting or analysis.

Here's an example of creating a materialized view:

CREATE MATERIALIZED VIEW mv_sales_data
REFRESH FAST ON DEMAND
AS SELECT product_name, SUM(sales_amount) total_sales
FROM sales
GROUP BY product_name;

And here's an example of creating a summary table:

CREATE TABLE summary_sales_data
AS SELECT product_name, SUM(sales_amount) total_sales
FROM sales
GROUP BY product_name;

-- Update the summary table when the sales table changes
CREATE OR REPLACE TRIGGER tr_summary_sales_data
AFTER INSERT OR UPDATE OR DELETE ON sales
FOR EACH ROW
BEGIN
    IF INSERTING THEN
        -- Update the summary table with new data
        INSERT INTO summary_sales_data (product_name, total_sales)
        VALUES (:NEW.product_name, :NEW.sales_amount);
    ELSIF UPDATING THEN
        -- Update the summary table with changed data
        UPDATE summary_sales_data
        SET total_sales = total_sales - :OLD.sales_amount + :NEW.sales_amount
        WHERE product_name = :OLD.product_name;
    ELSIF DELETING THEN
        -- Update the summary table with deleted data
        UPDATE summary_sales_data
        SET total_sales = total_sales - :OLD.sales_amount
        WHERE product_name = :OLD.product_name;
    END IF;
END;
/```

How do you use the DBMS_PROFILER package in PL/SQL?

View answer

Hide answer

The DBMS_PROFILER package is used to profile PL/SQL code to determine its performance characteristics. The package can be used to identify performance bottlenecks in code, such as slow-running procedures or functions. To use the package, you need to enable profiling, run the code you want to profile, and then generate a report. Here's an example:

-- Enable profiling
EXEC DBMS_PROFILER.START_PROFILING('my_program');

-- Run the code you want to profile
BEGIN
  -- PL/SQL code goes here
END;

-- Generate a report
SELECT * FROM TABLE(DBMS_PROFILER.REPORT);

The report generated by DBMS_PROFILER shows details about the time spent executing each line of code, as well as other performance metrics. This information can be used to optimize the code for better performance.

What is the difference between a database trigger and a table trigger in PL/SQL?

View answer

Hide answer

A database trigger is a stored PL/SQL program that is executed automatically in response to a specific event that occurs in the database (such as a DDL statement). A table trigger is a stored PL/SQL program that is executed automatically in response to a specific event that occurs on a specific table (such as an INSERT, UPDATE or DELETE statement). In other words, a table trigger is associated with a specific table, while a database trigger is not.

Example of a table trigger:

CREATE OR REPLACE TRIGGER my_table_trigger
AFTER INSERT OR UPDATE OR DELETE ON my_table
FOR EACH ROW
BEGIN
   -- trigger logic here
END;
/

Example of a database trigger:

CREATE OR REPLACE TRIGGER my_database_trigger
AFTER DDL ON DATABASE
BEGIN
   -- trigger logic here
END;
/

How do you use the DBMS_DATAPUMP package in PL/SQL?

View answer

Hide answer

The DBMS_DATAPUMP package is used to move large amounts of data in and out of a database. Here's an example of how to use it to export data from a table:

DECLARE
  l_dp_handle NUMBER;
BEGIN
  l_dp_handle := DBMS_DATAPUMP.OPEN(
    operation => 'EXPORT',
    job_mode => 'TABLE',
    job_name => 'my_table_export'
  );
  DBMS_DATAPUMP.ADD_FILE(
    handle => l_dp_handle,
    filename => 'my_table_export.dmp',
    directory => 'MY_DIR',
    filetype => DBMS_DATAPUMP.KU$_FILE_TYPE_DUMP_FILE
  );
  DBMS_DATAPUMP.METADATA_FILTER(
    handle => l_dp_handle,
    name => 'TABLE_FILTER',
    value => 'IN(''MY_SCHEMA'',''MY_TABLE'')'
  );
  DBMS_DATAPUMP.START_JOB(l_dp_handle);
  DBMS_DATAPUMP.WAIT_FOR_JOB(l_dp_handle);
  DBMS_DATAPUMP.DETACH(l_dp_handle);
END;
/

This code exports the MY_TABLE table in the MY_SCHEMA schema to a file named my_table_export.dmp in the MY_DIR directory. The METADATA_FILTER procedure is used to specify which schema and table to export. The exported file can then be imported using the IMPDP command.

What is the difference between a weak and strong entity in PL/SQL?

View answer

Hide answer

In PL/SQL, a strong entity is an entity that can be uniquely identified by its attributes alone, whereas a weak entity is an entity that cannot be uniquely identified without considering its relationship with another entity.

For example, consider a database schema for a university. The entity "Student" can be uniquely identified by its student ID, but the entity "Course Enrollment" cannot be uniquely identified without considering its relationship with the entities "Student" and "Course". Therefore, "Student" is a strong entity and "Course Enrollment" is a weak entity.

Here's an example of creating a table for a strong entity "Student" and a table for a weak entity "Course Enrollment" in PL/SQL:

-- Strong Entity
CREATE TABLE Student (
  student_id   NUMBER PRIMARY KEY,
  name         VARCHAR2(50),
  address      VARCHAR2(100)
);

-- Weak Entity
CREATE TABLE Course_Enrollment (
  enrollment_id NUMBER PRIMARY KEY,
  student_id    NUMBER,
  course_code   VARCHAR2(10),
  enroll_date   DATE,
  FOREIGN KEY (student_id) REFERENCES Student(student_id)
);
Other Interview Questions

ReactJS

Business Analyst

Android

Javascript

Power BI Django .NET Core
Drupal TestNG C#
React Native SAS Kubernetes
Check Other Interview Questions
customers across world
Join 1200+ companies in 75+ countries.
Try the most candidate friendly skills assessment tool today.
GET STARTED FOR FREE
g2 badges
logo
40 min tests.
No trick questions.
Accurate shortlisting.

[email protected]

Product
  • Product Tour
  • Science
  • Pricing
  • Features
  • Integrations
  • AI Resume Parser
Usecases
  • Aptitude Tests
  • Coding Tests
  • Psychometric Tests
  • Personality Tests
Helpful Content
  • Skills assessment tools
  • 52 pre-employment tools compared
  • Compare Adaface
  • Compare Codility vs Adaface
  • Compare HackerRank vs Adaface
  • Compare Mettl vs Adaface
  • Online Compiler
BOOKS & TOOLS
  • Guide to pre-employment tests
  • Check out all tools
Company
  • About Us
  • Join Us
  • Blog
Locations
  • Singapore (HQ)

    32 Carpenter Street, Singapore 059911

    Contact: +65 9447 0488

  • India

    WeWork Prestige Atlanta, 80 Feet Main Road, Koramangala 1A Block, Bengaluru, Karnataka, 560034

    Contact: +91 6305713227

© 2023 Adaface Pte. Ltd.
Terms Privacy Trust Guide

🌎 Pick your language

English Norsk Dansk Deutsche Nederlands Svenska Français Español Chinese (简体中文) Italiano Japanese (日本語) Polskie Português Russian (русский)
Search 500+ tests by skill or role name
JavaScript
React
How many questions will be there in AWS test?
What test do you recommend for analysts?