PL/SQL interview questions and answers for Oracle developers
PL/SQL interview questions test whether you can write Oracle server-side code that is correct under errors and fast on large data: block structure, cursors, exception handling, procedures, functions and packages, triggers, and bulk processing with BULK COLLECT and FORALL. Interviewers also ask about autonomous transactions and the mutating table error because both expose how well you understand transactions. The strongest answers prefer one set-based SQL statement over a loop whenever possible.
By Evin JohnPublished 9 min read
Who gets PL/SQL questions
PL/SQL is Oracle's procedural language, so these questions come up for Oracle developers, database developers, ERP and banking back-office teams, and data engineers who maintain ETL inside the database. A PL/SQL developer interview usually starts with SQL (joins, analytic functions, execution plans), moves to writing a procedure or package on paper or in a shared editor, and ends with scenarios: a batch job that runs for hours, a trigger that fails, or an error log that shows nothing useful. Broader data rounds are in data engineer interview questions.
- SQL warm-upJoins, GROUP BY, analytic functions such as ROW_NUMBER and LAG, and reading an execution plan.
- PL/SQL conceptsBlocks, cursors, exceptions, packages, triggers, collections, often rapid-fire.
- Write codeA procedure that processes rows with error handling, or a package with a public API and private helpers.
- Tuning and designWhy a nightly job is slow, how to log errors, how to deploy package changes without breaking sessions.
PL/SQL fundamentals questions
DECLARE
v_salary employees.salary%TYPE;
BEGIN
SELECT salary
INTO v_salary
FROM employees
WHERE employee_id = 101;
DBMS_OUTPUT.PUT_LINE('Salary: ' || v_salary);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No employee with that id');
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('Employee id is not unique');
END;
/| Question | What it tests | What a strong answer shows |
|---|---|---|
| What are the sections of a PL/SQL block? | Structure | An optional DECLARE section, a required BEGIN ... END executable section, and an optional EXCEPTION section. Blocks can be anonymous or named (procedures, functions, packages, triggers) and can nest. |
| Why use %TYPE and %ROWTYPE? | Anchored types | The variable follows the column or row definition, so a widened column does not break the code with a value error. It also documents where the value comes from. |
| Implicit versus explicit cursor? | Cursors | Oracle opens an implicit cursor for each DML and SELECT INTO. An explicit cursor is declared, opened, fetched and closed by you, or driven by a cursor FOR loop that does all of that for you. |
| Which cursor attributes do you use? | Cursors | %FOUND, %NOTFOUND, %ROWCOUNT and %ISOPEN. After an UPDATE, SQL%ROWCOUNT tells you how many rows changed, which is how you detect an update that matched nothing. |
| What is a REF CURSOR? | Cursor variables | A pointer to a result set that can be opened for different queries and passed to a client or another program. SYS_REFCURSOR is the built-in weak type. |
| What are the collection types? | Collections | Associative arrays (INDEX BY) live only in PL/SQL and suit lookups. Nested tables and VARRAYs can also be SQL types stored in columns; a VARRAY has a maximum size. |
| DELETE versus TRUNCATE inside PL/SQL? | DML versus DDL | DELETE is DML, can be rolled back and fires triggers. TRUNCATE is DDL, commits implicitly, resets the high-water mark, and needs EXECUTE IMMEDIATE inside PL/SQL. |
| Can you COMMIT inside a trigger? | Transactions | Not in a normal trigger, because the trigger is part of the triggering statement's transaction. Only an autonomous transaction can commit independently, which is rarely the right answer. |
| What does a cursor FOR loop give you? | Idiom | It opens the cursor, fetches each row into an implicit record and closes the cursor even if the loop exits early. Oracle also fetches in batches behind the scenes in recent versions, so it is not as slow as a manual row-by-row fetch. |
Exception handling questions
- Name some predefined exceptions. NO_DATA_FOUND, TOO_MANY_ROWS, ZERO_DIVIDE, DUP_VAL_ON_INDEX, VALUE_ERROR and INVALID_NUMBER. Each maps to an ORA error number, for example DUP_VAL_ON_INDEX to ORA-00001.
- How do you raise your own error to the caller? RAISE_APPLICATION_ERROR with a number from -20000 to -20999 and a message. The client sees a normal Oracle error it can handle.
- What does PRAGMA EXCEPTION_INIT do? It binds a name to an Oracle error number that has no predefined name, so you can write WHEN deadlock_detected THEN instead of checking SQLCODE.
- Why is WHEN OTHERS THEN NULL a red flag? It swallows every error, so the transaction may continue in a broken state and nobody learns why. Log the error and re-raise with RAISE.
- How do you log where an error really happened? Capture SQLERRM together with DBMS_UTILITY.FORMAT_ERROR_BACKTRACE, which gives the line that raised it, then re-raise.
- How do exceptions propagate? An unhandled exception leaves the current block and goes to the enclosing block, then to the caller. An error in the DECLARE section is raised to the enclosing block, not handled by the same block's handler.
- What happens to the transaction when an exception is unhandled? The failed statement is rolled back. If the exception reaches the client unhandled, the work the call did is rolled back as well, while work committed earlier stays committed.
Procedures, functions, packages and triggers
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Procedure versus function? | Program units | A function returns one value and can be called inside SQL if it follows the purity rules (for example, no DML when called from a query). A procedure returns data through OUT parameters and is called as a statement. |
| IN, OUT and IN OUT parameters? | Parameters | IN is read-only, OUT is written by the procedure, IN OUT is both. Large OUT collections are copied by default; NOCOPY is a hint to pass by reference. |
| Why put code in a package? | Packages | A spec as the public API and a body for the implementation, private helpers, overloading, shared types and constants, and fewer invalidations: changing only the body does not invalidate callers. |
| What is package state, and what is ORA-04068? | Session state | Package-level variables live for the session. Recompiling a package discards that state for sessions that used it, and their next call fails with ORA-04068. Stateless packages avoid it. |
| Row-level versus statement-level triggers? | Triggers | A row trigger fires once per affected row and can read :OLD and :NEW. A statement trigger fires once per statement, even for zero rows. |
| What is an INSTEAD OF trigger? | Triggers | A trigger on a view that replaces the DML, used to make a complex view updatable. |
| What is the mutating table error (ORA-04091)? | Trigger limits | A row-level trigger queried or changed the table that is being modified, whose state is mid-change. The usual fixes are a compound trigger that collects keys per row and acts after the statement, or moving the rule into the procedure that does the DML. |
| Definer rights versus invoker rights? | Security | By default code runs with the owner's privileges. AUTHID CURRENT_USER runs it with the caller's privileges and name resolution, useful for shared utilities. |
CREATE OR REPLACE TRIGGER trg_emp_payroll_budget
FOR INSERT OR UPDATE OF salary, department_id ON employees
COMPOUND TRIGGER
TYPE t_dept_ids IS TABLE OF employees.department_id%TYPE;
g_depts t_dept_ids := t_dept_ids();
AFTER EACH ROW IS
BEGIN
IF :NEW.department_id IS NOT NULL THEN
g_depts.EXTEND;
g_depts(g_depts.LAST) := :NEW.department_id;
END IF;
END AFTER EACH ROW;
AFTER STATEMENT IS
l_total NUMBER;
l_budget departments.payroll_budget%TYPE;
BEGIN
FOR i IN 1 .. g_depts.COUNT LOOP
SELECT NVL(SUM(e.salary), 0), d.payroll_budget
INTO l_total, l_budget
FROM departments d
LEFT JOIN employees e ON e.department_id = d.department_id
WHERE d.department_id = g_depts(i)
GROUP BY d.payroll_budget;
IF l_total > l_budget THEN
RAISE_APPLICATION_ERROR(-20010,
'Payroll over budget for department ' || g_depts(i));
END IF;
END LOOP;
END AFTER STATEMENT;
END trg_emp_payroll_budget;
/Bulk processing and autonomous transaction questions
Every row-by-row loop that runs SQL switches between the PL/SQL engine and the SQL engine on each iteration. BULK COLLECT fetches many rows per switch, and FORALL sends a whole collection of DML in one. Interviewers expect you to know both, to use LIMIT so memory stays flat, and to handle rows that fail without losing the rest. They also expect you to say that a single INSERT ... SELECT beats both when the logic fits in SQL.
DECLARE
CURSOR c_orders IS
SELECT order_id
FROM orders
WHERE status = 'SHIPPED'
AND archived = 'N';
TYPE t_ids IS TABLE OF orders.order_id%TYPE;
l_ids t_ids;
bulk_errors EXCEPTION;
PRAGMA EXCEPTION_INIT(bulk_errors, -24381);
BEGIN
OPEN c_orders;
LOOP
FETCH c_orders BULK COLLECT INTO l_ids LIMIT 1000;
EXIT WHEN l_ids.COUNT = 0; -- not c_orders%NOTFOUND, which would skip the last partial batch
BEGIN
FORALL i IN 1 .. l_ids.COUNT SAVE EXCEPTIONS
INSERT INTO orders_archive (order_id) VALUES (l_ids(i));
EXCEPTION
WHEN bulk_errors THEN
FOR j IN 1 .. SQL%BULK_EXCEPTIONS.COUNT LOOP
log_error(l_ids(SQL%BULK_EXCEPTIONS(j).ERROR_INDEX),
SQLERRM(-SQL%BULK_EXCEPTIONS(j).ERROR_CODE));
END LOOP;
END;
END LOOP;
CLOSE c_orders;
COMMIT;
END;
/CREATE OR REPLACE PROCEDURE log_error (
p_ref_id IN NUMBER,
p_message IN VARCHAR2
) AS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO error_log (logged_at, ref_id, message)
VALUES (SYSTIMESTAMP, p_ref_id, SUBSTR(p_message, 1, 4000));
COMMIT; -- commits only this insert, not the caller's work
END log_error;
/- Why LIMIT on BULK COLLECT? Without it the whole result set lands in session memory at once. A limit in the hundreds or low thousands keeps memory bounded with most of the speed gain.
- What does SAVE EXCEPTIONS change? FORALL keeps going after a failing row, then raises ORA-24381 at the end. SQL%BULK_EXCEPTIONS lists the index and error code of each failure.
- What is an autonomous transaction and when is it right? A routine with its own transaction, independent of the caller. Error logging and audit trails are the classic legitimate uses. Using one to dodge the mutating table error usually hides a design problem and can read inconsistent data.
- What must an autonomous routine do before it returns? Commit or roll back. Returning with pending changes raises an error and rolls them back.
- Why commit once at the end rather than inside the loop? Fewer commits are faster, the job is restartable as one unit, and committing while a cursor stays open over a changing table raises the risk of ORA-01555 snapshot too old.
Performance and senior PL/SQL questions
| Scenario | Likely cause | What to say you would check |
|---|---|---|
| A nightly job that loops over a million rows takes hours. | Row-by-row processing | Rewrite as set-based SQL (INSERT ... SELECT, MERGE) where the logic allows; otherwise BULK COLLECT with LIMIT and FORALL. Profile with DBMS_HPROF to find where time goes. |
| A report query slowed down after a PL/SQL function was added to its WHERE clause. | Function per row | The function runs once per row and switches context each time. Inline the logic in SQL, use a scalar subquery so results can be cached, or mark it DETERMINISTIC or RESULT_CACHE where valid. |
| Dynamic SQL is built by concatenating user input. | SQL injection and parsing | Use EXECUTE IMMEDIATE with USING bind variables, validate identifiers with DBMS_ASSERT, and note that binds also let Oracle reuse the parsed statement. |
| The error log says only "ORA-06512 at line 1". | Lost context | Handlers that re-raise without logging the backtrace. Log FORMAT_ERROR_BACKTRACE in the outermost handler. |
| Deploying a package fix breaks connected application sessions. | Package state | Global variables in the package. Remove session state, or use edition-based redefinition for zero-downtime changes. |
| Two sessions deadlock during a batch update. | Lock order | Rows locked in different orders by concurrent jobs. Process keys in a consistent order and keep transactions short. |
- MERGE or separate INSERT and UPDATE? MERGE does an upsert in one statement and one pass over the source, which beats a loop with exception handling around each insert.
- What is native compilation? Compiling PL/SQL to machine code with PLSQL_CODE_TYPE set to NATIVE. It helps compute-heavy logic, not code that mostly waits on SQL.
- How do you unit test PL/SQL? A framework such as utPLSQL, with tests that set up data, call the unit, assert results and roll back.
- How do you pass a result set to a Java or .NET application? A SYS_REFCURSOR OUT parameter, or a pipelined table function when the caller should query it with SQL.
Fictional example
- Interviewer
- A row-level trigger on employees checks that a department's total salary stays under budget, and it fails with a mutating table error on updates. How do you fix it?
- Candidate
- The trigger reads employees while a statement on employees is still changing it, so Oracle refuses because the table is mid-change. I would not reach for an autonomous transaction, because that reads the committed data and misses the rows this statement is changing. Instead I would use a compound trigger: in the after-each-row section, store the department ids touched, and in the after-statement section, when the table is consistent, sum salaries per stored department and raise an application error if any is over budget. If the rule only matters through one API, I might move the check into that package instead, so it is visible and testable. Either way I would add tests for a single-row update and a bulk update that crosses departments.
PL/SQL practice plan
- Day 1: write blocks with SELECT INTO, both exceptions, %TYPE and %ROWTYPE, and a cursor FOR loop; explain each cursor attribute.
- Day 2: build a small package with a public procedure, a private helper and an error logging routine; recompile it while a second session holds state.
- Day 3: time the same archive job three ways: row by row, BULK COLLECT with FORALL, and one INSERT ... SELECT.
- Day 4: reproduce ORA-04091 with a row trigger and fix it with a compound trigger.
- Day 5: practice reading an execution plan and explaining where the PL/SQL and SQL engines switch, then do a timed mock.
PL/SQL roles often sit next to reporting and application work. Power BI interview questions covers the reporting layer many Oracle shops feed, Django interview questions covers a common application stack on top of a relational database, and data analyst interview questions goes deeper on analytical SQL.
Exception-handling answers sound fine in your head and muddled out loud. Natively, an AI interview assistant for Mac and Windows, transcribes a mock PL/SQL round on your computer, so afterward you can check whether you said "log the backtrace and re-raise" or only "handle the error". In practice it can read a procedure or an ORA error stack from a screenshot and suggest a fix, and with Pro or the free trial it can lean on your résumé and the job description you add. Every transcript and set of notes is kept for review.
Questions people ask
What PL/SQL questions are asked in interviews?
Expect block structure, implicit and explicit cursors, exception handling with RAISE_APPLICATION_ERROR, procedures versus functions, packages, triggers, the mutating table error, BULK COLLECT with FORALL, autonomous transactions and tuning a slow batch job.
What is the difference between a procedure and a function in PL/SQL?
A function returns a single value and can be called from SQL when it follows the purity rules. A procedure is called as a statement and returns data through OUT parameters.
How do you fix the mutating table error?
Avoid querying the table being changed from a row-level trigger. Use a compound trigger that records keys per row and does the check after the statement, or move the rule into the procedure that performs the DML.
When should I use BULK COLLECT and FORALL?
When logic cannot be written as one SQL statement and you process many rows. BULK COLLECT with LIMIT fetches in batches and FORALL sends DML in batches, cutting switches between the PL/SQL and SQL engines.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
