Stored Procedures, Functions & Packages

Stored Procedures, Functions & Packages in Oracle Database: PL/SQL (Procedural Language for SQL) executes directly inside the database kernel.

PL/SQL (Procedural Language for SQL) executes directly inside the database kernel. It combines the declarative power of SQL with procedural loops, conditions, and custom error-handling constructs.


Procedures vs Functions

  • Stored Procedures: Designed to perform business actions, mutate data, and return zero or multiple values via OUT parameters.
  • Functions: Designed to compute and return a single scalar or collection value. Can be invoked directly within SQL statements if they adhere to purity rules (no side-effect DML when called from SELECT).
-- Pure deterministic function callable in high-speed SQL
CREATE OR REPLACE FUNCTION calculate_tier_discount (
    p_customer_id IN NUMBER,
    p_gross_amt   IN NUMBER
) RETURN NUMBER DETERMINISTIC IS
    v_total_spend NUMBER;
    v_discount    NUMBER := 0;
BEGIN
    SELECT COALESCE(SUM(order_total), 0)
    INTO v_total_spend
    FROM orders
    WHERE customer_id = p_customer_id 
      AND status = 'COMPLETED';

    IF v_total_spend > 100000 THEN
        v_discount := p_gross_amt * 0.15;
    ELSIF v_total_spend > 25000 THEN
        v_discount := p_gross_amt * 0.08;
    ELSE
        v_discount := 0;
    END IF;

    RETURN ROUND(v_discount, 2);
EXCEPTION
    WHEN NO_DATA_FOUND THEN
        RETURN 0;
    WHEN OTHERS THEN
        -- Re-raise or log through an autonomous transaction
        RAISE_APPLICATION_ERROR(-20001, 'Failed calculating tier discount: ' || SQLERRM);
END calculate_tier_discount;
/

Package Encapsulation (Specification vs Body)

In professional Oracle development, standalone procedures and functions are discouraged. Production logic is organized into Packages.

A Package consists of two separate database objects:

  1. Package Specification: The public contract exposing types, constants, variables, procedures, and functions.
  2. Package Body: The private implementation containing internal helper functions, algorithms, and SQL cursors.
-- 1. PACKAGE SPECIFICATION (Public Contract)
CREATE OR REPLACE PACKAGE banking_service AS
    -- Public constants and types
    c_max_daily_limit CONSTANT NUMBER := 50000.00;
    
    -- Public API procedures
    PROCEDURE transfer_funds (
        p_from_acc  IN NUMBER,
        p_to_acc    IN NUMBER,
        p_amount    IN NUMBER,
        p_txn_ref   OUT VARCHAR2
    );
    
    FUNCTION get_account_balance (p_acc_id IN NUMBER) RETURN NUMBER;
END banking_service;
/

-- 2. PACKAGE BODY (Implementation Details)
CREATE OR REPLACE PACKAGE BODY banking_service AS
    -- Private helper procedure (inaccessible to outside callers)
    PROCEDURE log_transfer_audit (p_from NUMBER, p_to NUMBER, p_amt NUMBER) IS
    BEGIN
        INSERT INTO transfer_audit_log (from_acc, to_acc, amount, logged_at)
        VALUES (p_from, p_to, p_amt, SYSTIMESTAMP);
    END log_transfer_audit;

    PROCEDURE transfer_funds (
        p_from_acc  IN NUMBER,
        p_to_acc    IN NUMBER,
        p_amount    IN NUMBER,
        p_txn_ref   OUT VARCHAR2
    ) IS
        v_curr_bal NUMBER;
    BEGIN
        IF p_amount <= 0 OR p_amount > c_max_daily_limit THEN
            RAISE_APPLICATION_ERROR(-20002, 'Transfer amount violates limits.');
        END IF;

        -- Lock source row for update to prevent concurrent race conditions
        SELECT balance INTO v_curr_bal
        FROM accounts WHERE account_id = p_from_acc FOR UPDATE;

        IF v_curr_bal < p_amount THEN
            RAISE_APPLICATION_ERROR(-20003, 'Insufficient funds for transfer.');
        END IF;

        UPDATE accounts SET balance = balance - p_amount WHERE account_id = p_from_acc;
        UPDATE accounts SET balance = balance + p_amount WHERE account_id = p_to_acc;

        log_transfer_audit(p_from_acc, p_to_acc, p_amount);
        p_txn_ref := 'TXN-' || SYS_GUID();
        COMMIT;
    END transfer_funds;

    FUNCTION get_account_balance (p_acc_id IN NUMBER) RETURN NUMBER IS
        v_bal NUMBER;
    BEGIN
        SELECT balance INTO v_bal FROM accounts WHERE account_id = p_acc_id;
        RETURN v_bal;
    END get_account_balance;
END banking_service;
/

Exercises

  1. Create a package specification and body for inventory_manager managing product restocks and reservations with transaction rollback on error.
  2. What are the advantages of packages over standalone procedures regarding schema invalidation and dependency management?
  3. Use PRAGMA UDF to optimize a PL/SQL function called from inside a high-volume SQL SELECT query.