Back to blog
Databases

Working with Variables in PL/SQL

Introduction

Variables are used to store data inside PL/SQL.

They allow your code to reuse values and make decisions.

Declaring Variables

DECLARE
   v_name VARCHAR2(20);
   v_salary NUMBER;

Variables are defined at the top of the block.

Assigning Values

v_name := 'John';

PL/SQL uses `:=` for assignment.

Naming Rules

Variable names must:

  • start with a letter
  • be under 30 characters
  • not use reserved words

Using Database Types

v_salary employees.salary%TYPE;

This copies the type from a database column.

Why This Helps

Instead of guessing the type:

v_salary NUMBER;

You link it directly:

v_salary employees.salary%TYPE;

If the column changes later, your code still works.

Example

DECLARE
   v_name VARCHAR2(20);
BEGIN
   v_name := 'Alice';
   DBMS_OUTPUT.PUT_LINE('User: ' || v_name);
END;
/

Why It Matters

Poor variable handling can lead to:

  • incorrect data
  • logic errors
  • unexpected behavior

Using proper types and clear names helps avoid these issues.

Conclusion

Variables are simple but essential.

They make your code flexible, readable, and easier to maintain.