Español Practice SQL

SQL ROW_NUMBER and RANK: number and rank rows

A window function adds a value to every row without collapsing the rows.

SQL skills · Window functions

Practice this nowLearn it step by step

Free. No sign up. Your progress stays in this browser.

What you will learn

ROW_NUMBER numbers the rows in an order you choose. PARTITION BY restarts the numbering for each group.

Combined with a CTE, it gives the top row per group, one of the most common interview questions.

The basics

A window function adds a value to every row, computed across a set of rows, without collapsing them the way GROUP BY does.

SELECT customer, amount,
  ROW_NUMBER() OVER (ORDER BY amount DESC) AS rn
FROM invoices

Per group

WITH ranked AS (
  SELECT region, customer, amount,
    ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC) AS rn
  FROM invoices
)
SELECT region, customer, amount FROM ranked WHERE rn = 1

PARTITION BY restarts the numbering for each group. WHERE cannot use a window function directly, so the filter goes in an outer query.

Ties

ROW_NUMBER gives every row its own number. RANK gives ties the same number and skips the next ones (1, 1, 3). DENSE_RANK does not skip (1, 1, 2).

Worked examples

Example 1

The largest invoice per region.

WITH ranked AS (
  SELECT region, customer, amount,
    ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC) AS rn
  FROM invoices
)
SELECT region, customer, amount
FROM ranked
WHERE rn = 1

The filter goes outside the CTE.

Reading helps, typing makes it stick. Every task gives you a fresh table, and your query is checked by a real database.

Try a task

Common mistakes

  • Filtering a window function in WHERE of the same query.
  • Using ROW_NUMBER when ties should share a rank.
  • Forgetting ORDER BY inside OVER.

Where you will use it at work

  • Sales: the biggest deal per rep.
  • Product: each user’s first payment.
  • HR: the most recent hire per department.

Questions people ask

RANK or DENSE_RANK?

RANK leaves gaps after ties (1, 1, 3), DENSE_RANK does not (1, 1, 2).

Is there a shortcut for rn = 1?

Snowflake and some others have QUALIFY.

Does ORDER BY in OVER sort the result?

No. Add a normal ORDER BY at the end to sort the output.

Ready to write it yourself?

Practice ROW_NUMBER and RANK

Further reading

Related guides