Returns the position index (starting from 1) for each element in the array. The function generates corresponding position numbers for each element in the array.
array_enumerate(ARRAY<T> arr)
arr:ARRAY type, the array for which to generate position indices. Supports column names or constant values.Supported types for T:
Return type: ARRAY
Return value meaning:
Usage notes:
Query Examples:
Generate position indices for an array:
SELECT array_enumerate([1, 2, 1, 4, 5]); +----------------------------------+ | array_enumerate([1, 2, 1, 4, 5]) | +----------------------------------+ | [1, 2, 3, 4, 5] | +----------------------------------+
Empty array returns empty array:
SELECT array_enumerate([]); +----------------------+ | array_enumerate([]) | +----------------------+ | [] | +----------------------+
Array containing null values, null elements also generate position indices:
SELECT array_enumerate([1, null, 3, null, 5]); +--------------------------------------------+ | array_enumerate([1, null, 3, null, 5]) | +--------------------------------------------+ | [1, 2, 3, 4, 5] | +--------------------------------------------+
Complex type examples:
Nested array types:
SELECT array_enumerate([[1,2],[3,4],[5,6]]); +----------------------------------------+ | array_enumerate([[1,2],[3,4],[5,6]]) | +----------------------------------------+ | [1, 2, 3] | +----------------------------------------+
Map types:
SELECT array_enumerate([{'k':1},{'k':2},{'k':3}]); +----------------------------------------------+ | array_enumerate([{'k':1},{'k':2},{'k':3}]) | +----------------------------------------------+ | [1, 2, 3] | +----------------------------------------------+
Struct types:
SELECT array_enumerate(array(named_struct('name','Alice','age',20),named_struct('name','Bob','age',30))); +----------------------------------------------------------------------------------------+ | array_enumerate(array(named_struct('name','Alice','age',20),named_struct('name','Bob','age',30))) | +----------------------------------------------------------------------------------------+ | [1, 2] | +----------------------------------------------------------------------------------------+
Error when parameter count is wrong:
SELECT array_enumerate([1,2,3], [4,5,6]); ERROR 1105 (HY000): errCode = 2, detailMessage = Can not found function 'array_enumerate' which has 2 arity. Candidate functions are: [array_enumerate(Expression)]
Error when passing non-array type:
SELECT array_enumerate('not_an_array'); ERROR 1105 (HY000): errCode = 2, detailMessage = Can not find the compatibility function signature: array_enumerate(VARCHAR(12))
ARRAY, ENUMERATE, ARRAY_ENUMERATE