Sub topic 7
Constants, Defaults, and NOT NULL
This chapter assumes you can run an anonymous block in SQL*Plus, SQL Developer, or SQLcl. It also assumes you know the basic layout of a block and have declared a variable with a data type. Here you will control three things about a declaration: whether the value can change, what value the variable starts with, and whether it may ever hold NULL.
What an uninitialized variable contains
A PL/SQL variable that you declare without an initial value starts as NULL. This holds for every scalar type, including numbers and strings. A NUMBER variable does not start at 0, and a VARCHAR2 variable does not start as an empty string that behaves like text.
NULL spreads through expressions. Arithmetic with NULL gives NULL, and IS NULL is the reliable way to test for it.
SET SERVEROUTPUT ON
DECLARE
v_bonus NUMBER(8,2);
BEGIN
DBMS_OUTPUT.PUT_LINE('Before: ' || NVL(TO_CHAR(v_bonus), 'NULL'));
v_bonus := v_bonus + 10;
DBMS_OUTPUT.PUT_LINE('After: ' || NVL(TO_CHAR(v_bonus), 'NULL'));
END;
/Both lines print NULL. Adding 10 to NULL does not produce 10. Forgetting to initialize a counter or an accumulator is a common cause of totals that stay empty.
Default values
A default value is the value a variable receives when the block starts. You give it in the declaration with either := or the keyword DEFAULT. The two forms are equivalent, so pick one and use it consistently.
SET SERVEROUTPUT ON
DECLARE
v_status VARCHAR2(10) DEFAULT 'NEW';
v_count PLS_INTEGER := 0;
v_started DATE := SYSDATE;
v_note VARCHAR2(30);
BEGIN
DBMS_OUTPUT.PUT_LINE('Status: ' || v_status);
DBMS_OUTPUT.PUT_LINE('Count: ' || v_count);
DBMS_OUTPUT.PUT_LINE('Started: ' || TO_CHAR(v_started, 'YYYY-MM-DD HH24:MI'));
DBMS_OUTPUT.PUT_LINE('Note is null: ' ||
CASE WHEN v_note IS NULL THEN 'yes' ELSE 'no' END);
END;
/A default can be any expression PL/SQL can evaluate, not only a literal. It can call a function, such as SYSDATE. It can also use a constant or a variable declared earlier in the same section.
The expression runs each time the block is entered, not once per session. If you run the block twice, v_started holds two different timestamps. Items are evaluated in the order you declare them, so you cannot refer to something declared further down.
Constants
A constant is an item whose value is fixed when it is declared. Add the keyword CONSTANT before the data type and give an initial value.
SET SERVEROUTPUT ON
DECLARE
c_tax_rate CONSTANT NUMBER(4,3) := 0.075;
c_max_items CONSTANT PLS_INTEGER := 50;
c_company CONSTANT VARCHAR2(30) := 'Example Corp';
v_price NUMBER(10,2) := 200;
BEGIN
DBMS_OUTPUT.PUT_LINE(c_company || ': ' ||
TO_CHAR(v_price * (1 + c_tax_rate), 'FM9990.00'));
END;
/This prints Example Corp: 215.00.
Two rules apply to every constant:
- It must be initialized in its declaration. There is no way to set it later.
- It cannot be the target of an assignment, a
SELECT INTO, or a fetch.
The compiler enforces both rules. The failures show up at compile time, before any code runs:
| Mistake | Typical error |
|---|---|
| `c_rate CONSTANT NUMBER;` | PLS-00322: declaration of a constant must contain an initialization assignment |
| `c_rate := 0.1;` in the executable section | PLS-00363: expression cannot be used as an assignment target |
Here is a block that fails to compile because it tries to change a constant:
DECLARE
c_tax_rate CONSTANT NUMBER(4,3) := 0.075;
BEGIN
c_tax_rate := 0.1; -- PLS-00363, the block does not compile
END;
/Why use constants
Constants give a name to a literal, so c_tax_rate explains itself where 0.075 does not. A rate that appears in ten places is changed in one. The compiler also guards the value, so a later edit cannot overwrite it by accident.
A common convention is a c_ prefix for constants and v_ for variables. The language does not require it, but it makes the intent visible when you read the executable section.
The value does not have to be a literal
The initial value of a constant is evaluated when the block is entered. A constant can therefore capture a runtime value once and hold it steady:
SET SERVEROUTPUT ON
DECLARE
c_run_date CONSTANT DATE := TRUNC(SYSDATE);
BEGIN
DBMS_OUTPUT.PUT_LINE('Run date: ' || TO_CHAR(c_run_date, 'YYYY-MM-DD'));
END;
/If the block runs past midnight, c_run_date still holds the date from the moment the block started. A call to TRUNC(SYSDATE) in the middle of the code would not.
NOT NULL
Adding NOT NULL to a declaration forbids the variable from ever holding NULL. The clause goes after the data type, and the initial value follows it:
v_attempts PLS_INTEGER NOT NULL := 0;A NOT NULL variable must be initialized with a non-NULL value. Without one, the compiler rejects the declaration with PLS-00218: a variable declared NOT NULL must have an initialization assignment.
The constraint is checked at run time on every assignment. If an assignment would store NULL, PL/SQL raises VALUE_ERROR (ORA-06502).
SET SERVEROUTPUT ON
DECLARE
v_attempts PLS_INTEGER NOT NULL := 0;
v_input PLS_INTEGER; -- NULL by default
BEGIN
v_attempts := v_attempts + 1;
DBMS_OUTPUT.PUT_LINE('Attempts: ' || v_attempts);
v_attempts := v_input; -- would store NULL
DBMS_OUTPUT.PUT_LINE('Not reached');
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('Cannot assign NULL to v_attempts');
END;
/The first line prints Attempts: 1. The second assignment raises VALUE_ERROR, and the handler prints the message.
NOT NULL and the empty string
Oracle treats a zero-length string as NULL. A VARCHAR2 NOT NULL variable therefore cannot be initialized with '', and assigning '' to it later raises VALUE_ERROR. If you want a placeholder, use a real value such as a single space or a word like 'NONE'.
NOT NULL combined with CONSTANT
You can write both: c_limit CONSTANT PLS_INTEGER NOT NULL := 100;. The order is CONSTANT, then the data type, then NOT NULL, then the value. Because a constant can never be reassigned, the extra clause mainly documents intent and rejects an initial expression that evaluates to NULL.
SIMPLE_INTEGER is a subtype of PLS_INTEGER that is NOT NULL by definition. You must initialize it, and you do not write the clause yourself.
Where the checks happen
The following diagram shows the decisions the compiler and the runtime make for a single declaration.
NOT NULL with SELECT INTO
A NOT NULL variable and a nullable table column can collide when you load data with SELECT INTO. In the HR sample schema, commission_pct is NULL for employee 100. The load therefore fails:
SET SERVEROUTPUT ON
DECLARE
v_comm NUMBER(3,2) NOT NULL := 0;
BEGIN
SELECT commission_pct
INTO v_comm
FROM employees
WHERE employee_id = 100;
DBMS_OUTPUT.PUT_LINE('Commission: ' || v_comm);
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('commission_pct is NULL for this employee.');
END;
/The query finds the row, but storing its NULL value into v_comm raises VALUE_ERROR. There are two ways to fix this. You can declare v_comm without NOT NULL and test it with IS NULL. Or you can replace NULL inside the query:
SELECT NVL(commission_pct, 0)
INTO v_comm
FROM employees
WHERE employee_id = 100;Choose NOT NULL when a NULL would be a bug that you want to surface immediately. Choose a nullable variable when NULL is a legitimate answer, such as "this employee has no commission".
Gotchas
- A failure while initializing a declaration is not caught by the handler of the same block. If
v_x NUMBER(3) := 1000;raises an error, the exception goes to the enclosing block, because the exception section only covers the executable section. In an anonymous block at top level, the error reaches the client. %TYPEcopies the data type and size of a table column, but not the column'sNOT NULLconstraint. A variable anchored to aNOT NULLcolumn can still hold NULL unless you addNOT NULLyourself.- When one variable is anchored to another variable declared
NOT NULL, the new variable inherits the constraint. It then needs an initial value too. - A constant's value is fixed within one execution of the block, but it can differ between executions if the expression uses
SYSDATEor similar.
Summary of the rules
| Feature | Syntax | Initial value required | Can change later |
|---|---|---|---|
| Plain variable | `v_x NUMBER;` | No, starts as NULL | Yes |
| Variable with default | `v_x NUMBER := 5;` or `DEFAULT 5` | Given | Yes |
| Constant | `c_x CONSTANT NUMBER := 5;` | Yes | No |
| NOT NULL variable | `v_x NUMBER NOT NULL := 5;` | Yes, not NULL | Yes, but never to NULL |
Exercise
A block declares v_limit PLS_INTEGER NOT NULL; and nothing else about it. What happens, and what is the smallest change that fixes it?
Show answer
The block fails to compile with PLS-00218, because a NOT NULL variable must have an initialization assignment. Add a non-NULL initial value, for example v_limit PLS_INTEGER NOT NULL := 10;.
Exercise
Write a block that declares a constant c_bonus_pct equal to 0.1, selects the salary of employee 100 into a variable anchored with %TYPE, and prints the bonus. Why can the SELECT INTO not target the constant?
Show answer
DECLARE
cbonuspct CONSTANT NUMBER(3,2) := 0.1;
vsalary employees.salary%TYPE;
BEGIN
SELECT salary INTO vsalary FROM employees WHERE employeeid = 100;
DBMSOUTPUT.PUTLINE('Bonus: ' || vsalary * cbonuspct);
END;
/
A constant cannot be the target of any assignment, and SELECT INTO assigns to its target, so the compiler rejects it with PLS-00363. Run SET SERVEROUTPUT ON first to see the output.
Exercise
In the HR schema, employee 100 has a NULL commissionpct. A block declares `vcomm NUMBER(3,2) NOT NULL := 0; and runs SELECT commissionpct INTO vcomm FROM employees WHERE employee_id = 100;`. Which exception is raised, and name two ways to avoid it.
Show answer
VALUEERROR (ORA-06502) is raised, because the query returns a NULL that cannot be stored in a NOT NULL variable. Either remove NOT NULL from the variable and test it with IS NULL, or use NVL(commissionpct, 0) in the query.