Deduplication & latest-record
Concept  ·  SQL & Querying

Joining back on MAX(updated_at) re-introduces ties and a second scan — a window is usually cheaper and safer.

'Latest per customer' contains a per-entity quantifier the uncorrelated subquery doesn't have — its MAX is computed once, over everything, and only rows tied with the global champion survive. The report doesn't error; it shrinks to the most-recently-active entities, which on a fresh table can even look right. The ROW_NUMBER form also forces the tiebreaker question the MAX form quietly dodges.

See it break
fittings
custts
75
73
92
The trap
SELECT
  cust,
  ts
FROM
  fittings WHERE
  ts = (
    SELECT
      MAX(ts)
    FROM
      fittings )
ORDER BY
  cust;
The fix
SELECT
  cust,
  ts
FROM
  fittings f
WHERE
  ts = (
    SELECT
      MAX(ts)
    FROM
      fittings f2
    WHERE
      f2.cust = f.cust
  )
ORDER BY
  cust;
The trap
75
The fix
75
92

The last-fitting report dropped customer 9 — an uncorrelated MAX(ts) subquery finds the table's single latest row, not each customer's latest, so only the globally-latest entity survived the filter.

The rule

Correlated MAX (WHERE f2.cust = f.cust), or ROW_NUMBER = 1 with a complete ORDER BY; never the bare global MAX for per-entity latest.

Shows up elsewhere
'Latest' without a tiebreakerTop-N per group
Try one →Prove it in practice →