DISTINCT ON (col1, col2) keeps the FIRST row per (col1, col2) tuple after the ORDER BY. It’s a Postgres superpower for “give me one row per X, picked by some order”. Avoids correlated subqueries and window tricks.
SELECT DISTINCT ON (customer_id) customer_id, total, ts FROM orders ORDER BY customer_id, ts DESC -> latest order per customer.
Picking the highest-scored embedding per user: order by user_id, score desc.
rows -> sort -> DISTINCT ON keeps first per tuple
(order by determines "first")
DISTINCT ON is the cleanest Postgres idiom for “latest per group”. One CTE, sorted, done.