Function Reference

NTH_VALUE

Returns the value of column from the n-th row of the window frame.

MySQL 8.1
NTH_VALUE(column, n) OVER ([PARTITION BY ...] [ORDER BY ...] [frame])

Parameters

column
Column or expression whose value is returned
nINT
Row number in the frame, starting from 1
PARTITION BYoptional
Columns that split rows into partitions
ORDER BYoptional
Order of rows in the partition that defines which row is n-th
framekeywordoptional
Window frame: ROWS or RANGE BETWEEN start AND end; from the start of the partition to the current row by default

Return value

A value of the same type as column; NULL if the frame has fewer than n rows

Examples

Second oldest

MySQL 8.1
SELECT member_name,
	birthday,
	NTH_VALUE(member_name, 2) OVER (
		ORDER BY birthday
	) AS second_oldest
FROM FamilyMembers;
member_namebirthdaysecond_oldest
Headley Quincey1960-05-13<NULL>
Ernest Forrest1961-09-11Ernest Forrest
Flavia Quincey1963-02-16Ernest Forrest
Constance Forrest1968-09-06Ernest Forrest
Andie Quincey1983-06-05Ernest Forrest
Lela Quincey1985-06-07Ernest Forrest
Annie Quincey1988-04-10Ernest Forrest
Wednesday Addams2005-01-13Ernest Forrest

Second salary in each department

MySQL 8.1
SELECT department_id,
	name,
	salary,
	NTH_VALUE(salary, 2) OVER (
		PARTITION BY department_id
		ORDER BY salary DESC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
	) AS second_salary
FROM employees;
department_idnamesalarysecond_salary
1Dmitry Sokolov220000210000
1Anna Ivanova210000210000
1Igor Petrov195000210000
1Pavel Smirnov180000210000
1Elena Kozlova175000210000
2Irina Volkova205000200000
2Olga Novikova200000200000
2Maxim Morozov160000200000
2Nikita Popov160000200000
3Tatiana Lebedeva170000155000

Details

With the default frame, the n-th row is visible only starting from itself: the first n - 1 rows of the partition get NULL. To get the value for all rows, set the frame to the whole partition. NTH_VALUE(column, 1) is the same as FIRST_VALUE(column).

The frame sets which rows of the partition the function sees and is written after ORDER BY: ROWS BETWEEN start AND end counts rows, while RANGE BETWEEN start AND end uses the ORDER BY values.

BoundMeaning
UNBOUNDED PRECEDINGThe first row of the partition
n PRECEDINGn rows before the current one
CURRENT ROWThe current row
n FOLLOWINGn rows after the current one
UNBOUNDED FOLLOWINGThe last row of the partition

Without a frame, the default rule applies. If OVER has ORDER BY, the frame runs from the start of the partition to the current row, including rows with the same ORDER BY value. Without ORDER BY, the frame is the whole partition.

See also