SQLQuestion 07 of 14
Most recently used product — MAX or the whole row?
Answer out loud or in your head first, then compare.
Answer
MAX(used_at) gives the date, but not the product's identifier. If one record is expected, I pick it by sorting with a tie-breaker.
SQL
-- product_usage(id PRIMARY KEY, product_id, used_at)
SELECT product_id, used_at
FROM product_usage
WHERE used_at IS NOT NULL
ORDER BY used_at DESC, id DESC
LIMIT 1;To be precise: when all records with the latest date should be returned, I compare used_at with a MAX(used_at) subquery.
Pitfall: without a second sort key, the choice among ties can be non-deterministic. MAX(id) doesn't have to mean the latest business event.
How did it go? Be honest — “Not yet” puts the question on your review list.