PL/SQL Collections: Mastering Memory Structures & Arrays
Collections are the arrays of PL/SQL. Master Associative Arrays, Nested Tables, and VARRAYs, and combine them with Bulk Processing to build lightning-fast data transformation pipelines.
The Types of Collections
Standard SQL works with sets of data on disk. When you transition into PL/SQL, you often need to hold sets of data in memory (PGA) to loop over them, modify them, and insert them elsewhere.
To hold an array of data in memory, PL/SQL uses Collections.
Associative Arrays (INDEX BY)
Also known as Index-By tables, these act like Hash Maps or Dictionaries in Python/Java. They consist of key-value pairs. The key can be a Number or a String (VARCHAR2).
Because keys aren't sequential, you cannot use a standard FOR i IN 1..v_emps.COUNT loop to iterate through them. You must use the FIRST and NEXT methods.
Nested Tables
Nested tables are unbounded, dense arrays (initially sequential, starting at index 1). Unlike Associative Arrays, Nested Tables can be stored physically in database columns, though this is heavily discouraged in relational modeling.
Collection Methods (COUNT, FIRST, LAST)
Oracle provides built-in methods to manipulate and interrogate collections.
.COUNT: Returns the number of elements..FIRST/.LAST: Returns the first and last index numbers..EXISTS(n): Returns TRUE if indexncontains data..EXTEND(n): Appendsnnull elements to a Nested Table or VARRAY (required before adding new data)..DELETE(n): Removes the element at indexn. This makes a Nested Table "sparse" (gaps in the index).
Bulk Processing (BULK COLLECT & FORALL)
Collections are most powerful when paired with Bulk Processing.
Normally, if you SELECT 10,000 rows into a loop, you cause 10,000 Context Switches between the SQL and PL/SQL engines. By using BULK COLLECT INTO a collection, you fetch all 10,000 rows into memory in a single trip.
Common Gotchas
Important Gotchas
- !
Associative Arrays automatically grow when you assign a new key. Nested Tables DO NOT. If you assign
v_list(1) := 'X'without callingv_list.EXTENDfirst, Oracle will throw aSubscript outside of limiterror. - !
If you
DELETEan element from the middle of a Nested Table, it becomes sparse (e.g., indices 1, 2, 4). If you loop usingFOR i IN 1..v_list.COUNT, the loop will try to read index 3 and crash withNo data found. You must use aWHILE v_index IS NOT NULLloop with the.NEXT()method for sparse collections.
Key Takeaways
Key Takeaways
- Use Associative Arrays for in-memory Hash Maps (key-value lookups).
- Use Nested Tables for sequential arrays, especially when integrating with SQL
TABLE()operators. - Combine Collections with
BULK COLLECTandFORALLto eliminate Context Switches and drastically improve batch performance.


