Start learning free

LESSON 7 OF 66 · SQL: BEYOND THE BASICS

Number the Rows: ROW_NUMBER in Python

Practice

With GROUP BY, many rows collapse into one row per group. A window function works the other way: it adds one more column to every row and keeps all the rows. The simplest one is ROW_NUMBER(), which numbers the rows 1, 2, 3…

After it comes OVER (…), the window. An ORDER BY inside its brackets says in which order to count. This query numbers the products in alphabetical order:

query = (
    "SELECT name, "
        "ROW_NUMBER() OVER (ORDER BY name) AS n "
    "FROM products "
)

Gift card gets 1, Lamp 2, Mug 3, and so on up to Teapot, 8. As in any ORDER BY, add DESC to count from the largest value down.

This lesson's query numbers the shop's products from the dearest to the cheapest. It must print:

name | price | row_num
Gift card | 50 | 1
Lamp | 29 | 2
Teapot | 22 | 3
Plant | 15 | 4
Mug | 12 | 5
Stapler | 9 | 6
Notebook | 7 | 7
Pen | 2 | 8
(8 rows)

Your task: db is already connected to shop.db. In query, select each product's name and price, plus a column row_num made with ROW_NUMBER() OVER (ORDER BY price DESC).


Assignment
Follow the Coding Tutorial to build query one clause per line: the two columns, the numbered column row_num, then FROM products.


Hint
End the SELECT line with a comma, since another column comes below it. The ORDER BY for the numbering goes inside the brackets after OVER, not at the end of the query.


STEP 1 OF 3
    Ctrl + Enter to check

    Sqlx Row Number in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free