Function Reference

LAST_VALUE

Returns the value of column from the last row of the window frame.

MySQL 8.1
LAST_VALUE(column) OVER ([PARTITION BY ...] [ORDER BY ...] [frame])

Parameters

column
Column or expression whose value is returned
PARTITION BYoptional
Columns that split rows into partitions
ORDER BYoptional
Order of rows in the partition that defines which row is last; without it the frame is the whole partition and the last row is arbitrary
framekeywordoptional
Window frame: ROWS or RANGE BETWEEN start AND end; from the start of the partition to the current row by default, the whole partition is ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING

Return value

A value of the same type as column

Examples

Youngest member in each status

MySQL 8.1
SELECT member_name,
	status,
	birthday,
	LAST_VALUE(member_name) OVER (
		PARTITION BY status
		ORDER BY birthday ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
	) AS youngest_in_status
FROM FamilyMembers;
member_namestatusbirthdayyoungest_in_status
Lela Quinceydaughter1985-06-07Wednesday Addams
Annie Quinceydaughter1988-04-10Wednesday Addams
Wednesday Addamsdaughter2005-01-13Wednesday Addams
Headley Quinceyfather1960-05-13Ernest Forrest
Ernest Forrestfather1961-09-11Ernest Forrest
Flavia Quinceymother1963-02-16Constance Forrest
Constance Forrestmother1968-09-06Constance Forrest
Andie Quinceyson1983-06-05Andie Quincey

Default frame ends at the current row

MySQL 8.1
SELECT member_name,
	status,
	birthday,
	LAST_VALUE(member_name) OVER (
		PARTITION BY status
		ORDER BY birthday
	) AS last_in_frame
FROM FamilyMembers;
member_namestatusbirthdaylast_in_frame
Lela Quinceydaughter1985-06-07Lela Quincey
Annie Quinceydaughter1988-04-10Annie Quincey
Wednesday Addamsdaughter2005-01-13Wednesday Addams
Headley Quinceyfather1960-05-13Headley Quincey
Ernest Forrestfather1961-09-11Ernest Forrest
Flavia Quinceymother1963-02-16Flavia Quincey
Constance Forrestmother1968-09-06Constance Forrest
Andie Quinceyson1983-06-05Andie Quincey

Details

The default frame ends at the current row (and rows with the same ORDER BY value), not at the end of the partition, so without a custom frame the function often returns the value of the current row.

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

Where to learn