Sub topic 4
The Declaration Section
This chapter assumes you can run SQL in SQL*Plus, SQL Developer, or SQLcl. It also assumes you know basic Oracle data types and can use the HR sample schema. You should already know the four parts of a PL/SQL block. Here the focus is the first part: what can go in the declaration section, in what order, when it runs, and how it fails.
What the declaration section is
The declaration section is the optional first part of a block. It names every item the block will use before the executable section starts. Those items exist only while the block runs, and they are visible only inside it and in blocks nested within it.
In an anonymous block, the section starts with the keyword DECLARE and ends at BEGIN. In a named block, such as a procedure or function, there is no DECLARE. The section starts right after IS or AS:
CREATE OR REPLACE PROCEDURE show_name (p_id IN NUMBER) IS
v_name employees.last_name%TYPE;
BEGIN
SELECT last_name INTO v_name FROM employees WHERE employee_id = p_id;
DBMS_OUTPUT.PUT_LINE(v_name);
END show_name;
/If a block has nothing to declare, leave out DECLARE entirely. An empty DECLARE followed directly by BEGIN is a syntax error.
What you can declare
Each declaration ends with a semicolon. You can declare several kinds of items:
| Item | Example | Notes |
|---|---|---|
| Variable | `v_count NUMBER := 0;` | Holds a value that can change. |
| Constant | `c_rate CONSTANT NUMBER := 0.07;` | Must be initialized and cannot be reassigned. |
| Exception | `e_bad_input EXCEPTION;` | A user-defined error name that you raise yourself. |
| Cursor | `CURSOR c_d IS SELECT ...;` | A named query, covered in a later chapter. |
| Type | `TYPE t_names IS TABLE OF ...;` | A collection or record type local to the block. |
| Subprogram | `FUNCTION f ... IS ...` | A procedure or function local to the block. |
The next block declares one of each kind and runs as written:
SET SERVEROUTPUT ON
DECLARE
c_max_raise CONSTANT NUMBER := 0.10;
v_emp_id NUMBER(6) := 100;
v_hired DATE := SYSDATE;
v_label VARCHAR2(30) DEFAULT 'unknown';
e_bad_input EXCEPTION;
CURSOR c_depts IS
SELECT department_id FROM departments;
TYPE t_names IS TABLE OF VARCHAR2(30) INDEX BY PLS_INTEGER;
v_names t_names;
FUNCTION double_it (p_n NUMBER) RETURN NUMBER IS
BEGIN
RETURN p_n * 2;
END double_it;
BEGIN
v_names(1) := 'Ada';
DBMS_OUTPUT.PUT_LINE(v_label || ', ' || v_names(1) || ', '
|| double_it(v_emp_id));
END;
/The output is unknown, Ada, 200. Most of the declared items go unused, and PL/SQL does not complain about that. Note that DEFAULT is a synonym for := in a declaration.
Ordering rules
- Declare a name before you use it. Every item can refer only to items declared above it.
- Put subprograms after all other declarations. A variable declared below a local function is a syntax error.
- Declare one item per statement.
v_a, v_b NUMBER;is not valid. Write two declarations.
A later declaration can build on an earlier one:
DECLARE
v_base NUMBER := 10;
v_double NUMBER := v_base * 2;
BEGIN
DBMS_OUTPUT.PUT_LINE(v_double);
END;
/This prints 20. If you swap the two declarations, compilation fails with PLS-00201: identifier 'V_BASE' must be declared.
When declarations run
Oracle processes the declaration section when control enters the block, before the first statement in BEGIN. This is called elaboration. It does two things:
- It allocates each item.
- It evaluates each initial value expression, in the order written, from top to bottom.
Items without an initial value start as NULL. Constants and NOT NULL variables must have one.
Elaboration happens every time the block is entered, not once. An inner block inside a loop re-initializes its variables on every pass:
SET SERVEROUTPUT ON
BEGIN
FOR i IN 1 .. 2 LOOP
DECLARE
v_count NUMBER := 0;
BEGIN
v_count := v_count + 1;
DBMS_OUTPUT.PUT_LINE('Pass ' || i || ': ' || v_count);
END;
END LOOP;
END;
/The output is Pass 1: 1 and Pass 2: 1. The counter does not accumulate, because a fresh v_count is created on each pass. If you need state that survives between calls, declare the variable in an enclosing block or in a package (a later topic).
The following diagram shows the sequence when a block starts.
Errors in the declaration section
A block's EXCEPTION section protects only the executable section. If a declaration raises an error, such as a value too large for its variable, the handler in the same block does not run. The error goes to the enclosing block.
SET SERVEROUTPUT ON
BEGIN
DECLARE
v_small VARCHAR2(3) := 'Too long';
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');
END;
/This prints outer handler. The assignment fails with ORA-06502, which maps to VALUE_ERROR, while the inner block is still elaborating its declarations. A top-level anonymous block has no enclosing block, so the same mistake there ends with an unhandled error returned to the client.
Naming declared items
Identifiers follow the same rules as in SQL. They must start with a letter and can be up to 128 bytes. They can include _, $, and #. They are not case-sensitive unless you use double quotes, which you should avoid. Do not use reserved words such as DATE or LOOP.
Variable names that match column names
Inside a SQL statement in PL/SQL, a name that matches both a column and a variable resolves to the column. This produces silent bugs:
SET SERVEROUTPUT ON
DECLARE
last_name employees.last_name%TYPE := 'King';
v_count NUMBER;
BEGIN
SELECT COUNT(*)
INTO v_count
FROM employees
WHERE last_name = last_name;
DBMS_OUTPUT.PUT_LINE('Matches: ' || v_count);
END;
/The condition last_name = last_name compares the column to itself, so it is true for every row with a non-null name. The block counts all of those rows instead of only those named King. The fix is a naming convention that cannot collide with column names:
| Kind | Prefix | Example |
|---|---|---|
| Local variable | `v_` | `v_last_name` |
| Constant | `c_` | `c_tax_rate` |
| Parameter | `p_` | `p_employee_id` |
| User-defined exception | `e_` | `e_bad_input` |
| Cursor | `c_` or `cur_` | `c_depts` |
Naming the block with a label and qualifying the variable, as in <<main>> ... main.last_name, also resolves the conflict. Prefixes are simpler and catch the problem before it happens.
Style that keeps declarations readable
- Group related items together: constants first, then variables, then types and cursors, then subprograms.
- Give each declaration its own line, and align the data types.
- Prefer a named constant over a literal repeated in the code. Changing
c_tax_rateonce is safer than finding every0.075.
Common mistakes
| Symptom | Cause | Fix |
|---|---|---|
| `PLS-00201: identifier ... must be declared` | Used before declaration, misspelled, or declared in another block. | Move the declaration up or into an enclosing block. |
| `PLS-00103: Encountered the symbol ...` near a declaration | Missing semicolon, two items in one declaration, or an empty `DECLARE`. | Declare one item per statement and drop an empty `DECLARE`. |
| `PLS-00322: declaration of a constant must contain an initialization assignment` | A `CONSTANT` with no value. | Add `:= value`. |
| `PLS-00218: a variable declared NOT NULL must have an initialization assignment` | A `NOT NULL` variable with no value. | Add an initial value. |
| `ORA-06502: PL/SQL: numeric or value error` at block start | An initial value does not fit the declared type or size. | Widen the type or fix the value. The error appears in the enclosing block. |
| A query returns too many rows or wrong results | A variable name matches a column name. | Use a naming prefix. |
Summary of the model
The declaration section is a list of named items, each ending in a semicolon. Oracle evaluates the list top to bottom every time the block is entered. An item can use only what appears above it, and subprograms come last. Errors raised while evaluating the list escape to the enclosing block, because the block's own handler covers only the executable section.
Exercise
A block declares v_total NUMBER := v_price * 2; on the line above v_price NUMBER := 50;. What happens, and what two changes could fix it?
Show answer
Compilation fails with PLS-00201 because v_price is used before it is declared. Fix it by moving the v_price declaration above v_total. Alternatively, declare v_total NUMBER; with no value and assign v_total := v_price * 2; in the executable section.
Exercise
In the block below, which handler runs, and what is printed? DECLARE vcode VARCHAR2(2) := 'ABC'; BEGIN NULL; EXCEPTION WHEN OTHERS THEN DBMSOUTPUT.PUT_LINE('handled here'); END; /
Show answer
No handler in this block runs. The initial value is too long for VARCHAR2(2), so ORA-06502 is raised during elaboration of the declaration section, and a block's own EXCEPTION section does not cover its declarations. There is no enclosing block, so the error is returned unhandled to the client and nothing is printed.
Exercise
Why does a variable named salary cause problems in SELECT ... FROM employees WHERE salary > salary, and how do you avoid it?
Show answer
Inside a SQL statement, a name that matches both a column and a variable resolves to the column, so the condition compares the column with itself. Avoid it by prefixing variable names, for example v_salary, or by qualifying the variable with a block label.