Skip to content

Window functions

Rank within groups, compare a row with the previous one, and smooth with a rolling average, all without losing a row.

Applied ~9 min9 steps

What runs in CodeSplash

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

01

Keep the rows

Read

GROUP 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.

02

How many rows?

Predict

Predict 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;

5, one per month153, one per dayA different number
Reveal
  1. 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 Month would give you five rows. You can now write Temp - month_mean to see how unusual a day was.
03

Top row per group

In the app

A 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.

04

Day to day

Explore

Add the air quality sample, then look at time order. lag reads the previous row, and a frame gives a rolling window.

New York air quality, 1973
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.

05

Share of a total

Explore

Aggregates and windows can combine: sum(count(*)) OVER () is the total of the grouped counts. An empty OVER () means every row.

SELECT species,
       count(*) AS n,
       round(100.0 * count(*) / sum(count(*)) OVER (), 1) AS pct
FROM palmer_penguins_sample
GROUP BY species
ORDER BY n DESC;

The window runs after the GROUP BY, which is why it can see the counts. Run it and check the percentages add to 100.

06

Write your own top row per group

In the app

Now 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.

07

Check your understanding

Checkpoint

Check 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.

08

From rolling to real

Reflect

A 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:

09

Recap

Recap
  • A window function keeps every row and adds a computed column.
  • PARTITION BY groups, ORDER BY sorts, and QUALIFY filters on the result.
  • lag and frames give you changes and rolling averages.

Concepts in this lesson