Make a latest-row query stable when timestamps tie

Find one latest event per account.

The interview question is to return one latest event per account. Start with two events for A at timestamp 10 and a single event for B at timestamp 4. If you find the maximum time and join it back to the source, both rows for A match. You need a rule for which of the tied rows counts as the answer.

ROW_NUMBER assigns a position inside each account’s partition. Order the partition by time descending and, when times tie, by event ID descending. Keep only row number one. The second key is an explicit convention here. An ID that was assigned out of order may be unsuitable as a business definition of recency, even when it yields a repeatable answer.

Run the query, then swap the order of the two A rows in VALUES and run it again. Both runs should return A with ID 9 and B with ID 3. Removing the ID from the ORDER BY leaves the database free to pick either A row. A single successful run without the tie-breaker therefore proves very little.

Use RANK if the question asks for every row tied at the latest timestamp. Use ROW_NUMBER with a stable final key when the result must contain one row. For a production table, make the final key unique within the account and inspect the query plan before assuming an index or a window function is the faster option.

Run the example

import sqlite3

db = sqlite3.connect(':memory:')
query = '''WITH events(account,t,id) AS (
  VALUES ('A',10,7), ('A',10,9), ('B',4,3)
), ranked AS (
  SELECT *, ROW_NUMBER() OVER (
    PARTITION BY account ORDER BY t DESC, id DESC
  ) AS rn FROM events
)
SELECT account,id FROM ranked WHERE rn=1
ORDER BY account'''
print(db.execute(query).fetchall())

Expected output

[('A', 9), ('B', 3)]

Reference: https://www.sqlite.org/windowfunctions.html

The team guide · My original notes on testing coding agents · Working with Lightbulb Partners