Skip to content

PL/SQL GOTO & Labels ‴️

Mentor's Note: GOTO is the "Teleportation" command of PL/SQL. It lets you jump from one part of the code directly to another. But be warned: too much teleporting makes your code very confusingβ€”this is known as "Spaghetti Code". 🍝 πŸ’‘


🌟 The Scenario: The Emergency Exit πŸšͺ

Imagine you are walking through a maze. - Usually, you follow the paths (IF, Loops). - GOTO: You see an "Emergency Exit" sign and jump straight out of the maze to the finish line, skipping everything else.


πŸ’» 1. Basic Syntax

You must define a Label using double angle brackets << >>.

DECLARE
   v_num NUMBER := 1;
BEGIN
   IF v_num = 1 THEN
      GOTO my_shortcut; -- πŸš€ Jump to label
   END IF;

   DBMS_OUTPUT.PUT_LINE('This line will be skipped!');

   <<my_shortcut>> -- πŸ“ The target label
   DBMS_OUTPUT.PUT_LINE('We arrived at the shortcut!');
END;

πŸ›‘ 2. Important Restrictions (Architect's Note)

You cannot jump anywhere you want. There are strict rules: 1. No Jumping In: You cannot jump from outside into an IF statement or a LOOP. 2. No Jumping Out: You cannot jump from an EXCEPTION handler back into the main BEGIN block. 3. Labels need code: A label must be followed by at least one executable statement (like NULL;).


πŸ—οΈ Architect's Advice: Avoid GOTO πŸ›‘οΈ

In 99% of cases, you can use IF, CASE, or LOOP instead of GOTO. - The Problem: GOTO makes it hard to track the flow of data. If you have 10 labels jumping around, debugging becomes a nightmare. - Tip: Only use GOTO if it significantly simplifies a very complex piece of logic that nothing else can solve.


πŸ“ˆ Learning Path