Like other programming languages, PL/SQL provides a data structure called VARRAY, which can store a collection of elements of the same type.
Varray stands for a variable-size array. When you create varrays you must provide the maximum size for them.
All varrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
Each element in a varray has an index associated with it. It also has a maximum size that can be changed dynamically.
Creating a VARRAY type.
TYPE varray_type_name IS VARRAY(n) of < element_type >
In PL/SQL, the starting index for varrays is always 1. Varrays are one-dimensional arrays.
A varray is automatically NULL when it is declared. We must be initialized before its elements can be referenced.
Once the array is initialized you can extend it and add elements.
We access each element using the VARRAY variable and the index number. When the PL/SQL block ends, the memory used by the array is recovered automatically by the PL/SQL engine.
Another example with loop statement.
Here, we added all elements like above and printed one by one with looping statement.
Elements of a varray could also be a %ROWTYPE of any database table or %TYPE of any database table field.
Take look into below examples as well.
Here, list_varray.extend(2,4) appends two copies on the fourth element to the collection like below.
list_varray.trim(2) will remove last two elements.