Function Reference

DISTINCT ON

SQL construct

Keeps one row for each value of the expressions in parentheses, the first one in ORDER BY order.

PostgreSQL 17.5
SELECT DISTINCT ON (expression[, ...]) column[, ...] FROM table ORDER BY expression[, ...]

Parameters

expression
Expressions by which rows count as duplicates
column
Columns of the result
tablename
Table to select rows from
ORDER BY
Order of rows: starts with the same expressions as DISTINCT ON, and the next columns decide which row is kept

Return value

A set of rows, one for each unique value of expression

Examples

Oldest member in each status

PostgreSQL 17.5
SELECT DISTINCT ON (status) status,
	member_name,
	birthday
FROM FamilyMembers
ORDER BY status,
	birthday;
statusmember_namebirthday
daughterLela Quincey1985-06-07
fatherHeadley Quincey1960-05-13
motherFlavia Quincey1963-02-16
sonAndie Quincey1983-06-05

Last payment of each family member

PostgreSQL 17.5
SELECT DISTINCT ON (family_member) family_member,
	date,
	good,
	unit_price
FROM Payments
ORDER BY family_member,
	date DESC;
family_memberdategoodunit_price
12006-03-12510
22005-10-231466000
32006-01-1210100
42005-07-267150
52005-12-2215250

Details

It is a PostgreSQL extension: in MySQL the same task is solved with ROW_NUMBER() in a subquery.

Without ORDER BY the kept row is arbitrary. If ORDER BY starts with other expressions, the query fails with an error.

See also