SQL ROW_NUMBER Function

Quick summary: The SQL ROW_NUMBER() function assigns a unique sequential number to rows within a partition.

SQL ROW_NUMBER Syntax

ROW_NUMBER() OVER ( [PARTITION BY column] ORDER BY column )
SQL

SQL ROW_NUMBER Basic examples

SELECT id, ROW_NUMBER() OVER (ORDER BY created_at) FROM users;
SQL
Output:
Sequential row numbers

Numbers rows in result order.

SQL ROW_NUMBER Real-world usage

SELECT * FROM (
  SELECT user_id, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) rn
  FROM orders
) t WHERE rn = 1;
SQL
Output:
Latest order per user

Selects the newest row per group.

SQL ROW_NUMBER Edge cases

SELECT ROW_NUMBER() OVER () FROM users;
SQL
Output:
Non-deterministic order

Ordering is undefined without ORDER BY.

SQL ROW_NUMBER Common mistakes

Using ROW_NUMBER without ORDER BY

Results may be unpredictable.

Incorrect
ROW_NUMBER() OVER ()
Correct
ROW_NUMBER() OVER (ORDER BY id)

Always specify ordering.

SQL ROW_NUMBER Frequently Asked Questions

What does ROW_NUMBER() do in SQL?

Assigns a unique sequential number to each row.

Use case of ROW_NUMBER()?

Pagination and ranking.

Syntax?

ROW_NUMBER() OVER (ORDER BY column).

Requires ORDER BY?

Yes.

Handles duplicates?

Always unique numbers.

Common mistake?

Missing ORDER BY.

Used with PARTITION BY?

Yes.

Performance?

Depends on dataset size.

Return type?

Integer.

Used in analytics?

Yes.

Alternative?

LIMIT/OFFSET.

Best practice?

Use with proper ordering.

SQL ROW_NUMBER Related SQL Keywords