# Array

`Array(T)` stores an ordered collection of values of type `T`. Arrays can be empty and can contain other arrays or typed collections.

## Creating an Array

Construct an array with `array(...)`, or pass standard JSON array text to a typed column or cast. An explicit type is useful for empty arrays and when the element range must be checked.

```sql
SELECT array(1, 2, 3), CAST('[]' AS Array(UInt8))
FORMAT csv;
```

```text
"[1,2,3]","[]"
```

Nested declarations preserve their element contracts even when the arrays are empty:

```sql
SELECT CAST('[[1,2],[]]' AS Array(Array(UInt8)))
FORMAT csv;
```

```text
"[[1,2],[]]"
```

## Working with Data Types

```text
Array(T)
```

* `T` — The element type. Every element is converted and validated against this type.

Use `Array(Nullable(T))` to allow missing elements. A top-level array column can itself be `NULL` unless declared `NOT NULL`.

## Array Size

Use `array_length` to count array elements. An empty array has length zero;
`NULL` members still count as elements.

```sql
SELECT array_length(array(1, 2, 3)),
       array_length(CAST('[]' AS Array(Int32)))
FORMAT csv;
```

```text
3,0
```

## Accessing elements

`array_element(array, index)` uses positions starting at 1. Negative positions count from the end. Position 0 raises `INVALID_ARGUMENT`. A position outside the array returns the declared element type's default, such as zero or an empty string; nullable elements default to `NULL`.

```sql
SELECT array_element(array(10, 20), 1),
       array_element(array(10, 20), -1),
       array_element(CAST('[10,20]' AS Array(UInt8)), 3)
FORMAT csv;
```

```text
10,20,0
```

Use the function syntax; bracket access such as `tags[1]` and lambda expressions are not implemented.

## Example

### Storing nullable measurements

```sql
CREATE TABLE samples(id UInt32, readings Array(Nullable(UInt8)));
INSERT INTO samples VALUES (1, '[10,null,20]');
```

```sql
SELECT id, readings, array_length(readings) AS positions
FROM samples
FORMAT csv;
```

```text
1,"[10,null,20]",3
```

See [array functions](https://coordinatordb.com/docs/reference/functions/regular-functions/array-functions) for membership, slicing and other operations, and [`array_agg`](https://coordinatordb.com/docs/reference/functions/aggregate-functions/array-agg) for collecting rows into an array.
