> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Array(T)

> Documentación del tipo de datos Array en ClickHouse

Un array de elementos de tipo `T`, con el índice inicial del array en 1. `T` puede ser cualquier tipo de datos, incluido un array.

## Crear un Array

Puede usar una función para crear un array:

```sql theme={null}
array(T)
```

También puedes usar `[]`.

```sql theme={null}
[]
```

También se admite la sintaxis del constructor de arrays del estándar SQL, PostgreSQL y Trino: `ARRAY[1, 2]` equivale a `[1, 2]`.
El tipo de datos también puede escribirse como `ARRAY(T)`.

Ejemplo de cómo crear un array:

```sql theme={null}
SELECT array(1, 2) AS x, toTypeName(x)
```

```text theme={null}
┌─x─────┬─toTypeName(array(1, 2))─┐
│ [1,2] │ Array(UInt8)            │
└───────┴─────────────────────────┘
```

```sql theme={null}
SELECT [1, 2] AS x, toTypeName(x)
```

```text theme={null}
┌─x─────┬─toTypeName([1, 2])─┐
│ [1,2] │ Array(UInt8)       │
└───────┴────────────────────┘
```

## Trabajar con tipos de datos

Al crear un array sobre la marcha, ClickHouse define automáticamente el tipo del argumento como el tipo de datos más pequeño capaz de almacenar todos los argumentos indicados. Si hay valores [Nullable](https://clickhouse.com/docs/es/reference/data-types/nullable.md) o valores literales [NULL](https://clickhouse.com/docs/es/reference/settings/formats/input-format.md#input_format_null_as_default), el tipo de los elementos del array también pasa a ser [Nullable](https://clickhouse.com/docs/es/reference/data-types/nullable.md).

Si ClickHouse no puede determinar el tipo de datos, genera una excepción. Por ejemplo, esto ocurre al intentar crear un array con cadenas y números al mismo tiempo (`SELECT array(1, 'a')`).

Ejemplos de detección automática de tipos de datos:

```sql theme={null}
SELECT array(1, 2, NULL) AS x, toTypeName(x)
```

```text theme={null}
┌─x──────────┬─toTypeName(array(1, 2, NULL))─┐
│ [1,2,NULL] │ Array(Nullable(UInt8))        │
└────────────┴───────────────────────────────┘
```

Si intenta crear un Array con tipos de datos incompatibles, ClickHouse lanza una excepción:

```sql theme={null}
SELECT array(1, 'a')
```

```text theme={null}
Received exception from server (version 1.1.54388):
Code: 386. DB::Exception: Received from localhost:9000, 127.0.0.1. DB::Exception: There is no supertype for types UInt8, String because some of them are String/FixedString and some of them are not.
```

## Tamaño de Array

Es posible conocer el tamaño de un array usando la subcolumna `size0` sin leer toda la columna. Para arrays multidimensionales, puedes usar `sizeN-1`, donde `N` es la dimensión deseada.

**Ejemplo**

```sql title="Query" theme={null}
CREATE TABLE t_arr (`arr` Array(Array(Array(UInt32)))) ENGINE = MergeTree ORDER BY tuple();

INSERT INTO t_arr VALUES ([[[12, 13, 0, 1],[12]]]);

SELECT arr.size0, arr.size1, arr.size2 FROM t_arr;
```

```text title="Response" theme={null}
┌─arr.size0─┬─arr.size1─┬─arr.size2─┐
│         1 │ [2]       │ [[4,1]]   │
└───────────┴───────────┴───────────┘
```

## Lectura de subcolumnas anidadas de Array

Si el tipo anidado `T` dentro de `Array` tiene subcolumnas (por ejemplo, si es una [tupla con nombre](https://clickhouse.com/docs/es/reference/data-types/tuple.md)), puede leer sus subcolumnas desde un tipo `Array(T)` con los mismos nombres de subcolumna. El tipo de una subcolumna será un `Array` del tipo de la subcolumna original.

**Ejemplo**

```sql theme={null}
CREATE TABLE t_arr (arr Array(Tuple(field1 UInt32, field2 String))) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t_arr VALUES ([(1, 'Hello'), (2, 'World')]), ([(3, 'This'), (4, 'is'), (5, 'subcolumn')]);
SELECT arr.field1, toTypeName(arr.field1), arr.field2, toTypeName(arr.field2) from t_arr;
```

```test theme={null}
┌─arr.field1─┬─toTypeName(arr.field1)─┬─arr.field2────────────────┬─toTypeName(arr.field2)─┐
│ [1,2]      │ Array(UInt32)          │ ['Hello','World']         │ Array(String)          │
│ [3,4,5]    │ Array(UInt32)          │ ['This','is','subcolumn'] │ Array(String)          │
└────────────┴────────────────────────┴───────────────────────────┴────────────────────────┘
```
