BigQuery’s HAVING MAX finds the latest timestamp, not necessarily the latest status
If two events share a timestamp, use a source sequence that actually defines their order—or report that the latest status is ambiguous.
“Show the latest status for each order” sounds like a request for one row per order. In BigQuery, ANY_VALUE(status HAVING MAX(event_ts)) can return one value without establishing which event came last. The GoogleSQL aggregate reference says HAVING MAX keeps all rows at the maximum value, and that the row picked by ANY_VALUE in its tied example is nondeterministic, not random. Getting the same answer on two runs is not evidence that the query resolves the tie.
Separate the timestamp from the event order
Suppose order 42 has two events at 10:00:00: packed at source sequence 17 and shipped at sequence 18. Both satisfy HAVING MAX(event_ts), so that clause alone cannot distinguish them. If the source guarantees that higher sequence numbers come later among events with the same timestamp, the business answer is shipped. If it does not, a reproducible arbitrary choice still doesn't tell you which event happened last.
Replacing the aggregate with ROW_NUMBER() ordered only by timestamp doesn't solve this problem. The GoogleSQL numbering reference explicitly leaves row numbering within a peer group nondeterministic. Under the source guarantee above, add the sequence to the window order:
WITH ranked AS (
SELECT order_id, status, event_ts, source_sequence,
ROW_NUMBER() OVER (
PARTITION BY order_id
ORDER BY event_ts DESC, source_sequence DESC
) AS rn
FROM order_events
WHERE event_ts IS NOT NULL
)
SELECT order_id, status, event_ts, source_sequence
FROM ranked
WHERE rn = 1;
This example assumes a non-null sequence unique within each order and timestamp; it intentionally excludes undated events. An order with only undated events won't appear. If those orders must appear, decide how to label them before treating the query as a complete status report.
Give the SQL agent a tie it has to resolve
Put the two rows for order 42 in an acceptance test and require shipped, not just one output row. Then remove the source-order guarantee from the test and require the agent to flag the ambiguity or show both candidates. The test checks whether the agent knows what makes a row latest, rather than whether it can make the result look like one row per order. The example is illustrative and was not run against a live BigQuery dataset.
sources
- Google Cloud: Aggregate function calls, HAVING MAX and HAVING MINdocs.cloud.google.com
- Google Cloud: Numbering functions, ROW_NUMBERdocs.cloud.google.com
comments · 0
- EKOS’s pending BIRD submission pairs a SQLite-tuned run with a separate hidden-test scoreDec 3, 2026
- MotherDuck rolls out DuckDB 2.0 and reports faster cold reads, not faster agent answersDec 3, 2026
- Oracle Select AI can use two definitions of the same metric. Source order won’t break the tieDec 3, 2026