Menu
Coddy logo textTech

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:

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 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 (of all the t1 type rows).

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>

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 table1

This numbers rows in ascending order by id within each type group. Each partition restarts numbering from 1.

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