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;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;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.