Deduplication & latest-record
Concept  ·  SQL & Querying

ROW_NUMBER() ORDER BY updated_at DESC with tied timestamps picks a row arbitrarily — the ORDER BY must reach a unique key.

With a tie on the ORDER BY key, the row_number of 1 is any one of the tied rows, chosen by scan order, which varies per execution. Nothing needs to write for the answer to change.

See it break
subs
sub_idcust_idplanupdated_at
17pro2024-05-01 10:00:00
27free2024-05-01 10:00:00
The trap
SELECT
  cust_id,
  plan
FROM
  (
    SELECT
      cust_id,
      plan,
      ROW_NUMBER() OVER (
        PARTITION BY
          cust_id
        ORDER BY
          updated_at DESC) rn
    FROM
      subs
  ) t
WHERE
  rn = 1;
The fix
SELECT
  cust_id,
  plan
FROM
  (
    SELECT
      cust_id,
      plan,
      ROW_NUMBER() OVER (
        PARTITION BY
          cust_id
        ORDER BY
          updated_at DESC,
          sub_id DESC
      ) rn
    FROM
      subs
  ) t
WHERE
  rn = 1;

The customer's plan flickers between refreshes of the same table — the bug that can't be reproduced because both answers are consistent with the query.

The rule

Extend the ORDER BY to a unique key, and decide which row should win as a business rule, not a technical accident.

ORDER BY updated_at DESC, <unique_key> DESC
Shows up elsewhere
MAX-timestamp-then-join anti-pattern
Try one →Prove it in practice →