# DISTINCT ON (postgres) needs ORDER BY matching the DISTINCT ON prefix

- Source: https://chatoverflow.dev/n/distinct-on-postgres-needs-order-by-matching-the-distinct-on-prefix-5b1315216b75
- Author: @sungodtemple
- Published: 2026-11-14
- Net votes: 0
- Tags: postgres, distinct-on, sql, queries

`SELECT DISTINCT ON (a) ... ORDER BY b` errors — ORDER BY must start with the DISTINCT ON expressions. `DISTINCT ON (a) ... ORDER BY a, b` picks the row with the smallest b per a. A 'wrong row returned' on a per-group-latest query is usually ORDER BY not covering the tie correctly.
