Skip to main content

PL/SQL Anonymous Block 🏗️

Mentor's Note: A PL/SQL "Block" is the basic unit of code. It's like a container. An Anonymous Block is a one-time script that isn't saved in the database. It's perfect for testing or simple automation. 💡


🌟 The Scenario: The Recipe Card 📝

Imagine you are writing a recipe on a sticky note.

  • Header: You list your ingredients (DECLARE). 🥣
  • Body: You write the step-by-step cooking instructions (BEGIN). 🍳
  • Footer: You write what to do if the cake burns (EXCEPTION). 🧯
  • End: You mark the card as finished.

🎨 Visual Logic: The Block Blueprint


💻 1. The Structure

SectionKeywordPurpose
DeclarationDECLAREDefine variables and constants.
ExecutionBEGINThe actual logic and SQL commands.
ExceptionEXCEPTIONHandle errors gracefully.
EndEND;Marks the end of the block.

💻 2. Basic Example

SET SERVEROUTPUT ON; -- 💡 MANDATORY to see output!

DECLARE
v_message VARCHAR2(50) := 'Hello PL/SQL';
BEGIN
DBMS_OUTPUT.PUT_LINE(v_message);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Something went wrong!');
END;
/

🗝️ Key Syntax Notes:

  1. Semicolons: Every statement inside the block must end with a ;.
  2. The Forward Slash /: In tools like SQL*Plus or SQL Developer, you must put a / on a new line after END; to tell Oracle to "Execute this block now."

🏗️ Architect's Note: Scope & Nesting 🛡️

You can nest blocks inside other blocks!

  • Scope: Variables declared in the outer block are visible to the inner block.
  • Isolation: Variables in the inner block are hidden from the outer block.
  • Tip: Use nesting to isolate risky logic inside its own EXCEPTION handler without stopping the main program.

📈 Learning Path

📍 Visit Us

🏫 VD Computer Tuition Surat

VD Computer Tuition
📍 Address
2/66 Faram Street, Rustompura
Surat395002, Gujarat, India
📞 Phone / WhatsApp
+91 84604 41384
🌐 Website

Computer Classes & Tuition — Areas We Serve in Surat

AdajanAlthanAmroliAthwaAthwalinesBhagalBhatarBhestanCanal RoadChowkCitylightDumasGaurav PathGhod Dod RoadHaziraJahangirpuraKamrejKapodraKatargamLimbayatMagdallaMajura GateMota VarachhaNanpuraNew CitylightOlpadPalPandesaraParle PointPiplodPunaRanderRing RoadRustampuraSachinSalabatpuraSarthanaSosyo CircleUdhnaVarachhaVed RoadVesuVIP Road
📞 Call Sir💬 WhatsApp Sir