Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
Overview and Dialect Availability¶
In GoogleSQL (formerly ZetaSQL, used by BigQuery and Cloud Spanner),
ANY_VALUE(c1 HAVING MAX ts) returns the value of c1
from a row where ts attains its maximum value within each group
(and HAVING MIN ts does the same for the minimum).
BigQuery also provides MAX_BY(c1, ts) and MIN_BY(c1, ts) as direct synonyms
for ANY_VALUE(c1 HAVING MAX ts) and ANY_VALUE(c1 HAVING MIN ts).
If multiple rows tie for the maximum ts,
GoogleSQL skips rows where c1 is NULL (as if IGNORE NULLS were set)
and nondeterministically picks one of the remaining tied rows.
| Engine / Dialect | Equivalent Function |
|---|---|
| GoogleSQL / BigQuery | ANY_VALUE(x HAVING MAX y) or MAX_BY(x, y) |
| DuckDB / Spark SQL / Trino / Snowflake | MAX_BY(x, y) |
| ClickHouse | argMax(x, y) |
| PostgreSQL | DISTINCT ON, ORDER BY y DESC LIMIT 1, or FIRST_VALUE |
Watch Out for NULL in ts¶
When using ANY_VALUE(c1 HAVING MAX ts), be careful if ts can be NULL:
Rows with
ts IS NULLare ignored byHAVING MAX:HAVING MAX tsevaluates the maximum over non-NULLvalues ofts. If all rows in a group havets IS NULL, the result isNULL.A
NULLc1on the winning row(s) still returnsNULL:HAVING MAX tsnarrows the candidate rows to those with the maximumtsfirst, andANY_VALUEselects from that restricted pool (preferring non-NULLc1values if any exist among the tied rows). If every row tied at the maximumtshasc1 IS NULL, the function returnsNULLrather than falling back to an earlier row with a non-NULLc1.Guarding
NULLtimestamps: If you wantNULLtimestamps treated as the earliest possible time (so non-NULLtimestamps always win, while still allowing aNULL-timestamp row to be picked if no non-NULLtimestamp exists), useCOALESCEwith a minimum sentinel timestamp such asTIMESTAMP '0001-01-01 00:00:00 UTC':SELECT id, ANY_VALUE(c1 HAVING MAX COALESCE(ts, TIMESTAMP '0001-01-01 00:00:00 UTC')) AS latest_c1 FROM events GROUP BY id;If
NULLtimestamps should be excluded altogether, filter them out withWHERE ts IS NOT NULL.
Both Arguments Can Be Expressions: As-Of Timestamp t Tricks¶
Both c1 and ts in ANY_VALUE(c1 HAVING MAX ts) can be arbitrary expressions.
This makes it possible to compute the latest value up to a cutoff timestamp t (ts <= t)
in a single GROUP BY pass without a separate subquery or join.
Trick 1: Sentinel Timestamp vs. NULL for ts > t¶
You can demote rows after t by mapping their having_expression to a sentinel minimum timestamp
that does not appear in your data:
-- Caution: if ALL rows in a group have ts > t, every row ties on the sentinel timestamp
-- and ANY_VALUE(c1 ...) will leak a post-t row's c1!
ANY_VALUE(c1 HAVING MAX IF(ts <= t, ts, TIMESTAMP '0001-01-01 00:00:00 UTC'))Notice the edge case: if a group has no rows with ts <= t,
every row gets the sentinel timestamp 0001-01-01 00:00:00 UTC,
so ANY_VALUE will still pick one of the ts > t rows.
Alternatively, mapping post-t timestamps to NULL causes HAVING MAX to ignore them completely
and return NULL when no row satisfies ts <= t:
ANY_VALUE(c1 HAVING MAX IF(ts <= t, ts, NULL))Trick 2: Transform Both Value and Timestamp Expressions¶
To prevent leaking a post-t value when using a sentinel timestamp—or when you want an explicit non-NULL default
(such as 0) whenever no row satisfies ts <= t—transform both arguments:
Map timestamps
> tto a smaller sentinel timestamp that will not appear in the database.Map values
c1corresponding to timestamps> ttoNULLor a default/smallest value.
Note that when the masked value is NULL, this produces the same result as Trick 1’s IF(ts <= t, ts, NULL);
Trick 2 is mainly useful when you want an explicit non-NULL fallback value such as 0.
SELECT
id,
ANY_VALUE(
IF(ts <= t, c1, NULL)
HAVING MAX IF(ts <= t, ts, TIMESTAMP '0001-01-01 00:00:00 UTC')
) AS c1_as_of_t,
ANY_VALUE(
IF(ts <= t, val, 0)
HAVING MAX IF(ts <= t, ts, TIMESTAMP '0001-01-01 00:00:00 UTC')
) AS val_as_of_t_or_zero
FROM events
GROUP BY id;Even if every row in a group has ts > t and ties on the sentinel timestamp,
all candidate values in that tied pool have already been masked to NULL (or 0),
so no post-t data can leak through.
Comparison with Window Functions (ROW_NUMBER / QUALIFY)¶
Prefer
ANY_VALUE(... HAVING MAX ...)when you already have aGROUP BY, only need one or a few columns at the latest timestamp, or want to compute multiple as-of horizons (t1,t2,t3) in a single table scan:SELECT id, ANY_VALUE(IF(ts <= t1, c1, NULL) HAVING MAX IF(ts <= t1, ts, NULL)) AS c1_t1, ANY_VALUE(IF(ts <= t2, c1, NULL) HAVING MAX IF(ts <= t2, ts, NULL)) AS c1_t2 FROM events GROUP BY id;Prefer
QUALIFY ROW_NUMBER() OVER (PARTITION BY id ORDER BY ts DESC, tie_breaker DESC) = 1when you need deterministic multi-column tie-breaking or need to project many columns from the winning row without repeatingHAVING MAXon each column.