Window functions
Rank within groups, compare a row with the previous one, and smooth with a rolling average, all without losing a row.
What runs in CodeSplash
- Baseline forecast Verified in Python and R
- Seasonal decomposition Verified in Python and R
You will be able to
- Say how a window function differs from GROUP BY
- Rank within groups and keep the top row per group
- Compute changes and rolling averages with LAG and a frame
Read first
Keep the rows
ReadGROUP BY collapses rows. A window functionWindow functionComputes across a set of related rows while keeping every row, whereas GROUP BY collapses them. computes across related rows and keeps every one. Each penguin stays, and gains a column showing its rank within its species.
SELECT species, body_mass,
row_number() OVER (
PARTITION BY species
ORDER BY body_mass DESC NULLS LAST
) AS rank_in_species
FROM palmer_penguins_sample
ORDER BY species, rank_in_species
LIMIT 5;
PARTITION BY splits the rows into groups, ORDER BY sorts within each group, and OVER makes it a window.
How many rows?
PredictPredict first
The air quality table has 153 days over five months. How many rows does this return?
SELECT Month, Temp, avg(Temp) OVER (PARTITION BY Month) AS month_mean FROM new_york_air_quality_1973_sample;
Reveal
- A window function adds a column and leaves the row count alone, so each day now sits beside its month's mean. The same average with
GROUP BY Monthwould give you five rows. You can now writeTemp - month_meanto see how unusual a day was.
Top row per group
In the appA top row per group is what people use window functions for most. DuckDB's QUALIFY filters on a window result.
SELECT species, sex, body_mass,
row_number() OVER (
PARTITION BY species
ORDER BY body_mass DESC NULLS LAST
) AS rn
FROM palmer_penguins_sample
QUALIFY rn = 1
ORDER BY species;
Run it: one heaviest bird per species. Ties get an arbitrary winner with row_number. rank() gives tied rows the same rank, so swap it in if you want to keep them.
Day to day
ExploreAdd the air quality sample, then look at time order. lag reads the previous row, and a frame gives a rolling window.
SELECT Day, Temp,
Temp - lag(Temp) OVER (ORDER BY Day) AS change,
round(avg(Temp) OVER (
ORDER BY Day ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
), 2) AS rolling_3
FROM new_york_air_quality_1973_sample
WHERE Month = 5
ORDER BY Day
LIMIT 5;
The first day's change is NULL, since it has no previous row. Change 2 PRECEDING to 6 PRECEDING for a weekly window, and see how much smoother it gets.
Write your own top row per group
In the appNow write one from a task. It opens in a new SQL tab, and Check compares your result with the answer's.
SQL exercise · penguins
Rank within a group
Find the heaviest penguin of each species. Show species and body mass, using a window function. Break ties by keeping one row.
Hints
- row_number() OVER (PARTITION BY species ORDER BY body_mass DESC) numbers each species from its heaviest.
- A window function can't go in WHERE, so filter on it in an outer query. In DuckDB, QUALIFY also works.
Show a solution
SELECT species, body_mass
FROM (
SELECT species, body_mass,
row_number() OVER (PARTITION BY species ORDER BY body_mass DESC) AS r
FROM {{table}}
WHERE body_mass IS NOT NULL
)
WHERE r = 1;In the app this opens in a real SQL tab on the sample table and checks your result.
Check your understanding
CheckpointCheck yourself
Using the QUALIFY query, what does the heaviest Adelie weigh, in grams?
Show the answer
Answer: 4775
4,775 grams. QUALIFY keeps the rows whose window value passes the test, the way HAVING does for groups.
Check yourself
From the lag query, by how many degrees did the temperature change from May 1 to May 2?
Show the answer
Answer: 5
From 67 to 72, a change of 5. lag gives you the previous row in the window's order.
Check yourself
You need each customer's order alongside that customer's total spend. Which fits?
Show the answer
Answer: b
You want to keep the order rows and add a group value, which is what a window does.
From rolling to real
ReflectA rolling average is a simple way to see a trend, but it can't separate trend from season, and it lags behind real changes. When would you want more than that? The Time Series track starts here:
Recap
Recap- A window function keeps every row and adds a computed column.
PARTITION BYgroups,ORDER BYsorts, andQUALIFYfilters on the result.lagand frames give you changes and rolling averages.
Concepts in this lesson