MAX_BY

Applies to: ✅ Data 360 SQL ✅ Tableau Hyper API

Returns the <value> from the row whose <key> is greatest among all rows in the aggregate (or within each group when used with GROUP BY).

  • <value>: Any expression whose result is returned when its row wins the comparison. The aggregate result type matches this expression’s type.
  • <key>: The expression MAX-BY uses to order the rows. The type must support comparison.
  • IGNORE NULLS: Skips rows containing NULL values. This is the default behavior.
  • RESPECT NULLS: Considers rows containgin NULL values.

The <value> from the row with the maximum <key> among considered rows.

Null handling:

  • You can combine max_by with other aggregates, GROUP BY, HAVING, subqueries, and expressions in the arguments (for example, max_by(upper(name), score * 2)).
  • max_by only supports a single value to sort on. To sort using multiple sort criteria, use FIRST_VALUE WITHIN GROUP.
  • If the aggregate has no input rows (empty table or empty group), the result is NULL.
  • If every row has a NULL key, those rows are skipped; if no row has a non-NULL key, the result is NULL.
  • If the winning row’s <value> is NULL, the result is NULL (the key still determines which row wins).

Tie-breaking: If multiple rows share the same maximum key, one of the tied <value> results is returned; which tied row wins is implementation-dependent.

  • DISTINCT is not supported (for example, max_by(DISTINCT name, score) is a syntax error).
  • Rows with a NULL <key> are ignored when searching for the maximum key.
  • You can combine max_by with other aggregates, GROUP BY, HAVING, subqueries, and expressions in the arguments (for example, max_by(upper(name), score * 2)).

Returns the name and score from the row with the highest score.

Returns 'David'.

Uses GROUP BY so each region gets its own arg-max product and returns the regions and their maximum revenue.

Returns one row per region. For example South / 'A' and North / 'B'.

Keys that are NULL are skipped. In this example, the largest non-NULL key is 15, and that row’s value is NULL.

Returns NULL.