NEXT Method in PL/SQL โ€“ Navigate to the Next Collection Index

The NEXT Method in PL/SQL is a powerful collection API function that lets you retrieve the next higher subscript value from a given index. Itโ€™s particularly useful when working with sparse collections or associative arrays.

By using the NEXT Method in PL/SQL, you can safely iterate through collections without assuming sequential subscriptsโ€”making your code more robust and error-resistant.

What is the NEXT Method in PL/SQL?

The NEXT method returns the next index value (or subscript) in a collection after a specified one.

  • Works with numeric and string-based indexes

  • Returns NULL if there is no higher index

  • Raises an exception if the collection is null (unless checked with EXISTS)

Syntax of NEXT Method in PL/SQL

collection_name.NEXT(index_value)
  • Returns:

    • PLS_INTEGER for numeric indexes

    • VARCHAR2 for associative arrays with string indexes

    • NULL if the passed index is the highest one

Example: Using NEXT Method with String Indexes

DECLARE
   TYPE assoc_array IS TABLE OF INTEGER INDEX BY VARCHAR2(10);
   my_list assoc_array;
BEGIN
   my_list('Apple') := 10;
   my_list('Mango') := 20;
   my_list('Banana') := 30;

   DBMS_OUTPUT.PUT_LINE('FIRST: ' || my_list.FIRST);
   DBMS_OUTPUT.PUT_LINE('NEXT of FIRST: ' || my_list.NEXT(my_list.FIRST));

   DBMS_OUTPUT.PUT_LINE('LAST: ' || my_list.LAST);
   DBMS_OUTPUT.PUT_LINE('NEXT of LAST: ' || TO_CHAR(my_list.NEXT(my_list.LAST)));
END;
/

Output:

FIRST: Apple
NEXT of FIRST: Banana
LAST: Mango
NEXT of LAST: 

Explanation

In associative arrays with string keys, PL/SQL internally sorts keys alphabetically based on the current NLS_SORT session setting. Hereโ€™s the order in the example:
Apple โ†’ Banana โ†’ Mango

Thus:

  • NEXT('Apple') returns 'Banana'

  • NEXT('Mango') returns NULL (no higher subscript)

Use Cases of the NEXT Method in PL/SQL

 

Use CaseDescription
Sparse ArraysSkip over deleted or missing elements
Associative ArraysSafely loop through keys
Dynamic IndexingAvoid hardcoded index assumptions
Backward NavigationUse with PRIOR to go back if needed

Best Practices for NEXT Method in PL/SQL

  • Always verify that the collection is not null before using NEXT.

  • Combine FIRST, NEXT, and EXISTS for safe iteration in sparse or associative collections.

  • Do not assume keys are ordered numerically when using string indexes.

๐Ÿ“˜ AmantPoint Exclusive Learning Series
ยฉ 2025 AmantPoint. All rights reserved. Educational content for developers and learners.

Scroll to Top