Function Reference

FIRST_VALUE

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

PostgreSQL 17.5
FIRST_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 first
framekeywordoptional
Window frame: ROWS, RANGE or GROUPS BETWEEN start AND end; by default, with ORDER BY, from the start of the partition to the current row together with rows equal to it in ORDER BY, without ORDER BY, the whole partition

Return value

A value of the same type as column

Examples

Oldest member in each status

PostgreSQL 17.5
SELECT member_name,
	status,
	birthday,
	FIRST_VALUE(member_name) OVER (
		PARTITION BY status
		ORDER BY birthday
	) AS oldest_in_status
FROM FamilyMembers;
member_namestatusbirthdayoldest_in_status
Lela Quinceydaughter1985-06-07Lela Quincey
Annie Quinceydaughter1988-04-10Lela Quincey
Wednesday Addamsdaughter2005-01-13Lela Quincey
Headley Quinceyfather1960-05-13Headley Quincey
Ernest Forrestfather1961-09-11Headley Quincey
Flavia Quinceymother1963-02-16Flavia Quincey
Constance Forrestmother1968-09-06Flavia Quincey
Andie Quinceyson1983-06-05Andie Quincey

Difference from the first purchase

PostgreSQL 17.5
SELECT family_member,
	date,
	unit_price,
	unit_price - FIRST_VALUE(unit_price) OVER (
		PARTITION BY family_member
		ORDER BY date
	) AS diff_from_first
FROM Payments
ORDER BY family_member,
	date;
family_memberdateunit_pricediff_from_first
12005-02-0380
12005-02-1220001992
12005-03-117-1
12005-04-2080
12005-05-137-1
12005-06-05300292
12006-01-15100009992
12006-03-12102
22005-03-1880
22005-03-2321002092

Details

The default frame always starts at the first row of the partition, so without an explicit frame the function returns the first value of the partition. How to set another frame is described in ROWS BETWEEN.

See also

Where to learn