Clase de error INVALID_ARRAY_INDEX

SQLSTATE: 22003

El índice está <indexValue> fuera de los límites. La matriz tiene <arraySize> elementos. Use la función SQL get() para tolerar el acceso al elemento en un índice no válido y devolver NULL en su lugar. Si es necesario, establezca <ansiConfig> en "false" para omitir este error.

Parámetros

  • indexValue: el índice solicitado en la matriz.
  • arraySize: la cardinalidad de la matriz.
  • ansiConfig: el valor de configuración para modificar el modo ANSI.

Explicación

A diferencia de element_at y elt, una referencia indexValue a una matriz mediante la sintaxis arrayExpr[indexValue] debe estar entre 0 para el primer elemento y arraySize - 1 para el último elemento.

No se permite un valor negativo indexValue o un valor mayor o igual a arraySize.

Mitigación

La mitigación de este error depende de la intención:

Ejemplos

-- An INVALID_ARRAY_INDEX error because of mismatched indexing
> SELECT array('a', 'b', 'c')[index] FROM VALUES(1), (3) AS T(index);
  [INVALID_ARRAY_INDEX] The index 3 is out of bounds. The array has 3 elements. If necessary set "ANSI_MODE" to false to bypass this error.

-- Using element_at instead for 1-based indexing
> SELECT element_at(array('a', 'b', 'c'), index) FROM VALUES(1), (3) AS T(index);
  a
  c

-- Adjusting the index to be 0-based
> SELECT array('a', 'b', 'c')[index -1] FROM VALUES(1), (3) AS T(index);

-- Tolerating out of bound array index with adjustment to 1-based indexing
> SELECT try_element_at(array('a', 'b', 'c'), index + 1) FROM VALUES(1), (3) AS T(index);
  b
  NULL

-- An INVALID_ARRAY_INDEX error because of negative index
> SELECT array('a', 'b', 'c')[index] FROM VALUES(-1), (2) AS T(index);
  [INVALID_ARRAY_INDEX] The index -1 is out of bounds. The array has 3 elements. If necessary set "ANSI_MODE" to "false" to bypass this error.

-- Using element_at to index relative to the end of the array
> SELECT element_at(array('a', 'b', 'c'), index) FROM VALUES(-1), (2) AS T(index);
  c
  b

-- Tolerating an out of bound index by setting ansiConfig in Databricks SQL
> SET ANSI_MODE = false;
> SELECT array('a', 'b', 'c')[index] FROM VALUES(1), (3) AS T(index);
  b
  NULL
> SET ANSI_MODE = true;

-- Tolerating an out of bound index by setting ansiConfig in Databricks Runtime
> SET spark.sql.ansi.enabled = false;
> SELECT array('a', 'b', 'c')[index] FROM VALUES(1), (3) AS T(index);
  b
  NULL
> SET spark.sql.ansi.enabled = true;