# max

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

Returns the largest non-NULL value, or up to `n` such values.

## Syntax

```scopeql
max(<expr>)
max(<expr>, n => <n>)
```

## Arguments

| Argument | Type                  | Description                                                                               |
| -------- | --------------------- | ----------------------------------------------------------------------------------------- |
| `<expr>` | Any type except `any` | Values to compare. Cast an `any` expression to the intended comparison type first.        |
| `n`      | `int`                 | Optional non-negative constant. Number of values to return as an array. Must not be NULL. |

## Returns

Without `n`, returns the same type as `<expr>`, or NULL for empty or all-NULL input.

With `n`, returns `array` of up to `n` non-NULL values in descending order. Keeps duplicates. Returns `[]` if `n` is 0 or there are no non-NULL values.

## Examples

Return the slowest duration and the three slowest durations per service. Values are milliseconds.

```scopeql
VALUES
    ('checkout', 95), ('checkout', 160), ('checkout', 480), ('checkout', 1200),
    ('catalog', 25), ('catalog', 40), ('catalog', 75), ('catalog', 140)
SELECT $0 AS service, $1 AS latency_ms
GROUP BY service
AGGREGATE max(latency_ms) AS slowest_ms, max(latency_ms, n => 3) AS top_three_ms
ORDER BY service
```

```text
+----------+------------+----------------+
| service  | slowest_ms | top_three_ms   |
+----------+------------+----------------+
| catalog  | 140        | [140,75,40]    |
| checkout | 1200       | [1200,480,160] |
+----------+------------+----------------+
```

Use [`max_by`](https://www.scopedb.io/docs/reference/functions/aggregate/max_by.md) to return details from the selected request.
