Declaring and Assigning Variables With the DEFAULT Keyword or NOT NULL Constraint

Previous
Previous
Next
Next

You can use the DEFAULT keyword instead of the assignment operator to initialize variables. Use DEFAULT for variables that have a typical value. Use the assignment operator for variables (such as counters and accumulators) that have no typical value. You can also use DEFAULT to initialize subprogram parameters, cursor parameters, and fields in a user-defined record.

In addition to assigning an initial value, declarations can impose the NOT NULL constraint so that assigning a NULL causes an error. The NOT NULL constraint must be followed by an initialization clause.

In Example: Using DEFAULT and NOT NULL in PL/SQL the declaration for the avg_days_worked_month variable uses the DEFAULT to assign a value of 21 and the declarations for the active_employee and monthly_salary variables use the NOT NULL constraint.

Using DEFAULT and NOT NULL in PL/SQL

DECLARE  -- declare and assign variables
  last_name              VARCHAR2(30);
  first_name             VARCHAR2(25);
  employee_id            NUMBER(6);
  active_employee        BOOLEAN NOT NULL := TRUE;  -- value cannot be NULL
  monthly_salary         NUMBER(6) NOT NULL := 2000; -- value cannot be NULL
  number_of_days_worked  NUMBER(2);
  pay_per_day            NUMBER(6,2);
  employee_count         NUMBER(6) := 0;
  avg_days_worked_month  NUMBER(2) DEFAULT 21;  -- assign a default value
BEGIN
  NULL; -- NULL statement does nothing, allows this block to executed and tested
END;
/