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:
| id | type |
| 132 | t1 |
| 52 | t2 |
| 92 | t1 |
| 154 | t3 |
| 198 | t1 |
SELECT id, type, ROW_NUMBER() OVER (PARTITION BY type ORDER BY id) as row_num
FROM table1This will generate a column that will number each type within itself:
| id | type | row_num |
| 132 | t1 | 1 |
| 52 | t2 | 1 |
| 92 | t1 | 2 |
| 154 | t3 | 1 |
| 198 | t1 | 3 |
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
EasyAvailable 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4More Keywords
The IN keywordThe BETWEEN keywordThe LIKE keywordThe AS keywordRecap - Cellphone Models2Conditions
Conditions BasicsThe AND keywordThe OR keywordThe NOT keywordMultiple Conditions CombinedParenthesisBooleans5Arithmetic Operations
Mathematical OperatorsMathematical ColumnsThe Modulo OperationThe ROUND() Function8Statistics
Built-In Aggregate Part 1Built-In Aggregate Part 2Grouping Part 1Grouping Part 2Subqueries Part 1Subqueries Part 2Recap - Total Gain ShopRecap - Scooter ShopRecap - Coffee Shop11Window Functions part 1
ROW_NUMBER functionORDER BY criterionPARTITION BY criterionPARTITION & ORDERLEAD & LAG FunctionsRecap - LEAD & LAGRecap - PicturesRecap - Boxes3Specific Return Format
Null valuesSort Results Part 1Sort Results Part 2Recap - Cyber Security FirmLimit number of recordsRecap - Vehicle Factory6Intro Challenges
Recap - Parliamentary ElectionRecap - Police Criminal ArrestRecap - Bar Beverage ContainerRecap - Engineer new columns