Skip to content
Home Database PL/SQL Variables, Constants and Data Types

PL/SQL Variables, Constants and Data Types

Where developers are forged. · Structured learning · Free forever.
📍 Part of: PL/SQL → Topic 2 of 27
Master PL/SQL foundational building blocks including variables, constants, %TYPE, and %ROWTYPE for robust Oracle Database development.
🧑‍💻 Beginner-friendly — no prior Database experience needed
In this tutorial, you'll learn
Master PL/SQL foundational building blocks including variables, constants, %TYPE, and %ROWTYPE for robust Oracle Database development.
  • PL/SQL Variables, Constants and Data Types is a core concept in PL/SQL that every Database developer should understand to write resilient code.
  • Always understand the problem a tool solves before learning its syntax: variables solve for storage, while anchored types solve for schema dependency.
  • Start with simple scalar variables before graduating to complex records and collections.
✦ Plain-English analogy ✦ Real code with output ✦ Interview questions
Quick Answer

Think of PL/SQL Variables, Constants and Data Types as a powerful tool in your developer toolkit. Once you understand what it does and when to reach for it, everything clicks into place. Imagine you are running a professional kitchen. A 'Variable' is like a prep bowl where you store chopped onions temporarily before adding them to the pot. A 'Constant' is like a standardized measuring cup—its size never changes and everyone relies on it for accuracy. 'Data Types' are the labels on your storage containers (e.g., 'Liquid', 'Dry Goods', 'Perishable') that ensure you don't accidentally try to store a gallon of milk in a paper bag.

PL/SQL Variables, Constants and Data Types is a fundamental concept in Database development. In PL/SQL, every piece of information must be held in a named storage location with a specific format. By mastering these building blocks, you can create programs that are not only functional but also highly maintainable and less prone to data-related errors.

In this guide we'll break down exactly what PL/SQL Variables, Constants and Data Types is, why it was designed this way to ensure strict data integrity within the Oracle engine, and how to use it correctly in real projects.

By the end you'll have both the conceptual understanding and practical code examples to use PL/SQL Variables, Constants and Data Types with confidence.

What Is PL/SQL Variables, Constants and Data Types and Why Does It Exist?

PL/SQL Variables, Constants and Data Types is a core feature of PL/SQL. It was designed to solve the problem of temporary data storage during procedural execution. Unlike standard SQL, which processes sets of data, PL/SQL needs a way to hold individual values, calculation results, and database records in memory. Variables allow for dynamic changes, while Constants protect values that must remain fixed (like a tax rate or API version). Data types (Scalar, Large Object, Composite, and Reference) exist to tell the compiler how much memory to allocate and what operations are valid on that data.

ForgeVariableBasics.sql · SQL
1234567891011121314151617181920212223
-- io.thecodeforge: Standard Variable and Constant Declaration
DECLARE
    -- Scalar Variable
    v_employee_name VARCHAR2(100) := 'TheCodeForge Developer';
    
    -- Constant: Must be initialized and cannot be changed
    gc_tax_rate CONSTANT NUMBER(3,2) := 0.05;
    
    -- Anchored Type: Dynamically matches the column type in the DB
    v_project_id forge_projects.project_id%TYPE;
    
    -- Rowtype: Holds an entire row from a table
    v_project_rec forge_projects%ROWTYPE;
BEGIN
    v_project_id := 101;
    
    -- Selective Assignment
    SELECT * INTO v_project_rec 
    FROM forge_projects 
    WHERE project_id = v_project_id;

    DBMS_OUTPUT.PUT_LINE('Processing: ' || v_project_rec.project_name);
END;
▶ Output
Processing: Forge Core API
💡Key Insight:
The most important thing to understand about PL/SQL Variables, Constants and Data Types is the problem it was designed to solve. Always ask 'why does this exist?' before asking 'how do I use it?' Use anchored types (%TYPE) as much as possible to ensure your code remains 'linked' to your database schema changes.

Common Mistakes and How to Avoid Them

When learning PL/SQL Variables, Constants and Data Types, most developers hit the same set of gotchas. A frequent mistake is hard-coding variable lengths (e.g., VARCHAR2(20)) instead of using %TYPE. If the database column later expands to 50 characters, your code will throw a 'Value Error'. Another common error is failing to initialize variables, leading to unexpected NULL logic in calculations.

Knowing these in advance saves hours of debugging production 'Buffer Overflow' and 'Constraint Violation' errors.

CommonMistakes.sql · SQL
123456789101112131415
-- io.thecodeforge: Avoiding hard-coded data types
-- WRONG: Risk of ORA-06502 if the DB column expands
-- v_name VARCHAR2(10);

-- CORRECT: Using %TYPE to stay synchronized
DECLARE
    v_forge_user_name forge_users.username%TYPE;
    v_current_total   NUMBER(10,2) := 0.00; -- Initialize to avoid NULL arithmetic
BEGIN
    SELECT username INTO v_forge_user_name 
    FROM forge_users 
    WHERE user_id = 1;
    
    v_current_total := v_current_total + 150.50;
END;
▶ Output
// Variable v_forge_user_name automatically adopts the DB column width.
⚠ Watch Out:
The most common mistake with PL/SQL Variables, Constants and Data Types is using it when a simpler alternative would work better. Avoid creating 'Global' variables in package specifications unless they truly need to persist across the session, as this can lead to memory bloat and difficult-to-trace state changes.
FeatureVariableConstantAnchored Type (%TYPE)
Value ModificationCan be updated anytimeImmutable once declaredDepends on usage
InitializationOptional (Defaults to NULL)MandatoryOptional
MaintenanceManual updates requiredSingle point of changeAutomatic via Schema
ScopeLocal or GlobalLocal or GlobalLinked to DB Object
Best Use CaseCounters, flags, temp dataConfiguration, Pi, Tax ratesDatabase data retrieval

🎯 Key Takeaways

  • PL/SQL Variables, Constants and Data Types is a core concept in PL/SQL that every Database developer should understand to write resilient code.
  • Always understand the problem a tool solves before learning its syntax: variables solve for storage, while anchored types solve for schema dependency.
  • Start with simple scalar variables before graduating to complex records and collections.
  • Read the official documentation — it contains edge cases tutorials skip, such as the maximum size of a PL/SQL VARCHAR2 (32,767 bytes) vs. a SQL VARCHAR2.

⚠ Common Mistakes to Avoid

    Overusing PL/SQL Variables, Constants and Data Types when a simpler approach would work — such as declaring individual variables for 20 columns instead of using a single %ROWTYPE variable.

    E variable.

    Not understanding the lifecycle of PL/SQL Variables, Constants and Data Types — specifically, ignoring that package-level variables persist for the entire user session, which can cause 'Memory Leak' symptoms in long-lived connections.

    onnections.

    Ignoring error handling — failing to handle VALUE_ERROR (ORA-06502) which occurs when you try to assign a value that exceeds the defined precision or length of a variable.

    a variable.

Interview Questions on This Topic

  • QWhat is the difference between %TYPE and %ROWTYPE?
  • QWhy should you use a CONSTANT instead of a regular variable for fixed values?
  • QHow does PL/SQL handle uninitialized variables by default?
  • QWhat are the benefits of using anchored data types in terms of database maintenance?
🔥
Naren Founder & Author

Developer and founder of TheCodeForge. I built this site because I was tired of tutorials that explain what to type without explaining why it works. Every article here is written to make concepts actually click.

← PreviousIntroduction to PL/SQLNext →PL/SQL Control Structures — IF, LOOP, WHILE
Forged with 🔥 at TheCodeForge.io — Where Developers Are Forged