Variables & Constants


Variables

Variables in Oracle PL/SQL are named storage locations that hold a single value. These values can change during the execution of a PL/SQL block. They are essential for temporary data storage, calculations, and manipulating data within your programs. When working with PL/SQL, effective variable management is key to writing clean and performant code.

 

Example 1: Declaring a Simple Numeric Variable

DECLARE
    -- Declaring a numeric variable to store an employee ID
    -- This is a basic example suitable for beginners in Oracle PL/SQL.
    employee_id NUMBER(6);
BEGIN
    -- Assigning a value to the employee_id variable
    employee_id := 101;

    -- Displaying the value using DBMS_OUTPUT.PUT_LINE
    -- DBMS_OUTPUT is commonly used for debugging and displaying output in PL/SQL.
    DBMS_OUTPUT.PUT_LINE('Employee ID: ' || employee_id);
END;
/

Explanation This beginner-friendly example demonstrates the basic syntax for declaring a numeric variable, employee_id, with a precision of 6 digits. We then assign the value 101 to it using the assignment operator := and display its content using DBMS_OUTPUT.PUT_LINE. This is a fundamental concept for anyone learning Oracle PL/SQL programming.

 

Example 2: Declaring a VARCHAR2 Variable and String Concatenation

DECLARE
    -- Declaring a variable to store an employee's first name
    first_name VARCHAR2(50);
    -- Declaring a variable to store an employee's last name
    last_name  VARCHAR2(50);
    -- Declaring a variable to store the full name
    full_name  VARCHAR2(100);
BEGIN
    -- Assigning values to the name variables
    first_name := 'John';
    last_name  := 'Doe';

    -- Concatenating strings to form the full name
    -- The || operator is used for string concatenation in PL/SQL.
    full_name  := first_name || ' ' || last_name;

    -- Displaying the full name
    DBMS_OUTPUT.PUT_LINE('Full Name: ' || full_name);
END;
/

Explanation This example introduces the VARCHAR2 data type, commonly used for storing character strings in Oracle PL/SQL. It illustrates how to declare two VARCHAR2 variables, assign string values, and then concatenate them using the || operator to create a full_name variable. This is a common operation in PL/SQL development for handling textual data.

 

Example 3: Using a BOOLEAN Variable for Conditional Logic

DECLARE
    -- Declaring a BOOLEAN variable to check if a condition is met
    is_active BOOLEAN := TRUE;
    -- Declaring a numeric variable for demonstration
    user_status NUMBER := 1;
BEGIN
    -- Using an IF-THEN-ELSE statement with the BOOLEAN variable
    -- Conditional logic is fundamental in PL/SQL for controlling program flow.
    IF is_active THEN
        DBMS_OUTPUT.PUT_LINE('User is currently active.');
    ELSE
        DBMS_OUTPUT.PUT_LINE('User is inactive.');
    END IF;

    -- Demonstrating another scenario where a BOOLEAN might be set based on a condition
    IF user_status = 1 THEN
        is_active := TRUE;
    ELSE
        is_active := FALSE;
    END IF;

    IF is_active THEN
        DBMS_OUTPUT.PUT_LINE('User status determined as active.');
    ELSE
        DBMS_OUTPUT.PUT_LINE('User status determined as inactive.');
    END IF;
END;
/

Explanation This example showcases the BOOLEAN data type, which can store only TRUE, FALSE, or NULL. It demonstrates how BOOLEAN variables are invaluable for implementing conditional logic (IF-THEN-ELSE statements) within your PL/SQL programs, a core concept for decision-making in programming. This helps in writing dynamic PL/SQL code.

 

Example 4: Advanced Variable Declaration and Initialization with a Query

DECLARE
    -- Declaring a variable to hold an employee's salary, initialized using a SELECT INTO statement
    -- This technique is common for retrieving data from tables directly into variables.
    employee_salary NUMBER(8, 2);
    -- Declaring a variable to hold the employee's department name
    department_name VARCHAR2(100);
BEGIN
    -- Retrieving the salary for a specific employee ID directly into the variable
    -- This demonstrates using SQL within PL/SQL to populate variables.
    SELECT salary
    INTO employee_salary
    FROM employees
    WHERE employee_id = 100; -- Assuming employee_id 100 exists in your HR schema

    DBMS_OUTPUT.PUT_LINE('Employee Salary for ID 100: ' || employee_salary);

    -- Retrieving the department name for a specific department ID
    SELECT department_name
    INTO department_name
    FROM departments
    WHERE department_id = 10; -- Assuming department_id 10 exists

    DBMS_OUTPUT.PUT_LINE('Department Name for ID 10: ' || department_name);

EXCEPTION
    WHEN NO_DATA_FOUND THEN
        DBMS_OUTPUT.PUT_LINE('No data found for the specified ID.');
    WHEN TOO_MANY_ROWS THEN
        DBMS_OUTPUT.PUT_LINE('Multiple rows found for the specified ID. Please refine your query.');
    WHEN OTHERS THEN
        DBMS_OUTPUT.PUT_LINE('An unexpected error occurred: ' || SQLERRM);
END;
/

Explanation This advanced example demonstrates initializing variables using SELECT INTO statements, a powerful feature for retrieving data from Oracle database tables directly into PL/SQL variables. It also includes basic exception handling (NO_DATA_FOUND, TOO_MANY_ROWS, OTHERS), which is critical for robust PL/SQL application development. This is a common practice for data manipulation in PL/SQL.

 

Example 5: Using Variables in Dynamic SQL (Advanced)

DECLARE
    -- Variable to hold the table name
    table_name VARCHAR2(30) := 'EMPLOYEES';
    -- Variable to hold the column name for which we want to count rows
    column_name VARCHAR2(30) := 'EMPLOYEE_ID';
    -- Variable to store the count of rows
    row_count NUMBER;
    -- Variable to construct the dynamic SQL statement
    sql_stmt   VARCHAR2(200);
BEGIN
    -- Constructing a dynamic SQL statement to count rows
    -- Dynamic SQL is used when the SQL statement is not known until runtime.
    sql_stmt := 'SELECT COUNT(' || column_name || ') FROM ' || table_name;

    -- Executing the dynamic SQL statement using EXECUTE IMMEDIATE
    -- EXECUTE IMMEDIATE is a powerful feature for flexible PL/SQL programming.
    EXECUTE IMMEDIATE sql_stmt INTO row_count;

    DBMS_OUTPUT.PUT_LINE('Number of rows in ' || table_name || ' based on ' || column_name || ': ' || row_count);

    -- Another example: Dynamic update
    DECLARE
        emp_id NUMBER := 100;
        new_salary NUMBER := 7000;
        update_stmt VARCHAR2(200);
    BEGIN
        update_stmt := 'UPDATE EMPLOYEES SET SALARY = :new_sal WHERE EMPLOYEE_ID = :emp_id';
        EXECUTE IMMEDIATE update_stmt USING new_salary, emp_id;
        DBMS_OUTPUT.PUT_LINE('Updated salary for employee ' || emp_id || ' to ' || new_salary);
    END;

EXCEPTION
    WHEN OTHERS THEN
        DBMS_OUTPUT.PUT_LINE('Error in dynamic SQL: ' || SQLERRM);
END;
/

Explanation This advanced example dives into dynamic SQL using EXECUTE IMMEDIATE. It demonstrates how variables can be used to construct and execute SQL statements at runtime, providing immense flexibility for tasks like schema introspection or generalized data manipulation. This is an advanced PL/SQL concept, crucial for building highly adaptable applications. We also show how to use bind variables (:new_sal, :emp_id) with EXECUTE IMMEDIATE for secure and efficient execution.


 

Constants

Constants in Oracle PL/SQL are similar to variables, but their values are fixed and cannot be changed after they are declared. They are used for values that remain constant throughout the execution of a PL/SQL program, such as mathematical constants, fixed rates, or configuration parameters. Using constants makes your code more readable, maintainable, and less prone to errors.

 

Example 1: Declaring a Simple Numeric Constant

DECLARE
    -- Declaring a constant for the maximum number of attempts
    -- Constants improve code readability and maintainability.
    MAX_ATTEMPTS CONSTANT NUMBER := 3;
BEGIN
    -- Displaying the constant value
    DBMS_OUTPUT.PUT_LINE('Maximum Login Attempts Allowed: ' || MAX_ATTEMPTS);

    -- Attempting to change a constant will result in a compilation error.
    -- MAX_ATTEMPTS := 5; -- This line would cause a PL/SQL compilation error.
END;
/

Explanation This example demonstrates the declaration of a simple numeric constant, MAX_ATTEMPTS. The CONSTANT keyword ensures that its value cannot be modified after initialization. This is a fundamental concept for beginners learning how to define fixed values in Oracle PL/SQL.

 

Example 2: Declaring a String Constant

DECLARE
    -- Declaring a constant for the application version string
    -- String constants are useful for fixed labels or version numbers.
    APP_VERSION CONSTANT VARCHAR2(10) := '1.0.0';
BEGIN
    -- Displaying the application version
    DBMS_OUTPUT.PUT_LINE('Application Version: ' || APP_VERSION);
END;
/

Explanation This example illustrates the declaration of a VARCHAR2 constant, APP_VERSION. String constants are frequently used for storing fixed labels, messages, or version numbers, making your PL/SQL code more robust and consistent.

 

Example 3: Using a Boolean Constant

DECLARE
    -- Declaring a boolean constant to indicate if debugging is enabled
    -- Boolean constants are great for toggling features like debugging.
    DEBUG_MODE_ENABLED CONSTANT BOOLEAN := TRUE;
BEGIN
    -- Using the boolean constant in a conditional statement
    IF DEBUG_MODE_ENABLED THEN
        DBMS_OUTPUT.PUT_LINE('Debugging mode is currently active.');
        -- In a real application, this would trigger more verbose logging.
    ELSE
        DBMS_OUTPUT.PUT_LINE('Debugging mode is inactive.');
    END IF;
END;
/

Explanation This example demonstrates the use of a BOOLEAN constant, DEBUG_MODE_ENABLED. Boolean constants are excellent for controlling program flow, enabling or disabling features like debugging or logging, leading to more manageable PL/SQL applications.

 

Example 4: Constants for Mathematical Values (Advanced)

DECLARE
    -- Declaring a constant for the mathematical value of PI
    -- Using constants for mathematical values ensures precision and consistency.
    PI CONSTANT NUMBER := 3.14159265358979323846;
    -- Variable to store the radius
    radius NUMBER := 5;
    -- Variable to store the area of a circle
    circle_area NUMBER;
BEGIN
    -- Calculating the area of a circle using the PI constant
    circle_area := PI * radius * radius;
    DBMS_OUTPUT.PUT_LINE('Radius: ' || radius);
    DBMS_OUTPUT.PUT_LINE('Area of Circle: ' || circle_area);

    -- Example with another constant
    DECLARE
        GRAVITY_CONSTANT CONSTANT NUMBER := 9.80665; -- Acceleration due to gravity in m/s^2
        mass NUMBER := 10; -- kg
        force_due_to_gravity NUMBER;
    BEGIN
        force_due_to_gravity := mass * GRAVITY_CONSTANT;
        DBMS_OUTPUT.PUT_LINE('Force due to gravity for ' || mass || ' kg: ' || force_due_to_gravity || ' Newtons');
    END;
END;
/

Explanation This advanced example shows how to declare and use a constant for a mathematical value like PI. Employing constants for such values ensures accuracy and consistency throughout your PL/SQL programs, which is vital for scientific or engineering calculations. It also demonstrates nesting blocks for scope management.

 

Example 5: Using Constants in Package Specifications (Advanced)

-- Package Specification (mypackage.pks)
-- This file defines the public interface of the package.
-- Package constants provide a centralized location for shared values.

CREATE OR REPLACE PACKAGE my_constants_pkg AS
    -- Public constant for maximum allowed salary
    MAX_SALARY CONSTANT NUMBER := 150000;
    -- Public constant for standard tax rate
    STANDARD_TAX_RATE CONSTANT NUMBER := 0.20;
    -- Public constant for a default status message
    DEFAULT_STATUS_MESSAGE CONSTANT VARCHAR2(50) := 'Processing Complete';
END my_constants_pkg;
/

-- Package Body (mypackage.pkb) - for demonstration of usage
-- This file contains the implementation of the package's procedures and functions.
CREATE OR REPLACE PACKAGE BODY my_constants_pkg AS
    -- No implementation needed for simple constants in the body, but could contain procedures/functions
    -- that use these constants.
END my_constants_pkg;
/

-- Anonymous PL/SQL Block to demonstrate using constants from the package
DECLARE
    employee_pay NUMBER := 160000;
    tax_amount NUMBER;
BEGIN
    -- Accessing constants defined in the package
    DBMS_OUTPUT.PUT_LINE('Maximum Allowed Salary: ' || my_constants_pkg.MAX_SALARY);

    IF employee_pay > my_constants_pkg.MAX_SALARY THEN
        DBMS_OUTPUT.PUT_LINE('Warning: Employee pay exceeds maximum allowed salary.');
    END IF;

    tax_amount := employee_pay * my_constants_pkg.STANDARD_TAX_RATE;
    DBMS_OUTPUT.PUT_LINE('Tax amount for ' || employee_pay || ': ' || tax_amount);
    DBMS_OUTPUT.PUT_LINE('Default Message: ' || my_constants_pkg.DEFAULT_STATUS_MESSAGE);
END;
/

Explanation This advanced example demonstrates declaring constants within an Oracle PL/SQL package specification. This approach provides a centralized, global access point for shared constant values across multiple PL/SQL procedures, functions, and forms, promoting code reusability and maintainability in large-scale applications. This is a best practice for managing application-wide constants.