ARRAY_LAST

Return the last element of an array.

Category: collectionReturns: TDialect: PostgreSql

Syntax

ARRAY_LAST(array)

Description

## Overview Returns the final element of the array in its stored order. ARRAY_LAST is the idiomatic shortcut for reading the tail of an array without writing explicit size-and-index arithmetic, and it pairs naturally with ARRAY_FIRST to capture the endpoints of an ordered collection. Typical uses include extracting the exit event from a session trail, reporting the most recently added tag in an append-only list, and implementing a tail accessor analogous to the list-last operation in functional languages. ## Behavior - Returns the element at position ARRAY_SIZE(array), that is the rightmost element in stored order. - Element type matches the array's element type, including STRUCT, MAP, and nested ARRAY elements. - Never mutates the input. - Does not reorder or sort. If the array was built from an unordered source, the tail is similarly unordered. - Operationally equivalent to ELEMENT_AT(array, -1) or ELEMENT_AT(array, ARRAY_SIZE(array)). ## Null and empty handling - NULL input array returns NULL. - Empty array returns NULL; no error is raised. - If the last element itself is NULL, the result is NULL. ARRAY_LAST cannot distinguish an empty array from an array whose last element is NULL. ## Compatibility - Matches the array/map SQL convention for tail access with 1-based indexing. - Equivalent to ELEMENT_AT(array, -1) in dialects that support negative indexing, and to array[ARRAY_SIZE(array)] where bracket indexing is available.

Parameters

NameTypeDescription
arraySpecifies the input array. The element at position ARRAY_SIZE(array) is returned in its stored order.

Examples

-- Last element of a numeric array
SELECT ARRAY_LAST(ARRAY[10, 20, 30]);  -- 30
-- Last event in a per-session trail
SELECT session_id, ARRAY_LAST(events) AS exit_event
FROM analytics.events.user_sessions;
-- Last element is NULL
SELECT ARRAY_LAST(ARRAY[1, 2, CAST(NULL AS INT)]);  -- NULL
-- Empty array returns NULL
SELECT ARRAY_LAST(CAST(ARRAY() AS ARRAY<INT>));  -- NULL
-- NULL input returns NULL
SELECT ARRAY_LAST(CAST(NULL AS ARRAY<INT>));  -- NULL
-- Use with ARRAY_AGG to return the final event per group
SELECT user_id, ARRAY_LAST(ARRAY_AGG(event_type)) AS final_event
FROM analytics.events.user_sessions
GROUP BY user_id;

Pitfalls

See Also

Open in interactive docs →   DeltaForge home →