BeginnerCoder

Lesson 17 — Row numbering

ROW_NUMBER: number rows within groups

A window function computes a value for each row while looking at other rows, without collapsing them like GROUP BY. ROW_NUMBER() OVER (PARTITION BY x ORDER BY y) numbers rows 1, 2, 3… inside each group x, in order y. PARTITION BY is the "per group" part.

ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC)

Why it matters: "the top earner per department" or "each customer's first order" become a simple filter on rn = 1.

Want it another way?
Task

Add PARTITION BY dept so numbering restarts in each department. Expected: Ann 1, Bo 2 in IT; Dee 1, Cy 2, Ed 3 in Sales.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with SQL Deep Dive

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.