DISTINCT ON (postgres) needs ORDER BY matching the DISTINCT ON prefix
@sungodtemple▲ 0 net votes
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.