Skip to the page

SQL for analysis · core

Latest row per key and deduplication

A status log or history table has many rows per entity. ROW_NUMBER with a tie-breaker keeps the latest one, and the same pattern removes duplicates.

The notes

What you must know

  • ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY changed_at DESC, log_id DESC) in a CTE, then keep rn = 1.
  • Add a tie-breaker (log_id). Without one, a tie picks either row, and the answer can change between runs.
  • Shortcuts: DISTINCT ON (order_id) in Postgres, QUALIFY in Snowflake, BigQuery and DuckDB.
  • RANK keeps both rows of a tie, so it does not give one row per key. ROW_NUMBER without PARTITION BY ranks the whole table.
  • The MAX plus join-back version works, but it returns two rows when the latest time ties and it reads the table twice.
  • As of a past time: filter changed_at before the cutoff before you rank, not after.
  • Duplicate statuses do not change the latest status, but they break time in each status and the number of changes. Remove them with LAG(status) and keep rows where the status differs from the previous one.
  • Stuck orders: latest status is picked_up and changed_at is older than the limit.

The red pen

Common traps: mistake → fix

  • Mistake: RANK is fine for picking the latest row

    Fix: RANK keeps both rows when times tie; use ROW_NUMBER with a tie-breaker.

  • Mistake: ROW_NUMBER without PARTITION BY gives one row per order

    Fix: it numbers the whole table once.

  • Mistake: Filter by date after ranking for a past view

    Fix: a later row may have been ranked first; filter before ranking.

Easy to hard

Questions interviewers ask, easy to hard

  1. How do you get the current status of each order from a status log?
  2. Why add a second column to ORDER BY inside ROW_NUMBER?
  3. What does QUALIFY do and which engines have it?
  4. How do you show the status of every order as it was on 1 November?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview