Variables, Constants and Data Type, Assigning Values

PL/SQL variables and constants act as named buckets in database memory that hold changing or fixed data values for safe processing.

8 min read · 10 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

Tracking an unpredictable ticket identifier

Suppose you are writing an automated management script for TicketDesk to track an incoming customer complaint. The ticket ID number changes every single time a customer submits a new issue. The urgency level might be Critical now, but an administrator could modify it to Low a few minutes later. How do you catch and hold onto these fluid pieces of information while your server evaluates the rules? You need an isolated storage container inside the database engine memory that can hold, read, and manipulate values instantly.

Theory

The Labelled Storage Bins

Think of your Oracle database server as a massive, busy warehouse floor. If you throw raw text on the floor without a box, it gets lost. A variable is like an empty plastic bin with a sticky note indicating 'Numbers Only'. A constant is like a heavy wooden crate sealed with industrial glue: once you put an item inside and declare its category, nobody can change it. Assigning a value is simply dropping an item into that specific bin.

Theory

Variables and Constants in PL/SQL Operations

In Oracle PL/SQL, a variable is a named storage address whose internal contents can fluctuate during program execution. A constant is a fixed data entity that cannot change after initialization and requires the CONSTANT keyword. Every container requires a defined datatype (such as NUMBER or VARCHAR2) to enforce consistency. You populate these placeholders either through manual computation using the assignment operator := or by retrieving column records using a SELECT INTO database query.

At a glance

Primary declaration and assignment structures in Oracle PL/SQL engine

Syntax ComponentPrimary Operational PurposeExample Statement
Assignment OperatorOverwrites a declared variable with a specific value directlyv_status := 'Open';
CONSTANT KeywordLocks a memory slot so its initial definition is unalterablec_tax CONSTANT NUMBER := 0.18;
%TYPE AttributeDynamically copies the matching datatype of a columnv_title tickets.title%TYPE;
SELECT INTO ClausePulls database fields into memory variablesSELECT status INTO v_status FROM tickets;

Practical

Declaring and Allocating Ticket Fields within a Block

-- Enable console text printing in Oracle terminal
SET SERVEROUTPUT ON;

DECLARE
  -- Anchor variable data properties directly to our schema layout
  v_ticket_title tickets.title%TYPE;
  v_ticket_status VARCHAR2(20) := 'Unassigned';
  
  -- Establish a strict baseline tracking limit constant
  c_max_days CONSTANT NUMBER := 7;
BEGIN
  -- Update the tracking state using the assignment mechanism
  v_ticket_status := 'In Progress';
  
  -- Extract a live row directly into our localized variable placeholder
  SELECT title INTO v_ticket_title
  FROM tickets
  WHERE id = 101;
  
  DBMS_OUTPUT.PUT_LINE('Processing Title: ' || v_ticket_title);
  DBMS_OUTPUT.PUT_LINE('Current Status: ' || v_ticket_status);
  DBMS_OUTPUT.PUT_LINE('SLA Day Limit: ' || c_max_days);
END;
/

Copy and open Oracle FreeSQL
Oracle FreeSQL is a free online editor for Oracle SQL. The code is copied first: paste it there and run it.

Quiz

Which code configuration properly builds an unalterable constant holding a maximum priority limit inside an Oracle declaration zone?

  1. c_limit NUMBER CONSTANT = 5;
  2. c_limit CONSTANT NUMBER := 5;
  3. c_limit NUMBER := 5 CONSTANT;
  4. c_limit CONSTANT NUMBER = 5;
Show the answer

c_limit CONSTANT NUMBER := 5;

In Oracle PL/SQL, a constant requires a specific structural pattern: identifier first, followed by the explicit CONSTANT keyword, then the structural datatype, and final initialization through the := assignment operator. A single equal sign = is reserved for conditional matching in SQL queries, not allocation.

Think first

Mental Challenge: Structural Adaptability with %TYPE

If a system administrator modifies the database schema to change the tickets.title column width from VARCHAR2(100) to VARCHAR2(300), what changes must you make to a script using %TYPE to avoid buffer crashes? Analyze this internally before tapping.

Show the answer

You do not need to make any code updates! This represents the main engineering advantage of the anchoring %TYPE mechanism. It references the underlying table blueprint dynamically at execution runtime, automatically matching the expanded scale and preserving block stability without code compilation errors.

Watch out

The Laboratory Mismatch and Assignment Traps

University examiners frequently catch student scripts on two classic allocation blunders. First, inadvertently typing a simple = instead of := inside execution expressions, which triggers an immediate compilation failure. Second, using SELECT INTO on queries that yield multi-row streams or zero records. A basic SELECT INTO expects exactly 1 match: anything else forces a runtime crash via TOO_MANY_ROWS or NO_DATA_FOUND anomalies.

Theory

Enterprise Usage and Frontend Transitions

Using anchored variable allocation prevents unnecessary text re-parsing in production analytics pipelines, increasing transaction processing speeds. As you transition to your Sem 3 mobile architecture courses utilizing SQLite data frameworks, you will build parameterized lookup queries that mirror this exact binding behavior, linking frontend inputs directly into memory locations securely without risking SQL injection vulnerabilities.

Summary

Key takeaways

  • Variables represent designated data bins in memory whose values remain malleable during block routines.
  • Constants demand initialization during declaration using the explicit CONSTANT keyword modifier.
  • The specialized operator combo := handles internal value mapping within active block logic.
  • The %TYPE anchoring tool automatically inherits live column properties to eliminate data mismatch errors.
  • Queries using SELECT INTO must locate exactly 1 matching record to avoid exceptions.
  • Memory hook: Define the layout, anchor with percent-type, assign using colon-equals, and capture lone rows!

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from PL/SQL and Conditional Statements

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Variables, Constants and Data Type, Assigning Values · Mastering SQL - PL/SQL (SEC-02 option A) · Gri-Learn