Sub topic 1
Anatomy of a PL/SQL block
PL/SQL code is organized into blocks. Every program you write, from a ten-line script to a package with thousands of lines, is built from them. This chapter covers the parts of a block, the order in which they run, and the errors you will hit most often when you start writing them.
Prerequisites
This chapter assumes you can do the following:
- Write basic SQL: SELECT, INSERT, UPDATE, and DELETE statements.
- Recognize Oracle data types such as NUMBER, VARCHAR2, and DATE.
- Run statements in SQL*Plus, SQL Developer, or SQLcl.
- Query a sample table, such as HR.EMPLOYEES, in a schema you can access.
The chapter does not assume any earlier PL/SQL experience.
The working model
A PL/SQL block has up to three sections and a terminator:
| Section | Keyword | Required | Purpose |
|---|---|---|---|
| Declaration | `DECLARE` | No | Defines variables, constants, and other local items |
| Executable | `BEGIN` | Yes | Holds the statements that do the work |
| Exception | `EXCEPTION` | No | Handles runtime errors raised in the executable section |
| Terminator | `END;` | Yes | Closes the block |
The skeleton looks like this:
DECLARE
-- declarations (optional)
BEGIN
-- statements (at least one required)
EXCEPTION
-- handlers (optional)
END;The sections must appear in this order. The executable section needs at least one statement. If you have nothing to put there yet, use the NULL; statement, which does nothing.
Every statement inside a block ends with a semicolon, including the final END;. A block is one statement from the point of view of the PL/SQL engine, so the semicolon after END closes the whole block.
A first complete block
This block uses all three sections. It divides two numbers and handles the failure case.
SET SERVEROUTPUT ON
DECLARE
v_dividend NUMBER := 10;
v_divisor NUMBER := 0;
v_result NUMBER;
BEGIN
v_result := v_dividend / v_divisor;
DBMS_OUTPUT.PUT_LINE('Result: ' || v_result);
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('Cannot divide by zero.');
END;
/Running it prints Cannot divide by zero.. The division raises the predefined exception ZERO_DIVIDE. The PUT_LINE call on the next line never runs. Control jumps straight to the exception section.
Change v_divisor to 4 and the exception section is skipped. The block prints Result: 2.5.
The lone / on the last line is not PL/SQL. It is a client command that tells SQL*Plus, SQLcl, or SQL Developer to send the buffered block to the database. Without it, the client keeps waiting for more input.
How a block runs
The database runs a block top to bottom. It first processes the declaration section, then the executable section. If a statement in the executable section raises an exception, the database stops that section and looks for a matching handler in the exception section.
Two details matter here:
- After a handler finishes, the block ends. Execution does not return to the statement that failed.
- If no handler matches, the exception propagates outward. The client sees an unhandled error, such as
ORA-01476: divisor is equal to zero.
The declaration section
The DECLARE keyword starts the declaration section. Everything declared here is local to the block and disappears when the block ends. This section is optional. A block that needs no variables starts directly with BEGIN:
SET SERVEROUTPUT ON
BEGIN
DBMS_OUTPUT.PUT_LINE('No declarations needed.');
END;
/Later chapters cover declarations in detail, including data types, constants, NOT NULL, and the %TYPE and %ROWTYPE attributes. For now, remember that an item must be declared before you use it. PL/SQL reads declarations in order, so a variable cannot refer to one declared below it.
The executable section
The BEGIN keyword starts the only mandatory section. It can contain:
- Assignments, such as
v_total := v_price * 2; - SQL statements, such as
SELECT ... INTO,INSERT,UPDATE,DELETE, andMERGE - Control structures such as
IFand loops - Calls to procedures and functions, including
DBMS_OUTPUT.PUT_LINE - Other blocks, nested inside this one
You can also put transaction control statements such as COMMIT and ROLLBACK here. A block that runs DML does not commit on its own. The changes belong to your session's open transaction until you commit or roll back.
DDL statements such as CREATE TABLE cannot appear directly in the executable section. They require dynamic SQL, which this tutorial does not cover.
The exception section
The EXCEPTION keyword starts a list of handlers. Each handler is a WHEN clause that names one or more exceptions, followed by statements:
SET SERVEROUTPUT ON
DECLARE
v_text VARCHAR2(10) := 'abc';
v_num NUMBER;
BEGIN
v_num := TO_NUMBER(v_text);
EXCEPTION
WHEN INVALID_NUMBER OR VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('Not a number: ' || v_text);
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Unexpected error: ' || SQLERRM);
END;
/In a PL/SQL assignment, a failed TO_NUMBER conversion raises VALUE_ERROR (ORA-06502). The same conversion inside a SQL statement raises INVALID_NUMBER (ORA-01722). Listing both with OR covers each case.
WHEN OTHERS matches any exception not named earlier, so it must come last. The function SQLERRM returns the text of the current error message.
Errors in the declaration section are not caught by the same block
The exception section handles only errors raised in the executable section of its own block. An error raised while the database processes a declaration skips that block's handlers. The next block out must catch it.
SET SERVEROUTPUT ON
BEGIN
DECLARE
v_code VARCHAR2(3) := 'too long for this variable';
BEGIN
DBMS_OUTPUT.PUT_LINE(v_code);
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 output is Outer handler caught the declaration error. The initial value does not fit in VARCHAR2(3), so the error occurs during declaration. The inner EXCEPTION section is never consulted.
Anonymous and named blocks
All the blocks above are anonymous blocks. They have no name, they are not stored in the database, and they are compiled each time you run them. Anonymous blocks suit scripts, tests, and one-off tasks.
A named block has a header before the declaration section. In a stored procedure, the header replaces the DECLARE keyword:
CREATE OR REPLACE PROCEDURE say_hello AS
v_message VARCHAR2(50) := 'Hello from a stored procedure';
BEGIN
DBMS_OUTPUT.PUT_LINE(v_message);
END say_hello;
/The body has the same declaration, executable, and exception structure. Everything you learn about blocks applies to named blocks too. A later chapter in this tutorial compares the two kinds in more detail.
Common errors
These are the mistakes learners hit most often with block structure.
- Missing slash. The client appears to hang or shows a line number prompt. Add
/on its own line afterEND;. - Empty executable section. A block with
BEGIN END;fails withPLS-00103. Add a statement, or useNULL;. - No output. If the block runs but prints nothing, run
SET SERVEROUTPUT ONfirst. This is a client setting, not part of the block. - Semicolon after the last handler's
ENDmissing.ENDwithout;leaves the block unterminated. - Stray semicolon after
DECLARE,BEGIN, orEXCEPTION. These keywords are not statements, so they take no semicolon. A semicolon afterBEGINcauses a compile error. - Wrong section order. Putting
EXCEPTIONbefore the executable statements, or declarations afterBEGIN, fails to compile. - Handler assumed to resume. After a handler runs, the block ends. Code placed after the failing statement does not run.
Summary of the structure
A block is declarations, then statements, then handlers, closed by END;. Only the statements are mandatory. Exceptions flow from the executable section to the handlers of the same block, and then outward if unhandled. Errors in declarations flow outward directly. The rest of this tutorial builds on this skeleton by filling in the declaration section with variables and constants, and by loading them from tables with SELECT INTO.
Exercise
The block below is meant to print the text "Done" even when a conversion fails. It does not compile. Find the problems and write the corrected block. DECLARE vtext VARCHAR2(10) := 'xyz'; vnum NUMBER; BEGIN; vnum := TONUMBER(vtext); EXCEPTION WHEN VALUEERROR THEN DBMSOUTPUT.PUTLINE('Done'); END
Show answer
There are two problems. First, BEGIN must not be followed by a semicolon. Second, the final END needs a semicolon, and the block needs a / line to run in a client. A corrected block:
SET SERVEROUTPUT ON
DECLARE
vtext VARCHAR2(10) := 'xyz';
vnum NUMBER;
BEGIN
vnum := TONUMBER(vtext);
EXCEPTION
WHEN VALUEERROR THEN
DBMSOUTPUT.PUTLINE('Done');
END;
/
It prints "Done", because the failed conversion raises VALUE_ERROR and the handler runs.
Exercise
A block declares v_flag VARCHAR2(1) := 'yes'; and has a WHEN VALUE_ERROR handler in its own EXCEPTION section. Does the handler run? Explain.
Show answer
No. The initial value 'yes' is three characters, which does not fit in VARCHAR2(1), so the error is raised while the declaration is processed. A block's exception section handles only errors from its own executable section. The error propagates to the enclosing block or to the caller. To catch it, enclose the block in an outer block with a handler, or assign the value in the executable section.