Menu
Coddy logo textTech

PARTITION BY criterion

Lesson 5 of 13 in Coddy's SQL for advanced course.

Another option for the OVER () options are the PARTITION BY

It allows us to number the rows for each group separately 

For example:

idtype
132t1
52t2
92t1
154t3
198t1
SELECT id, type, ROW_NUMBER() OVER (PARTITION BY type) as row_num
FROM table1

This will generate a column that will number each type within itself:

idtyperow_num
132t11
52t21
92t12
154t31
198t13

id 92 has row_num 2 because it is the second row of type t1

We can also combine PARTITION BY with ORDER BY:

SELECT id, type, ROW_NUMBER() OVER (PARTITION BY type ORDER BY id) as row_num
FROM table1

This will number the rows in ascending order by the id of each type:

idtyperow_num
132t12
52t21
92t11
154t31
198t13

Now id 132 has row_num 2 because it is larger than 92 and smaller than 198.

We can even specify multiple columns inside the PARTITION BY:

ROW_NUMBER() OVER (PARTITION BY type, hue)
challenge icon

Challenge

Easy

A factory is building doors. It needs to number the doors for each country and color that their publication_year is before 2000. name this column row_num.

Doors without specs should be ignored. sort the result in ascending order by the id

Try it yourself

All lessons in SQL for advanced