SQL Dojo
Keyword

Window frames: ROWS, RANGE and the default

Which rows a window function sees: ROWS or RANGE, the default frame that comes with an ORDER BY, and why LAST_VALUE returns the current row.

A window function with an ORDER BY works on a frame: by default, the rows from the start of the partition to the current one. Write the frame yourself for a moving average, a strict row-by-row total, or the whole partition.

SELECT month, revenue,
       SUM(revenue) OVER (ORDER BY month) AS running_total,
       AVG(revenue) OVER (ORDER BY month
         ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS avg_3_months,
       LAST_VALUE(revenue) OVER (ORDER BY month
         ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_month
FROM monthly_revenue;

ROWS counts rows: 2 PRECEDING is two rows back, whatever their dates. RANGE works on the values of the ORDER BY: RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW is the last 7 calendar days, empty ones included. The default, an ORDER BY with no frame, is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: rows tied on the ORDER BY get the same running total.

The trap. LAST_VALUE(x) OVER (ORDER BY …) returns the current row's value, since the default frame ends there. Write ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING, or take FIRST_VALUE with a descending sort.

On your warehouse. On Snowflake, the default frame of LAST_VALUE is the whole partition: write the frame anyway, so the query means the same everywhere. BigQuery's RANGE with an offset needs a number: ORDER BY UNIX_DATE(day) RANGE BETWEEN 6 PRECEDING AND CURRENT ROW. Postgres and DuckDB also have GROUPS frames (N distinct values back); Snowflake and BigQuery do not.

The trap

WITH sales(sale_id, day, amount) AS (
  VALUES (1, DATE '2025-03-01', 10), (2, DATE '2025-03-02', 20),
         (3, DATE '2025-03-02', 20), (4, DATE '2025-03-03', 40)
)
SELECT sale_id, day, amount,
       SUM(amount) OVER (ORDER BY day) AS running,
       LAST_VALUE(amount) OVER (ORDER BY day) AS last_amount
FROM sales
ORDER BY sale_id;
sale_iddayamountrunninglast_amount
12025-03-01101010
22025-03-02205020
32025-03-02205020
42025-03-03409040
Try it in Randori

The fix

WITH sales(sale_id, day, amount) AS (
  VALUES (1, DATE '2025-03-01', 10), (2, DATE '2025-03-02', 20),
         (3, DATE '2025-03-02', 20), (4, DATE '2025-03-03', 40)
)
SELECT sale_id, day, amount,
       SUM(amount) OVER (ORDER BY day, sale_id
         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running,
       LAST_VALUE(amount) OVER (ORDER BY day, sale_id
         ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_amount
FROM sales
ORDER BY sale_id;
sale_iddayamountrunninglast_amount
12025-03-01101040
22025-03-02203040
32025-03-02205040
42025-03-03409040
Try it in Randori