How to Fix ORA-06531: Reference to Uninitialized Collection in Oracle

Initialize nested tables and varrays before EXTEND or COUNT, with a constructor or BULK COLLECT, and empty them with DELETE.

ORA-06531 is raised when PL/SQL code uses a nested table or varray variable that was declared but never initialized. Such a variable starts atomically null: it is not an empty collection, it is no collection at all, so EXTEND, COUNT, and element access all fail. The predefined exception is COLLECTION_IS_NULL. Initialize the variable with its constructor, or fill it with BULK COLLECT.

Reproduce the Error

Example:

declare
  type num_list is table of number;
  v_list num_list;                       -- declared, but atomically null
begin
  v_list.extend;
end;
/
declare
  type num_list is table of number;
  v_list num_list;
begin
  dbms_output.put_line(v_list.count);
end;
/

Output:

declare
*
ERROR at line 1:
ORA-06531: Reference to uninitialized collection
ORA-06512: at line 5

declare
*
ERROR at line 1:
ORA-06531: Reference to uninitialized collection
ORA-06512: at line 5

Both EXTEND and COUNT fail on the null collection.

Fix: Initialize the Collection

Example:

set serveroutput on
declare
  type num_list is table of number;
  v_list num_list := num_list();         -- empty, not null
begin
  v_list.extend;
  v_list(1) := 42;
  dbms_output.put_line('Count: ' || v_list.count);
end;
/
declare
  type num_list is table of number;
  v_list num_list;
begin
  -- BULK COLLECT initializes the collection
  select level bulk collect into v_list from dual connect by level <= 3;
  dbms_output.put_line('Count: ' || v_list.count);
end;
/

Output:

Count: 1

PL/SQL procedure successfully completed.

Count: 3

PL/SQL procedure successfully completed.
  • NUM_LIST() creates an empty collection, ready for EXTEND.
  • BULK COLLECT INTO initializes the collection itself, even when the query returns no rows.

Things to Know

  • Associative arrays (INDEX BY tables) never need initialization and cannot raise ORA-06531.
  • Test a collection with IS NULL before using it when it comes from a parameter or a column.
  • Assigning NULL to a collection makes it atomically null again; use DELETE to empty it instead.

Related Guides

Conclusion

ORA-06531 means a nested table or varray was used before it existed. Initialize it with its constructor at declaration, or fill it with BULK COLLECT, and empty it with DELETE rather than NULL.

Vinish Kapoor
Vinish Kapoor

An Oracle ACE, author of four books on Oracle APEX, SQL and PL/SQL, and Oracle Forms, and a software developer building Oracle database applications since 2001.

guest

0 Comments
Oldest
Newest Most Voted