Search code examples
oracle-databasefor-loopindexingplsqlnested-table

Oracle PLSQL nested table iteration via index - can indices be out of order?


I've been reading, on different oracle.com sites, that

FOR i IN nested_table.FIRST .. nested_table.LAST

is what you normally do in PLSQL, when iterating over all elements of a nested table type (as long as there were no elements deleted).

The way my nested table comes into existence, is by doing

type  nested_table_type  is table of  varchar2(20)

and in a different package

nested_table   other_package.nested_table_type := other_package.nested_table_type();

then later, in a loop

nested_table.extend;
nested_table(nested_table.last) := something;

for any number of times. Then, I want to do something with each value, kind of like using a for each in other languages. Can I use the for loop here? Somebody told me to watch out, because indices in case of Oracle may not be in order, so some might not be considered by the for loop. I should defintely use this, he said:

index := nested_table.first;
while (index is not null)
loop
   do things...
   index := nested_table.next(index);
end loop;

Is this true? How would the indices not be in order or the for loop not iterate over them all?

Thanks for helping :)

Edit:

Most likely this was some kind of miscommunication. I left the code the way it is. Still, thanks for reading / answering, and hopefully this helps somebody in the future or something :)


Solution

  • Indices are in order, it's just that you can create sparse table, meaning that some indices might be missing.

    However, for your case using i IN t.FIRST .. t.LAST is perfectly fine.