One Row Per User

orders:

id user_id ordered_at total
1 7 2026-01-03 40
2 7 2026-01-09 120
3 8 2026-01-05 55
4 8 2026-02-01 55
SELECT DISTINCT ON (user_id) user_id, id, total
FROM orders
ORDER BY user_id, total DESC, id;

What comes back?

A

All four rows, since DISTINCT ON only deduplicates identical rows

B

7, 2, 120 and 8, 3, 55

C

7, 1, 40 and 8, 3, 55

D

7, 2, 120 and 8, 4, 55