max

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

Syntax

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

Arguments

ArgumentTypeDescription
<expr>Any type except anyValues to compare. Cast an any expression to the intended comparison type first.
nintOptional 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.

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
+----------+------------+----------------+
| service  | slowest_ms | top_three_ms   |
+----------+------------+----------------+
| catalog  | 140        | [140,75,40]    |
| checkout | 1200       | [1200,480,160] |
+----------+------------+----------------+

Use max_by to return details from the selected request.