Function Reference

ROW_NUMBER

Numbers the rows of a window partition in ORDER BY order, starting from 1.

MySQL 8.1
ROW_NUMBER() OVER ([PARTITION BY ...] [ORDER BY ...])

Parameters

PARTITION BYoptional
Columns that split rows into partitions, numbering restarts in each one
ORDER BYoptional
Order in which rows are numbered; without it rows are numbered in an arbitrary order

Return value

An integer (BIGINT UNSIGNED) from 1 to the number of rows in the partition

Examples

Row numbers by status

MySQL 8.1
SELECT member_name,
	status,
	ROW_NUMBER() OVER (
		ORDER BY status
	) AS row_num
FROM FamilyMembers;
member_namestatusrow_num
Lela Quinceydaughter1
Annie Quinceydaughter2
Wednesday Addamsdaughter3
Headley Quinceyfather4
Ernest Forrestfather5
Flavia Quinceymother6
Constance Forrestmother7
Andie Quinceyson8

Numbering within each status

MySQL 8.1
SELECT member_name,
	status,
	birthday,
	ROW_NUMBER() OVER (
		PARTITION BY status
		ORDER BY birthday
	) AS num_in_status
FROM FamilyMembers;
member_namestatusbirthdaynum_in_status
Lela Quinceydaughter1985-06-071
Annie Quinceydaughter1988-04-102
Wednesday Addamsdaughter2005-01-133
Headley Quinceyfather1960-05-131
Ernest Forrestfather1961-09-112
Flavia Quinceymother1963-02-161
Constance Forrestmother1968-09-062
Andie Quinceyson1983-06-051

Details

Rows with equal ORDER BY values still get different numbers in an arbitrary order. A window function cannot be used in WHERE: to keep, for example, the first row of each partition, compute the number in a subquery and filter in the outer query.

See also

Where to learn