Sub topic 9
Nested blocks, scope, and shadowing
This chapter explains where a PL/SQL variable can be seen and how Oracle picks a variable when two have the same name. It assumes you can write an anonymous block with DECLARE, BEGIN, EXCEPTION, and END. It also assumes you can declare variables and assign to them with := and SELECT INTO. All examples use SET SERVEROUTPUT ON and the HR sample schema.
Blocks inside blocks
The executable section of a block can contain other complete blocks. The nested block is called an inner block or sub-block, and the block around it is the enclosing or outer block. Nesting has no fixed depth limit in practice. You can nest a block anywhere a statement is allowed.
SET SERVEROUTPUT ON
DECLARE
v_counter NUMBER := 0;
BEGIN
v_counter := v_counter + 1;
BEGIN
v_counter := v_counter + 10;
END;
DBMS_OUTPUT.PUT_LINE('Counter: ' || v_counter);
END;
/This prints Counter: 11. The inner block has no declaration section of its own. It uses v_counter from the outer block and changes it. That change persists after the inner block ends, because both blocks refer to the same variable.
The scope rule
The scope of a variable is the region of code where you can refer to it by its simple name. Two rules define it:
- A variable is visible in the block where it is declared and in every block nested inside that block.
- A variable is not visible in the enclosing block or in sibling blocks.
Information flows inward only. An inner block can read and write outer variables. An outer block cannot see what the inner block declared.
SET SERVEROUTPUT ON
BEGIN
DECLARE
v_inner NUMBER := 5;
BEGIN
DBMS_OUTPUT.PUT_LINE('Inside: ' || v_inner);
END;
-- v_inner is out of scope here
DBMS_OUTPUT.PUT_LINE('Outside: ' || v_inner);
END;
/This block does not compile. Oracle reports ORA-06550 together with PLS-00201: identifier 'V_INNER' must be declared. The check happens at compile time, so nothing runs, not even the first PUT_LINE.
Shadowing
If an inner block declares a name that an outer block already uses, the inner declaration shadows the outer one. Inside the inner block, the simple name refers to the inner variable. The outer variable still exists and keeps its value, but you cannot reach it by its simple name.
SET SERVEROUTPUT ON
DECLARE
v_level VARCHAR2(10) := 'outer';
BEGIN
DECLARE
v_level VARCHAR2(10) := 'inner';
BEGIN
DBMS_OUTPUT.PUT_LINE(v_level);
END;
DBMS_OUTPUT.PUT_LINE(v_level);
END;
/The output is inner, then outer. The two variables are separate objects. Assigning to the inner v_level never changes the outer one.
Shadowing is legal but easy to misuse. A common bug looks like this: you intend to update the outer variable, but you accidentally redeclare it in the inner block. The inner assignment then changes only the local copy, and the outer value stays the same with no error or warning. Use distinct names, or a naming convention such as v_ for variables and p_ for parameters, to make accidental shadowing unlikely.
Reaching a shadowed variable with a label
You can give a block a label, written between double angle brackets before DECLARE or BEGIN. A label lets you qualify a variable name as label.variable. This reaches an outer variable that an inner one has hidden.
SET SERVEROUTPUT ON
<<outer_block>>
DECLARE
v_level VARCHAR2(10) := 'outer';
BEGIN
DECLARE
v_level VARCHAR2(10) := 'inner';
BEGIN
DBMS_OUTPUT.PUT_LINE('Simple name: ' || v_level);
DBMS_OUTPUT.PUT_LINE('Qualified name: ' || outer_block.v_level);
END;
END;
/This prints inner for the simple name and outer for outer_block.v_level. Qualification works in the other direction too. You can write outer_block.v_level even when nothing is shadowed, which makes the intent explicit.
Lifetime: variables are created on entry
Scope is about where a name is visible. Lifetime is about when the variable exists. A block's variables are created and initialized each time execution enters the block, and they are released when it exits. A block inside a loop therefore starts fresh on every pass:
SET SERVEROUTPUT ON
BEGIN
FOR i IN 1 .. 3 LOOP
DECLARE
v_count NUMBER := 0;
BEGIN
v_count := v_count + 1;
DBMS_OUTPUT.PUT_LINE('Pass ' || i || ': v_count = ' || v_count);
END;
END LOOP;
END;
/Every pass prints v_count = 1. If you moved the declaration of v_count outside the loop, the value would grow to 1, 2, and 3. Declaring a variable in an inner block is a simple way to guarantee a clean initial state.
Name capture in SQL statements
Shadowing also occurs between PL/SQL variables and table columns. Inside a SQL statement embedded in PL/SQL, Oracle resolves a name against the tables in the statement first. Only if no column matches does it look for a PL/SQL variable. A variable that has the same name as a column is therefore silently ignored.
SET SERVEROUTPUT ON
DECLARE
last_name VARCHAR2(25) := 'King';
v_count NUMBER;
BEGIN
SELECT COUNT(*)
INTO v_count
FROM employees
WHERE last_name = last_name;
DBMS_OUTPUT.PUT_LINE('Matching rows: ' || v_count);
END;
/You might expect the number of employees named King. Both sides of the comparison resolve to the column, so the condition is true for every row with a non-null last_name. The query counts all of them, 107 in the standard HR schema.
The same mistake in a DELETE or UPDATE would change every row. A label on the block fixes this, because you can qualify the variable:
SET SERVEROUTPUT ON
<<main>>
DECLARE
last_name VARCHAR2(25) := 'King';
v_count NUMBER;
BEGIN
SELECT COUNT(*)
INTO v_count
FROM employees e
WHERE e.last_name = main.last_name;
DBMS_OUTPUT.PUT_LINE('Matching rows: ' || v_count);
END;
/Now the column is qualified with the table alias e, and the variable with the block label main. The count is the number of employees named King, 2 in the standard HR data. The simpler habit is to avoid the problem with a prefix such as v_ on every variable, so a variable never has the same name as a column.
Scope and exception handling
Each block has its own exception section, so nesting lets you contain an error where it happens and keep the outer block running. This is a common use of nested blocks together with SELECT INTO:
SET SERVEROUTPUT ON
DECLARE
v_last_name employees.last_name%TYPE;
v_found BOOLEAN := TRUE;
BEGIN
BEGIN
SELECT last_name
INTO v_last_name
FROM employees
WHERE employee_id = -1;
EXCEPTION
WHEN NO_DATA_FOUND THEN
v_found := FALSE;
END;
IF v_found THEN
DBMS_OUTPUT.PUT_LINE('Found: ' || v_last_name);
ELSE
DBMS_OUTPUT.PUT_LINE('No such employee, continuing.');
END IF;
END;
/The inner block handles NO_DATA_FOUND and records the result in the outer variable v_found. Execution then continues after the inner END;. Without the inner handler, the exception would leave the outer block and skip the rest of its statements.
Two rules govern where an exception goes:
- If the inner block has no matching handler, the exception propagates to the enclosing block's exception section. If that block has no handler either, it keeps propagating outward.
- An exception raised in a block's declaration section is not handled by that same block's exception section. It propagates to the enclosing block.
The second rule surprises many people. The following example shows it:
SET SERVEROUTPUT ON
BEGIN
DECLARE
v_code VARCHAR2(3) := 'ABCDEF';
BEGIN
NULL;
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('Inner handler');
END;
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('Outer handler caught the declaration error');
END;
/The initial value is too long for VARCHAR2(3), so VALUE_ERROR (ORA-06502) is raised while the inner block is being set up. The inner handler never runs. The output is Outer handler caught the declaration error.
Summary of the rules
| Situation | Result |
|---|---|
| Inner block uses an outer variable | Allowed. Changes are visible to the outer block |
| Outer block uses an inner variable | Compile error `PLS-00201` |
| Inner block declares a name used by the outer block | Inner shadows outer for the inner block's extent |
| Need the shadowed outer variable | Qualify it with a block label |
| Variable name equals a column name in a SQL statement | The column wins |
| Error raised in a declaration section | Handled by the enclosing block, not the same block |
Exercise
A block declares v_total NUMBER := 10;. An inner block declares v_total NUMBER := 99; and then runs v_total := v_total + 1;. After the inner block ends, the outer block prints v_total. What does it print, and how could the inner block change the outer variable instead?
Show answer
It prints 10. The inner assignment changes only the inner variable, which shadows the outer one. To change the outer variable, label the outer block (for example <<outer_block>>) and assign to outer_block.v_total in the inner block, or drop the inner declaration so the name refers to the outer variable.
Exercise
In a block with v_name VARCHAR2(30) := 'Kochhar';, you run SELECT COUNT(*) INTO v_count FROM employees WHERE last_name = v_name; and get the expected count. A colleague renames the variable to last_name and the count jumps to 107. Why, and what are two ways to prevent it?
Show answer
Inside a SQL statement, a name that matches a column resolves to the column. After the rename, last_name = last_name compares the column with itself, which is true for every row. Prevent it by keeping a prefix such as v_ on variables, or by qualifying both sides, for example e.last_name = main.last_name with a table alias and a block label.
Exercise
An inner block has v_code VARCHAR2(3) := 'ABCDEF'; and its own WHEN VALUE_ERROR handler. Which handler runs, and why?
Show answer
The handler in the enclosing block runs, if it has one. An exception raised in a block's declaration section is not caught by that block's own exception section. It propagates outward.