How to Declare a Variable in PL/SQL?
Last Updated :
21 Oct, 2024
Declaring variables in PL/SQL is a fundamental step towards building powerful and efficient database applications. Variables act as placeholders for data which enable us to manipulate and store information within our PL/SQL programs.
Here, we will explore various methods of declaring variables in PL/SQL, including syntax, examples, and practical use cases. We will cover variable initialization, scope, and the use of variable attributes like %TYPE and %ROWTYPE.
How to Declare PL/SQL Variables?
When writing PL/SQL code it is important to declare variables properly to store and manipulate data effectively. Variables act as containers for values and enable various operations on the stored data.
Variables in PL/SQL are declared using the DECLARE keyword within an anonymous block or a named program unit such as a procedure, function, or package.
Common Methods for Declaring Variables in PL/SQL
The below methods are used to declare a variable in PL/SQL are as follows:
Let's understand each method one be one along with the Examples.
1. Using Declare Variables in PL/SQL
To declare a variable in PL/SQL, use the DECLARE keyword followed by the variable name and its data type. Optionally, you can also assign an initial value to the variable using the ':=' operator.
Syntax:
DECLARE
variable_name datatype := initial_value;
here,
- variable_name: It is the name of the variable.
- datatype: It is the data type of the variable.
- := initial_value: It is an optional assignment of an initial value to the variable.
Example:
DECLARE
name VARCHAR2(20) := 'GeeksForGeeks';
BEGIN
DBMS_OUTPUT.PUT_LINE(name);
END;
Output:
OutputExplanation: In the above Query, We have declares a variable named "name" with a size of 20 characters and initializes it with the value GeeksForGeeks then prints the value of the variable using DBMS_OUTPUT.PUT_LINE.
2. Using Initializing Variables in PL/SQL
In this method Variables can be initialized in two ways either during declaration or later in the code.
a. Initializing during declaration
Variables can be assigned values when declared, as shown below:
Syntax:
DECLARE
my_variable NUMBER := value;
BEGIN
-- PL/SQL code
END;
Example:
DECLARE
name VARCHAR2(20) := 'GeeksForGeeks';
BEGIN
DBMS_OUTPUT.PUT_LINE(name);
END;
Output:

b. Initialization After Declaration
You can also assign a value to a variable later in the code using the := operator.
Syntax:
DECLARE
my_variable NUMBER;
BEGIN
my_variable := value;
END;
Example:
DECLARE
num1 NUMBER;
num2 NUMBER;
result NUMBER;
BEGIN
num1 := 5;
num2 := 3;
result := num1 + num2;
DBMS_OUTPUT.PUT_LINE('Sum: ' || result);
END;
Output:

3. Using Variable Scope in PL/SQL
Variable scope determines where a variable can be accessed within a program. In PL/SQL, variable scope can be either local or global.
- Local Variables: Declared within a block or subprogram, accessible only inside that block or subprogram.
- Global Variables: Declared in the outermost block and accessible by nested blocks.
Example:
DECLARE
global_var NUMBER; -- global variable
BEGIN
-- PL/SQL code using global_var
DECLARE
local_var NUMBER; -- local variable
BEGIN
-- PL/SQL code using local_var and global_var
END;
-- Here you can't access local_var
END;
Explanation: The global_var can be accessed throughout the entire program, while the local_var is only accessible within the inner block
4. Using Variable Attributes (%TYPE and %ROWTYPE)
PL/SQL provides two powerful attributes, %TYPE and %ROWTYPE, which allow variables to inherit data types from existing columns or entire rows.
- %TYPE: It defines a variable with the same data type as another variable or column.
- %ROWTYPE: It defines a record with the same structure as a table or cursor.
Example: The below example is demonstrating the use of %TYPE and %ROWTYPE attribute
Create a employees table and Insert some records into a employees table
-- Creating a employees table
CREATE TABLE employees (
employee_id NUMBER PRIMARY KEY,
first_name VARCHAR2(50),
last_name VARCHAR2(50),
salary NUMBER
);
-- Inserting some records
INSERT INTO employees VALUES (1, 'John', 'Doe', 50000);
INSERT INTO employees VALUES (2, 'Jane', 'Smith', 60000);
INSERT INTO employees VALUES (3, 'Bob', 'Johnson', 55000);
1. Using %TYPE Attribute
In this example, we have declared a variable salary_var using %TYPE to match the data type of the salary column in the employees table then we have assigned a value to salary_var and displayed the assigned value using DBMS_OUTPUT.PUT_LINE.
DECLARE
salary_var employees.salary%TYPE;
BEGIN
-- Assign a value to the variable
salary_var := 70000;
-- Display the assigned value
DBMS_OUTPUT.PUT_LINE('Assigned Salary: ' || salary_var);
END;
Output:

Explanation: In the above Query, We have declares a variable salary_var with the same data type as the salary column in the employees table, assigns a value of 70000 to it, and then prints the assigned salary using DBMS_OUTPUT.PUT_LINE.
2. Using %ROWTYPE Attribute
In this example, We have declared a record variable employee_record using %ROWTYPE to match the structure of the employees table and fetched the data from the employees table into the employee_record variable using a SELECT INTO statement then we have displayed the retrieved data from the employee_record using DBMS_OUTPUT.PUT_LINE.
DECLARE
employee_record employees%ROWTYPE;
BEGIN
-- Fetch data from the table into the record variable
SELECT * INTO employee_record FROM employees WHERE employee_id = 2;
-- Display the retrieved data
DBMS_OUTPUT.PUT_LINE('Employee ID: ' || employee_record.employee_id);
DBMS_OUTPUT.PUT_LINE('First Name: ' || employee_record.first_name);
DBMS_OUTPUT.PUT_LINE('Last Name: ' || employee_record.last_name);
DBMS_OUTPUT.PUT_LINE('Salary: ' || employee_record.salary);
END;
Output:

Explanation: In the above Query, We have declares a record variable employee_record that matches the structure of the employees table. It then fetches the data for the employee with employee_id 2 into the employee_record variable using a SELECT INTO statement and prints the retrieved data using DBMS_OUTPUT.PUT_LINE.
Important Points About PL/SQL Variables
- All variables must be declared before they can be used in a PL/SQL block. Declaration involves specifying the variable's name and data type.
- You can declare variables as constants using the CONSTANT keyword, ensuring their value cannot be changed once assigned.
- Use %TYPE whenever possible to avoid data type mismatches and to ensure compatibility with changes in database schema.
- Avoid using Oracle reserved keywords as variable names.
Similar Reads
How to Declare a Variable in SQL?
Variables in SQL are fundamental for building efficient and scalable database applications. They enhance the flexibility and efficiency of database queries by acting as placeholders for data. Understanding how to declare and use variables in SQL is crucial for writing dynamic and effective queries I
3 min read
How to Declare a Variable in SQLite?
Declaring variables in SQLite can greatly enhance the flexibility and efficiency of our database queries. Whether we need to store temporary values, simplify complex operations or reuse values within a query, understanding how to declare variables in SQLite is very important. In this article, we'll
3 min read
How to Declare a Variable in SQL Server?
In SQL Server, variables play a critical role in the dynamic execution of SQL scripts and procedures. Variables allow you to store and manipulate data temporarily within the scope of a batch or procedure. By using the DECLARE statement, you can create variables with specific data types, which can th
6 min read
How to Add Column in View in PL/SQL?
In Oracle PL/SQL, adding a column to a view is not done through the ALTER VIEW command since it does not directly support adding columns. Instead, views are modified by recreating them using the CREATE OR REPLACE VIEW statement, which allows the addition of new columns while retaining the existing s
3 min read
How to Display all Tables in PL/SQL?
In Oracle PL/SQL, we need to work with database objects like tables. It provides various approaches to display all the tables. Such as using the USER_TABLES, ALL_TABLES, and DBA_TABLES views. Each approach is explained with syntax and examples. In this article, We will learn about How to Display all
5 min read
How to Count Distinct Values in PL/SQL?
PL/SQL, an extension of SQL for Oracle databases, allows developers to blend procedural constructs like conditions and loops with the power of SQL. It supports exception handling for runtime errors and enables the declaration of variables, constants, procedures, functions, packages, triggers, and mo
6 min read
How to Check If a Table Exist in PL/SQL?
In PL/SQL (Procedural Language/Structured Query Language), it's often necessary to determine whether a particular table exists in the database schema before attempting any operations on it. These views offer detailed metadata about database objects. This article explores methods and techniques to ch
4 min read
How to Open a PL/SQL File?
In database management and application development, PL/SQL (Procedural Language/Structured Query Language) files play an important role. These files contain stored procedures, functions, triggers, and other programmatic constructs essential for Oracle database systems. Opening a PL/SQL file is the f
4 min read
How to Set a Column Value to Null in PL/SQL?
In PL/SQL, setting a column value to NULL is a common requirement when working with databases. Understanding how to set column values to NULL is essential for database developers and administrators. In this article, we will look into the concept of setting a column value to NULL in PL/SQL, covering
4 min read
How to Get the Top 10 Values in PL/SQL?
PL/SQL stands for Procedural Language/ Structured Query Language. It has block structure programming features. PL/SQL supports SQL queries. PL/SQL contains a declaration section, execution section, and exception-handling section. Declare and exception handling sections are optional. This article exp
6 min read