Sub topic 5
Declaring and naming variables
This chapter assumes you can write basic SQL (SELECT, INSERT, UPDATE, DELETE) and know Oracle data types such as NUMBER, VARCHAR2, and DATE. It also assumes you can run a script in SQL*Plus, SQL Developer, or SQLcl against a schema with the HR sample tables. The examples use HR.EMPLOYEES.
A variable is a named storage location in memory that holds one value of a given data type while a block runs. You declare it in the declaration section, between DECLARE and BEGIN. This chapter covers the declaration syntax, the rules for valid names, and the naming mistakes that cause wrong query results. Choosing data types, constants, and NOT NULL get fuller treatment in later chapters.
The declaration syntax
Every variable declaration has the same shape:
variable_name datatype [NOT NULL] [:= initial_value | DEFAULT initial_value];Only the name and the data type are required. Each declaration ends with a semicolon and declares exactly one variable. You cannot write v_a, v_b NUMBER;.
SET SERVEROUTPUT ON
DECLARE
v_first_name VARCHAR2(20) := 'Ada';
v_last_name VARCHAR2(25) DEFAULT 'Lovelace';
v_full_name VARCHAR2(50);
v_hire_date DATE := DATE '2024-01-15';
v_bonus NUMBER;
BEGIN
v_full_name := v_first_name || ' ' || v_last_name;
DBMS_OUTPUT.PUT_LINE(v_full_name);
DBMS_OUTPUT.PUT_LINE(TO_CHAR(v_hire_date, 'YYYY-MM-DD'));
IF v_bonus IS NULL THEN
DBMS_OUTPUT.PUT_LINE('v_bonus is NULL');
END IF;
END;
/The output is:
Ada Lovelace
2024-01-15
v_bonus is NULLSeveral details are worth noting:
:=andDEFAULTdo the same job in a declaration. Pick one and use it consistently.- A variable with no initial value starts as
NULL, whatever its type. Unlike some languages, a NUMBER does not start at 0 and a VARCHAR2 does not start as an empty string. - Character types need a maximum length, as in
VARCHAR2(25). Leaving it out is a compile error. NUMBER does not need a precision or scale. - The initial value can be any expression, including one that uses variables declared earlier.
Declaration order matters
PL/SQL reads the declaration section from top to bottom. A declaration can refer only to items declared above it.
SET SERVEROUTPUT ON
DECLARE
v_base NUMBER := 10;
v_limit NUMBER := v_base * 5;
BEGIN
DBMS_OUTPUT.PUT_LINE('Limit: ' || v_limit);
END;
/This prints Limit: 50. If you swap the two declarations, the compiler stops with PLS-00201: identifier 'V_BASE' must be declared. Forward references are not allowed for variables.
Rules for valid names
PL/SQL names, called identifiers, follow these rules:
| Rule | Detail |
|---|---|
| First character | Must be a letter. |
| Other characters | Letters, digits, `$`, `#`, and `_`. |
| Maximum length | 30 bytes before Oracle Database 12.2. 128 bytes from 12.2 onward. |
| Case | Not case-sensitive. `v_total`, `V_TOTAL`, and `V_Total` are the same variable. |
| Spaces | Not allowed in ordinary identifiers. |
| Reserved words | Cannot be used. Examples: `DATE`, `BEGIN`, `LOOP`, `SELECT`. |
Two variables with the same name in the same declaration section are an error. The same name in a nested block is legal and is called shadowing, which a later chapter covers.
A quoted identifier such as "Total Cost" can contain spaces and keeps its case. It also forces you to type the quotes and exact case every time. Avoid quoted identifiers in PL/SQL code.
DECLARE
v_date DATE; -- valid: not a reserved word on its own
date DATE; -- invalid: DATE is reserved
BEGIN
NULL;
END;
/The second declaration fails to compile. The first is valid because v_date is a different word from DATE.
A naming convention
Oracle does not enforce a convention, but a prefix makes the role of every name visible at a glance. A common scheme:
| Prefix | Used for | Example |
|---|---|---|
| `v_` | Local variable | `v_salary` |
| `c_` | Constant | `c_tax_rate` |
| `p_` | Subprogram parameter | `p_employee_id` |
| `r_` or `rec_` | Record | `r_emp` |
| `e_` | User-defined exception | `e_invalid_id` |
Use descriptive names. v_salary tells the next reader what the variable holds. v_s does not. Name the variable after its meaning, not after its type, so v_hire_date is better than v_date1.
The prefixes are not only a style choice. They prevent the most common naming bug, described next.
When a variable name matches a column name
Inside a SQL statement embedded in PL/SQL, Oracle resolves a name by looking at the columns of the tables in that statement first. Only if no column matches does it look for a PL/SQL variable. If a variable has the same name as a column, the column wins, and you get no error or warning.
SET SERVEROUTPUT ON
DECLARE
last_name VARCHAR2(25) := 'King';
v_count NUMBER;
BEGIN
SELECT COUNT(*)
INTO v_count
FROM employees
WHERE last_name = last_name;
DBMS_OUTPUT.PUT_LINE('Rows matched: ' || v_count);
END;
/Both last_name references in the WHERE clause resolve to the column. The condition compares each row's last_name with itself, so it is true for every row where last_name is not null. In the standard HR schema the block prints Rows matched: 107, not the number of employees named King.
The diagram shows the lookup order that produces this result.
There are two fixes.
Fix 1: use a prefix
Rename the variable to v_last_name. No column is called that, so the name resolves to the variable. This is the simplest fix and the reason the v_ convention exists.
Fix 2: qualify the name with a block label
Put a label before the block and prefix the variable with it.
SET SERVEROUTPUT ON
<<main>>
DECLARE
last_name VARCHAR2(25) := 'King';
v_count NUMBER;
BEGIN
SELECT COUNT(*)
INTO v_count
FROM employees
WHERE employees.last_name = main.last_name;
DBMS_OUTPUT.PUT_LINE('Rows matched: ' || v_count);
END;
/Now employees.last_name is the column and main.last_name is the variable. In the standard HR data this prints Rows matched: 2. The labelled form is useful when you cannot rename a variable, for example because it is a subprogram parameter that other code calls by name.
Declarations and the DECLARE keyword
The DECLARE keyword begins the declaration section of an anonymous block. The section is optional. A block that needs no variables starts directly with BEGIN.
In a stored procedure, function, or trigger, there is no DECLARE. The declarations go between the IS or AS keyword and BEGIN. The syntax inside the section is the same.
CREATE OR REPLACE PROCEDURE show_greeting IS
v_message VARCHAR2(50) := 'Hello from a procedure';
BEGIN
DBMS_OUTPUT.PUT_LINE(v_message);
END show_greeting;
/Common mistakes
- Missing length.
v_name VARCHAR2;fails to compile. Writev_name VARCHAR2(30);. - Values that do not fit. If
v_codeisVARCHAR2(3)and you assign'ABCD', the block raisesORA-06502: PL/SQL: numeric or value error. This happens at run time, not compile time. - Assuming a default of 0 or empty. An uninitialized variable is
NULL, and arithmetic withNULLyieldsNULL.v_total := v_total + 5;leavesv_totalnull if it was never set. - Using
=to assign. In PL/SQL,=is only a comparison. Assignment is:=. - Hard-coding column sizes. Writing
VARCHAR2(25)to hold alast_namevalue breaks quietly when the column grows. The next chapters show how%TYPEremoves this problem.
Summary
- Declare one variable per statement as
name datatype [NOT NULL] [:= value];. - Uninitialized variables are
NULL. - Declare an item before you use it.
- Identifiers are case-insensitive, begin with a letter, and may not be reserved words.
- A column name beats a variable name inside embedded SQL. Use prefixes such as
v_, or qualify with a block label.
Exercise
The block below should count employees whose departmentid equals the variable. It returns the count of all employees with a non-null departmentid instead. Explain why, and give two different fixes. DECLARE departmentid NUMBER := 90; vcount NUMBER; BEGIN SELECT COUNT(*) INTO vcount FROM employees WHERE departmentid = departmentid; DBMSOUTPUT.PUTLINE(vcount); END;
Show answer
Inside the SQL statement, both departmentid references resolve to the column employees.departmentid, because a column name takes precedence over a variable name. The condition compares each row's column with itself, so it is true for every row where departmentid is not null. Fix 1: rename the variable to vdepartmentid and compare against it. Fix 2: label the block, for example <<main>>, and write WHERE employees.departmentid = main.department_id.
Exercise
Why does this declaration section fail to compile, and how do you correct it? DECLARE vtotal NUMBER := vprice * 2; v_price NUMBER := 40;
Show answer
vprice is used before it is declared, and PL/SQL does not allow forward references, so the compiler reports PLS-00201 (identifier must be declared). Declare vprice first, then declare v_total using it.