← Back to SQL, page 24

sql-0477 · Hard senior

Given an order status history table, return each order's status as it was at the end of 5 March 2026.

Keep only history rows with changed_at up to the cut-off, then pick the latest of those per order with ROW_NUMBER() ordered by changed_at descending. Orders created after the cut-off have no qualifying row and are absent, or appear with NULL through a LEFT JOIN from the orders table.

Full answer
sql
CREATE TABLE status_history (order_id INTEGER, status TEXT, changed_at TEXT);
INSERT INTO status_history VALUES
 (1, 'placed', '2026-03-01 09:00'), (1, 'paid', '2026-03-01 09:05'), (1, 'shipped', '2026-03-06 10:00'),
 (2, 'placed', '2026-03-04 12:00'), (2, 'cancelled', '2026-03-05 18:30'),
 (3, 'placed', '2026-03-07 08:00');
sql
SELECT order_id, status, changed_at FROM (
  SELECT h.*, ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY changed_at DESC) AS rn
  FROM status_history h WHERE changed_at < '2026-03-06'
) WHERE rn = 1 ORDER BY order_id;
order_idstatuschanged_at
1paid2026-03-01 09:05
2cancelled2026-03-05 18:30

Order 1 was 'paid' at the cut-off; its shipment happened on the 6th, after it. Order 2 had been cancelled on the evening of the 5th. Order 3 did not exist yet, so it is missing. The filter uses < '2026-03-06' rather than <= '2026-03-05' so changes at any time on the 5th are included. This 'as of' pattern is the basis of audit questions and of type 2 dimension lookups; an index on (order_id, changed_at) serves it well.

sql
CREATE TABLE status_history (order_id INTEGER, status TEXT, changed_at TEXT);
INSERT INTO status_history VALUES
 (1, 'placed', '2026-03-01 09:00'), (1, 'paid', '2026-03-01 09:05'), (1, 'shipped', '2026-03-06 10:00'),
 (2, 'placed', '2026-03-04 12:00'), (2, 'cancelled', '2026-03-05 18:30'),
 (3, 'placed', '2026-03-07 08:00');

SELECT order_id, status, changed_at FROM (
  SELECT h.*, ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY changed_at DESC) AS rn
  FROM status_history h WHERE changed_at < '2026-03-06'
) WHERE rn = 1 ORDER BY order_id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Filter history to the cut-off first
  • Pick the latest row per key
  • Use a half-open bound for the day
  • Entities created later are absent

Common mistakes

  • Picking the latest row overall and then filtering by date
  • Using <= with a date-only bound on timestamps

Follow-ups

  • How would you show how long each order stayed in each status?
  • How would you list orders whose status changed on a given day?

Tips

  • Filter before ranking