PARTITION & ORDER
Part of the Fundamentals section of Coddy's SQL journey — lesson 60 of 72.
We can also combine PARTITION BY with ORDER BY. For example consider the following table1:
| 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 number the rows in ascending order by the id of each type:
| id | type | row_num |
| 132 | t1 | 2 |
| 52 | t2 | 1 |
| 92 | t1 | 1 |
| 154 | t3 | 1 |
| 198 | t1 | 3 |
Now id 132 has row_num 2 because it is larger than 92 and smaller than 198 (of all the t1 type rows).
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>
Write a SQL query to analyze the sequence of door colors within each country, ordered by publication year. For each door space, show:
- The country
- The color
- The publication year
- A number representing the order of colors within each country based on publication year. Call this column
color_sequence_number
Cheat sheet
You can combine PARTITION BY with ORDER BY to number rows within each partition in a specific order:
SELECT id, type, ROW_NUMBER() OVER (PARTITION BY type ORDER BY id) as row_num
FROM table1This numbers rows in ascending order by id within each type group. Each partition restarts numbering from 1.
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