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.
NULLif 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
| Method | Returns | Use Case |
|---|---|---|
FIRST | Lowest index | Begin iteration, check lower bound |
LAST | Highest index | End iteration, check upper bound |
Best Practices for LAST Method in PL/SQL
Use
LASTwithPRIORfor reverse iteration.Always verify
LASTis notNULLbefore using it in loops or access.Avoid using
FOR i IN FIRST..LASTif your collection uses string indexes.Use
LASTwithEXISTSto safely access sparse arrays.
AmantPoint Exclusive Learning Series
© 2025 AmantPoint. All rights reserved. Educational content for developers and learners.
