Function Reference

PERCENT_RANK

Returns the relative rank of a row in a window partition, that is, the share of rows that come before it.

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

Parameters

PARTITION BYoptional
Columns that split rows into partitions, the share is computed in each one separately
ORDER BYoptional
Order of rows that defines the place; without it all rows get 0

Return value

A floating-point number (DOUBLE) from 0 to 1

Examples

Share by birth date

MySQL 8.1
SELECT member_name,
	birthday,
	RANK() OVER (
		ORDER BY birthday
	) AS birthday_rank,
	PERCENT_RANK() OVER (
		ORDER BY birthday
	) AS birthday_percent_rank
FROM FamilyMembers;
member_namebirthdaybirthday_rankbirthday_percent_rank
Headley Quincey1960-05-1310
Ernest Forrest1961-09-1120.14285714285714285
Flavia Quincey1963-02-1630.2857142857142857
Constance Forrest1968-09-0640.42857142857142855
Andie Quincey1983-06-0550.5714285714285714
Lela Quincey1985-06-0760.7142857142857143
Annie Quincey1988-04-1070.8571428571428571
Wednesday Addams2005-01-1381

Salary position in a department

MySQL 8.1
SELECT department_id,
	name,
	salary,
	ROUND(
		PERCENT_RANK() OVER (
			PARTITION BY department_id
			ORDER BY salary
		),
		2
	) AS salary_percent_rank
FROM employees;
department_idnamesalarysalary_percent_rank
1Elena Kozlova1750000
1Pavel Smirnov1800000.25
1Igor Petrov1950000.5
1Anna Ivanova2100000.75
1Dmitry Sokolov2200001
2Maxim Morozov1600000
2Nikita Popov1600000
2Olga Novikova2000000.67
2Irina Volkova2050001
3Andrey Kozlov1400000

Details

The value is calculated as (RANK() - 1) / (number of rows in the partition - 1): the first row gets 0, the last one gets 1. Rows with equal ORDER BY values get the same share, like the same place in RANK. In a partition of one row the result is 0.

See also