SQL-Engineering-Handbook

ROW_NUMBER()

ROW_NUMBER sequential numbering diagram

Overview

ROW_NUMBER() assigns a unique, sequential integer to every row within its window, starting at 1. Ties in the ORDER BY are broken arbitrarily — no two rows ever receive the same number.

Ordered values: [10, 20, 20, 40]
ROW_NUMBER():   [1,  2,  3,  4]

Learning Objectives

Prerequisites

Syntax

SELECT
    column_a,
    column_b,
    ROW_NUMBER() OVER (ORDER BY sort_column) AS row_seq
FROM table_name;

Dataset Used

employes (emp_id, emp_name, dept_id, manager_id)

Examples

See 01_row_number.sql for five fully worked, production-commented examples.

Real World Applications

Business Use Cases

Domain Scenario
HR Assign a unique seniority sequence to employees
E-commerce Number a customer’s orders chronologically
Banking Sequence transactions for a statement

Common Mistakes

Best Practices

Engineering Notes

ROW_NUMBER() is computed by MySQL’s window function engine in a single pass after the base result set is materialized. It is O(n log n) due to the required sort on ORDER BY. For very large tables, ensure the ORDER BY column is indexed to avoid an expensive filesort.

Practice Questions

  1. Assign a row number to every employee ordered by emp_id.
  2. Assign a row number ordered by emp_name instead.
  3. Return only the employee name and its row number.
  4. Return only the first 3 employees using ROW_NUMBER().
  5. Return the employee whose ROW_NUMBER() = 1 (requires a CTE or subquery).

Difficulty

Beginner

Estimated Time

20–25 minutes

Learning Outcomes

Next Topic

02_RANK


Lesson Navigation

← Previous: Module READMEModule README → Next: 02_RANK