DELAPARRA
Index
Color
NL
Category: SQL

ROW_NUMBER

Explained by Updated

What is ROW_NUMBER?

ROW_NUMBER: Assigns a unique sequential number per row within each partition, in the ORDER BY order. ROW_NUMBER() gives each row a unique sequential number, following the order you specify in OVER (ORDER BY ...). With PARTITION BY, numbering restarts for each group. Its most common use is picking the top rows per group. Number each customer's orders from newest to oldest, then keep rows numbered 1 to get every customer's latest order in one query.

Definition source Coders Lingo, CC BY 4.0

Frequently asked questions about ROW_NUMBER

What should you keep in mind with ROW_NUMBER?

Unlike RANK(), it never gives two rows the same number, even when they tie in the ordering. Add a tie-breaker column, such as the ID, to the ORDER BY so the result is stable between runs. It is also useful for removing duplicates: number the duplicates within each group and delete every row with a number greater than one.

What does an example of ROW_NUMBER look like?

SELECT name, dept, ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) AS rn FROM employees;

At a glance

CategorySQL
Explained by
Updated

More SQL terms

All terms starting with R

Skills

Download all skills (zip)

Manuals

Related services

Need any help?

Stuck on one of these in your own project? Tell me what you are working on and I will tell you how I would approach it.