Sub topic 8
Assigning values to variables
This chapter covers every way a PL/SQL variable gets a value and what happens at the moment of assignment. It assumes you can already write an anonymous block with DECLARE, BEGIN, and END. It also assumes you can declare variables with NUMBER, VARCHAR2, and DATE types, and run blocks in SQL*Plus, SQL Developer, or SQLcl. Examples that read data use the HR.EMPLOYEES table.
Where a variable gets its value
A variable gets a value from one of three places:
| Source | Syntax | Typical use |
|---|---|---|
| Declaration default | `v_x NUMBER := 0;` or `v_x NUMBER DEFAULT 0;` | Give the variable a known starting state |
| Assignment statement | `v_x := expression;` | Compute and store values in the executable section |
| Query | `SELECT col INTO v_x FROM ...` | Copy database data into the variable |
A variable that receives none of these is NULL. This is the source of many bugs, covered below.
The assignment statement
The assignment operator is :=. The target goes on the left, and any expression goes on the right. PL/SQL evaluates the right side first, then stores the result.
SET SERVEROUTPUT ON
DECLARE
v_count NUMBER := 0;
v_name VARCHAR2(30) DEFAULT 'Ada';
v_today DATE;
v_len PLS_INTEGER;
BEGIN
v_count := v_count + 1;
v_today := SYSDATE;
v_len := LENGTH(v_name);
v_name := UPPER(v_name) || '!';
DBMS_OUTPUT.PUT_LINE(v_name || ' has length ' || v_len);
DBMS_OUTPUT.PUT_LINE('Count: ' || v_count);
DBMS_OUTPUT.PUT_LINE('Date: ' || TO_CHAR(v_today, 'YYYY-MM-DD'));
END;
/Four points about this block:
DEFAULTand:=mean the same thing in a declaration. Pick one and use it consistently.- The right side can be a literal, another variable, an arithmetic expression, a function call, or a mix.
- The right side is read before the target changes.
v_count := v_count + 1therefore uses the old value ofv_count. - There is no chained assignment.
a := b := 0is a syntax error, so write two statements.
Conversion and constraint checks
Assignment is where the declared type of the variable takes effect. The declared constraints are checked at the moment of assignment, not when you declare the variable.
Scale rounds, precision overflows
A NUMBER(p,s) variable rounds extra decimal places silently. It raises an error if the integer part is too large.
SET SERVEROUTPUT ON
DECLARE
v_amount NUMBER(6,2);
v_small NUMBER(3);
BEGIN
v_amount := 10.456;
DBMS_OUTPUT.PUT_LINE('Rounded: ' || v_amount);
v_small := 1000;
DBMS_OUTPUT.PUT_LINE('Never printed');
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('Value does not fit: ' || SQLERRM);
END;
/The first assignment stores 10.46. The second fails with ORA-06502: PL/SQL: numeric or value error because 1000 needs four digits and NUMBER(3) holds three. Control jumps to the exception handler, so the second PUT_LINE never runs.
Strings that are too long
A VARCHAR2(n) variable raises the same error when the assigned string is longer than n. PL/SQL does not truncate it.
SET SERVEROUTPUT ON
DECLARE
v_code VARCHAR2(5);
BEGIN
v_code := 'ABCDEFGH';
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('Too long for v_code');
END;
/Note that the declaration VARCHAR2(5) sets a limit of 5 bytes by default, not 5 characters, unless the column or session uses character length semantics. With multibyte characters, a string of five characters can still overflow.
Implicit and explicit conversion
PL/SQL converts between types when it can. A character literal that looks like a number is accepted by a NUMBER variable. A string that does not look like a number raises VALUE_ERROR.
SET SERVEROUTPUT ON
DECLARE
v_n NUMBER;
BEGIN
v_n := '42';
DBMS_OUTPUT.PUT_LINE('Implicit: ' || (v_n + 1));
v_n := TO_NUMBER('1,234.50', '9,999.99');
DBMS_OUTPUT.PUT_LINE('Explicit: ' || v_n);
v_n := '4x2';
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('Cannot convert: ' || SQLERRM);
END;
/Implicit conversion of dates depends on the session setting NLS_DATE_FORMAT, so the same code can behave differently for different users. Use TO_NUMBER, TO_DATE, and TO_CHAR with explicit format models whenever you convert text.
NULL in assignments
An uninitialized variable is NULL, and any arithmetic involving NULL yields NULL. This applies even to an accumulator that you add to.
SET SERVEROUTPUT ON
DECLARE
v_total NUMBER;
v_good NUMBER := 0;
BEGIN
v_total := v_total + 10;
v_good := v_good + 10;
DBMS_OUTPUT.PUT_LINE('Uninitialized: [' || v_total || ']');
DBMS_OUTPUT.PUT_LINE('Initialized: [' || v_good || ']');
END;
/The first line prints empty brackets because NULL + 10 is NULL. The concatenation operator || treats NULL as an empty string, so no error appears. Initialize every accumulator and counter in its declaration.
Two related rules:
- Assigning
NULLexplicitly (v_x := NULL;) is legal for any variable that is not declaredNOT NULL. - Oracle treats an empty string
''asNULL. Afterv_s := '';, the testv_s IS NULLis true.
NOT NULL and constants
A variable declared NOT NULL must be initialized in its declaration, and it rejects any later assignment of NULL.
SET SERVEROUTPUT ON
DECLARE
v_price NUMBER(10,2) NOT NULL := 100;
v_input NUMBER;
BEGIN
v_price := 120;
DBMS_OUTPUT.PUT_LINE('Price: ' || v_price);
v_price := v_input;
DBMS_OUTPUT.PUT_LINE('Never printed');
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('NOT NULL variable cannot take NULL');
END;
/The assignment v_price := v_input fails at run time because v_input is NULL. This is the same VALUE_ERROR as the overflow cases.
A CONSTANT can be assigned only once, in its declaration. If you write c_tax_rate := 0.08; in the executable section, the block does not compile. The error is PLS-00363: expression 'C_TAX_RATE' cannot be used as an assignment target. This is a compile-time error, so no part of the block runs.
Assigning from a query
SELECT ... INTO is the other assignment form. It copies column values into variables. A later chapter covers it in detail, so only the assignment-related points follow.
SET SERVEROUTPUT ON
DECLARE
v_salary employees.salary%TYPE;
v_bonus NUMBER;
BEGIN
SELECT salary INTO v_salary
FROM employees
WHERE employee_id = 100;
v_bonus := v_salary * 0.1;
DBMS_OUTPUT.PUT_LINE('Bonus: ' || v_bonus);
END;
/- The query must return exactly one row. Zero rows raises
NO_DATA_FOUND. More than one raisesTOO_MANY_ROWS. SELECT INTOfollows the same conversion and size rules as:=. A column value that does not fit the target variable raisesVALUE_ERROR.- When the query returns no rows, the variable is not assigned. The exception is raised before any usable value is stored, so do not rely on the old contents of the variable after the error.
- A column that holds
NULLassignsNULLto the variable, which is not an error.
You can also compute a value with a plain expression instead of a query. Write v_next := v_id + 1; rather than SELECT v_id + 1 INTO v_next FROM dual;. The plain form avoids a round trip into the SQL engine.
Boolean assignment
A BOOLEAN variable accepts TRUE, FALSE, or NULL. You can assign the result of a comparison directly:
SET SERVEROUTPUT ON
DECLARE
v_count PLS_INTEGER := 3;
v_has_rows BOOLEAN;
BEGIN
v_has_rows := (v_count > 0);
IF v_has_rows THEN
DBMS_OUTPUT.PUT_LINE('There is data.');
ELSE
DBMS_OUTPUT.PUT_LINE('No data.');
END IF;
END;
/DBMS_OUTPUT.PUT_LINE has no BOOLEAN overload, so you cannot print a boolean directly. Test it with IF or CASE. Also remember that a comparison involving NULL yields NULL, not FALSE. If v_count were NULL, v_has_rows would be NULL, and the IF would take the ELSE branch.
Common mistakes
- Using
=instead of:=for assignment. In PL/SQL,=is a comparison, sov_x = 5;is a syntax error. - Forgetting to initialize accumulators and counters, which turns every later total into
NULL. - Declaring a variable too small for the data.
VARCHAR2(5)andNUMBER(3)fail at run time, and often only for unusual data. - Relying on implicit date and number conversion, which changes with session settings.
- Assuming a failed assignment leaves a partial value. The statement either completes or raises an exception.
Exercise
A block declares v_total NUMBER; with no default, then runs v_total := v_total + 50; and prints v_total. What is printed, and what is the smallest change that fixes it?
Show answer
It prints nothing visible for the number (an empty value), because v_total starts as NULL and NULL + 50 is NULL. Initialize it in the declaration: v_total NUMBER := 0;.
Exercise
Given v_code VARCHAR2(3);, what happens when the block runs v_code := 'ABCD';, and how can you handle it?
Show answer
PL/SQL raises VALUEERROR (ORA-06502) because the string is longer than the declared size. It does not truncate. Handle it with `EXCEPTION WHEN VALUEERROR THEN ...`, or better, declare the variable large enough or use SUBSTR to shorten the value before assigning it.