BigQuery’s LAST_VALUE can return the current status instead of the final status
For an event-history query that keeps every row, a full-partition frame and a deterministic event order make “final” explicit.
“Show every order event alongside the order’s final status” sounds like a job for LAST_VALUE. It is, but only if the window reaches the final event. BigQuery defines LAST_VALUE as the value from the last row in the current window frame, not the last row in the partition. Google’s window reference explicitly shows an ordered LAST_VALUE without a frame as equivalent to RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
Keep the event rows; widen the frame
Take a synthetic order with three events at distinct timestamps: placed, paid, then shipped. With LAST_VALUE(status) OVER (PARTITION BY order_id ORDER BY event_ts), the expected result is placed, paid, and shipped on the three respective rows. The query runs and every value looks plausible, but the column is not the final status repeated on each row. For that output, adapt the full-partition frame in Google’s example:
SELECT
order_id,
event_ts,
event_id,
status,
LAST_VALUE(status) OVER (
PARTITION BY order_id
ORDER BY event_ts, event_id
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS final_status
FROM order_events;
On that fixture, final_status should be shipped on all three rows. The example assumes event_id is a valid tie-breaker when timestamps match. If your data has a source sequence that defines which tied event happened last, use that instead; a stable sort key is not necessarily the business definition of event order.
Make a null final event a separate test
LAST_VALUE includes nulls by default. If the fixture ends with a fourth event whose status is NULL, the full-frame expression returns NULL on every row. LAST_VALUE(status IGNORE NULLS) with the same frame instead returns shipped on every row. Those are different questions: “What did the final event say?” versus “What was the last known status?”
For a SQL-agent regression test, assert both the output row count and the expected status on the first event. Checking only the last event would let the default-frame query pass the three-event case. Then add a tied timestamp and a null final event, so the test checks ordering and missing-value semantics separately from the frame. These are expected outputs derived from the documented behavior, not timings or results from a warehouse run.
sources
- Google Cloud: LAST_VALUE navigation functiondocs.cloud.google.com
- Google Cloud: Window function calls and default framesdocs.cloud.google.com
comments · 0