TopicsCheat sheetLessons
Lurndo › Topics › Window functions and ROW_NUMBER

Learn SQL: Window functions and ROW_NUMBER

A number for every row

"On the podium I want the youngest riders in the spotlight," says Griet. For that you need to number them, from young to old. `GROUP BY` can't do it: the riders would disappear into a little group.

A window over the rows

A window function calculates something over a set of rows, the window, but leaves every row standing. That is the big difference from GROUP BY.

ROW_NUMBER() gives every row a sequence number. After OVER you say in brackets in which order to number: here from old to young.

SELECT name, birth_date, ROW_NUMBER() OVER (ORDER BY birth_date) AS num FROM riders
Result
namebirth_datenum
Kasper Holm1996-04-211
Jesper Kuipers1997-01-192
Jens Moreels1997-11-233
Louis Garnier1998-07-154
Senne Pauwels1998-12-055
Lars Vermeulen1999-03-146
Thijs Bakker1999-08-287
Arne Van Hecke2000-05-098

The total next to every row

SUM, COUNT and AVG can be window functions too. With an empty OVER () the window is the whole table: every row gets the total next to it, and not a single row disappears.

That lets you compare each row with the whole, something GROUP BY can't do.

SELECT finish, km, SUM(km) OVER () AS total FROM stages
Result
finishkmtotal
Lennik164701
Lennik18701
Galmaarden178701
Pepingen185701
Halle156701

Filtering on the number

WHERE runs before the window functions: at that moment the number doesn't exist yet. That is why a window function is not allowed in WHERE.

The way out: number first in a WITH or a subquery, then filter on the column. That's how you find the three youngest riders.

WITH numbered AS (
SELECT name, birth_date, ROW_NUMBER() OVER (ORDER BY birth_date DESC) AS num
FROM riders
)
SELECT name, num FROM numbered WHERE num <= 3
Result
namenum
Ruben de Graaf1
Ben Schmit2
Milan Dhondt3

Try it yourself

Show the finish town and the distance of every stage, with a sequence number from the longest (1) to the shortest.

Ready for more?

The full lesson has 6 exercises, from easy to challenging, with hints, points and a streak you can build.

Start the lesson
← PreviousAll or nothingNext →Same time
SQL topicsCheat sheetExcelLeaderboardAccountPrivacyNederlands