# array\_agg

[Read this page in HTML](https://www.scopedb.io/docs/reference/functions/aggregate/array_agg)

Collects values into an array.

## Syntax

```scopeql
array_agg(<expr>)
```

## Arguments

| Argument | Type     | Description  |
| -------- | -------- | ------------ |
| `<expr>` | Any type | Input value. |

## Returns

Returns `array`. Includes NULL values. Returns `[]` for empty input.

## Usage notes

Use `WITHIN GROUP ORDER BY` before `AGGREGATE` to define element order.

## Examples

Collect each session’s events in sequence, even when the input rows arrive out of order:

```scopeql
VALUES
    ('s-17', 3, 'payment_failed'), ('s-17', 1, 'cart_viewed'),
    ('s-17', 2, 'checkout_started'), ('s-42', 2, 'payment_completed'),
    ('s-42', 1, 'checkout_started')
SELECT $0 AS session_id, $1 AS sequence, $2 AS event
GROUP BY session_id
WITHIN GROUP ORDER BY sequence
AGGREGATE array_agg(event) AS journey
ORDER BY session_id
```

```text
+------------+-----------------------------------------------------+
| session_id | journey                                             |
+------------+-----------------------------------------------------+
| s-17       | ["cart_viewed","checkout_started","payment_failed"] |
| s-42       | ["checkout_started","payment_completed"]            |
+------------+-----------------------------------------------------+
```

`ORDER BY session_id` sorts result rows; `WITHIN GROUP ORDER BY sequence` sorts the elements inside each array.
