Menu
Coddy logo textTech

PARTITION BY criterion

Part of the Fundamentals section of Coddy's SQL journey — lesson 59 of 72.

Another option for the OVER () clause is 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 ORDER BY id) 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 when ordered by id.

Note: ROW_NUMBER() requires an ORDER BY clause within the OVER() to determine how rows should be numbered within each partition.

We can even specify multiple columns inside the PARTITION BY:

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

Challenge

Easy

Available tables and columns:

  • <strong>doors</strong>: <strong>id</strong>, <strong>publication_year</strong>
  • <strong>doors_specs</strong>: <strong>id</strong>, <strong>country</strong>, <strong>color</strong>

A factory is building doors. It needs to number the doors for each country and color combination that have a publication_year smaller than 2000. Name this column row_num.

The doors should be numbered within each group in ascending order by their id. Doors without specs should be ignored. Sort the final result in ascending order by the id

Cheat sheet

Use PARTITION BY in the OVER()</clause to number rows within groups:</p> <pre><code class="language-sql">SELECT id, type, ROW_NUMBER() OVER (PARTITION BY type) as row_num FROM table1

You can partition by multiple columns:

ROW_NUMBER() OVER (PARTITION BY type, hue)

Try it yourself

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals