LAST Method in PL/SQL โ€“ Usage with Numeric and String Indexes

The LAST Method in PL/SQL is a built-in collection function that returns the highest index (subscript) currently in use. Whether you’re working with nested tables, varrays, or associative arrays, the LAST method helps you safely determine the upper bound of the collection.

This guide explores the syntax, behavior, and examples for using the LAST Method in PL/SQL with both numeric and string index types.

What is the LAST Method in PL/SQL?

The LAST method is a function that returns the last (highest) index that currently exists in a collection.

  • For numeric-indexed collections, it returns a PLS_INTEGER.

  • For associative arrays with string indexes, it returns a VARCHAR2.

If the collection is empty, LAST returns NULL.

Syntax of LAST Method in PL/SQL

collection_name.LAST

Returns:

  • The highest valid subscript value in the collection.

  • NULL if the collection has no elements.

Example: LAST Method with String Indexes

DECLARE
   -- Define an associative array with VARCHAR2 keys
   TYPE number_table IS TABLE OF INTEGER INDEX BY VARCHAR2(9 CHAR);
   number_list number_table;
BEGIN
   -- Insert three elements using string keys
   number_list('One') := 1;
   number_list('Two') := 2;
   number_list('Nine') := 9;

   -- Display FIRST and NEXT
   DBMS_OUTPUT.PUT_LINE('FIRST Index [' || number_list.FIRST || ']');
   DBMS_OUTPUT.PUT_LINE('NEXT Index [' || number_list.NEXT(number_list.FIRST) || ']');

   -- Display LAST and PRIOR
   DBMS_OUTPUT.PUT_LINE(CHR(10) || 'LAST Index [' || number_list.LAST || ']');
   DBMS_OUTPUT.PUT_LINE('PRIOR Index [' || number_list.PRIOR(number_list.LAST) || ']');
END;
/

Output:

FIRST Index [Nine]
NEXT  Index [One]

LAST  Index [Two]
PRIOR Index [One]

Behavior with String Indexes

When used with associative arrays that have string indexes, the LAST method returns the alphabetically last key, based on the NLS_SORT session setting.

In the example above, although 'Two' was inserted last, it was returned as LAST because it comes last in alphabetical order (Nine, One, Two).

LAST vs FIRST in PL/SQL

MethodReturnsUse Case
FIRSTLowest indexBegin iteration, check lower bound
LASTHighest indexEnd iteration, check upper bound

Best Practices for LAST Method in PL/SQL

  • Use LAST with PRIOR for reverse iteration.

  • Always verify LAST is not NULL before using it in loops or access.

  • Avoid using FOR i IN FIRST..LAST if your collection uses string indexes.

  • Use LAST with EXISTS to safely access sparse arrays.

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

Scroll to Top