Skip to content

PL/SQL Collections (Arrays) πŸ“¦πŸ“¦ΒΆ

Prerequisites: PL/SQL Basics, Cursors

Mentor's Note: A variable holds one value. A record holds one row. A Collection is a "Bag of Rows" held in the computer's memory. It allows you to process thousands of records at lightning speed without talking to the database disk every time! πŸ’‘


🌟 The Scenario: The Delivery Crate πŸš›ΒΆ

  • Variable: One apple. 🍎
  • Collection: A Crate of 100 apples. πŸ“¦
  • The Speed: It is much faster to carry one crate into the kitchen than to walk back and forth 100 times for each individual apple.

πŸ’» 1. Associative Arrays (Index-by Tables)ΒΆ

The most common type. They act like "Key-Value" pairs (like a Dictionary in Python or an Object in JS).

DECLARE
   -- 1. Define the type (Key is VARCHAR2 or PLS_INTEGER)
   TYPE t_capitals IS TABLE OF VARCHAR2(100) INDEX BY VARCHAR2(50);

   -- 2. Create the variable
   v_list t_capitals;
BEGIN
   -- 3. Assign values
   v_list('India') := 'New Delhi';
   v_list('Gujarat') := 'Gandhinagar';

   DBMS_OUTPUT.PUT_LINE('Capital: ' || v_list('India'));
END;

πŸ’» 2. Nested Tables πŸͺœΒΆ

Can be stored in database columns! They are like a list that can grow dynamically.

DECLARE
   TYPE t_names IS TABLE OF VARCHAR2(50);
   v_students t_names := t_names('Arjun', 'Priya'); -- Initialize
BEGIN
   v_students.EXTEND; -- Add a new empty slot
   v_students(3) := 'Sneha';
END;

πŸ’» 3. VARRAY (Fixed-Size Arrays) πŸ“ΒΆ

Best for small, fixed lists (like days of the week).

DECLARE
   TYPE t_days IS VARRAY(7) OF VARCHAR2(10);
   v_week t_days := t_days('Mon', 'Tue', 'Wed');
BEGIN
   -- Max size is 7. You cannot extend beyond that.
   NULL;
END;

πŸ—οΈ Architect's Note: Bulk Collect & Performance πŸ›‘οΈΒΆ

The real power of collections is BULK COLLECT. - The Secret: Instead of fetching rows one by one in a loop, you say "Fetch all 1,000 rows into this Collection at once." - Benefit: This reduces "Context Switching" between the PL/SQL and SQL engines. It can make your code 10x to 100x faster! ⚑


πŸ“Š Summary TableΒΆ

Type Size Key Type Database Storage?
Associative Array Dynamic String/Int No (Memory only)
Nested Table Dynamic Integer Yes βœ…
VARRAY Fixed Integer Yes βœ…

πŸ“ˆ Learning PathΒΆ