Retrieving the first and last array elements (ARRAY_FIRST, ARRAY_LAST functions)
Retrieving the first and last elements in a simple array can most easily be done by using the ARRAY_FIRST and ARRAY_LAST functions.
Before you begin
- Read: Ordinary array data type
- Read: Restrictions on the array data type
- Privileges required to execute the SET statement
About this task
Procedure
Define a SET statement:
- Declare and specify a variable that is of the same type as the array element.
- Specify the assignment symbol, '='.
- Specify the name of the ARRAY_FIRST or ARRAY_LAST function and within the required brackets, the name of the array.
Results
Example
firstPhone index 0 1 2 3
phone '416-223-2233' '416-933-9333' '416-887-8887' '416-722-7227'
If the following SQL statement is executed:SET firstPhoneIx = ARRAY_FIRST(phones);
The
variable firstPhoneIx will have the value 0. This would be
true even if the element value in this position was NULL.The following
SET statement accesses the element value in the first position in
the array:
SET firstPhone = A[ARRAY_FIRST(A)]
What to do next
- Verify the SQL statement syntax of the SET statement and execute the statement again.
- Verify that the local variable is of the correct data type.
- Verify that the array was created successfully and currently exists.