Window Frames

Learn how to calculate aggregate expression over a sliding window.

Overview

The PARTITION clause in an aggregate expression can calculate the difference between the temperature on each day and the hottest day ever in the same city:

Press + to interact
SELECT
*,
temperature - MAX(temperature) OVER (PARTITION BY city) AS diff_from_hottest
FROM
temperatures;

What if, instead of comparing each day with the hottest day of all time, we want to compare each day with the hottest day in the same city to date?

Order of rows in a partition

To compare each temperature to the maximum temperature in the same city before that date, we need to add another element to our group. So far, we used the PARTITION clause to tell the databases how to group the data. Now, we want to provide order as well:

Press + to interact
SELECT
*,
MAX(temperature) OVER (
PARTITION BY city ORDER BY day
) AS hottest_day_so_far
FROM
temperatures
ORDER BY
city,
day;

To introduce order to the aggregate expression, we added the ORDER BY clause in addition to the PARTITION. The aggregate expression will now calculate the aggregate in that order. In our case, we sorted the results by day, so at every row, the aggregate will calculate the maximum temperature within the group, until that day.

If we execute the query and ...