Introduction
PL/SQL code always runs inside a block.
Once you understand this structure, it becomes much easier to read and write code.
The Basic Structure
DECLARE
-- variables
BEGIN
-- main logic
EXCEPTION
-- error handling
END;
Each section has a purpose.
What Each Part Does
`DECLARE` is used to define variables. This section is optional.
`BEGIN` is where the code actually runs. This part is required.
`EXCEPTION` handles errors if something goes wrong. This section is also optional.
Example
SET SERVEROUTPUT ON;
DECLARE
v_name VARCHAR2(20);
BEGIN
SELECT first_name INTO v_name FROM employees WHERE employee_id = 100;
DBMS_OUTPUT.PUT_LINE('Name: ' || v_name);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Something went wrong');
END;
/
Why This Structure Matters
Without structure, code becomes harder to follow and maintain.
With blocks:
- logic is organized
- errors are handled
- code is easier to debug
In Real Systems
If errors are not handled properly:
- systems may crash
- incorrect data may be used
- internal details may be exposed
Using blocks helps prevent that by keeping everything controlled.
Conclusion
PL/SQL blocks are simple but very important.
They keep your code structured, readable, and predictable.