Interview question
Return the latest status for every order
Uses ROW_NUMBER with a deterministic tie-breaker to return the complete latest status row per order.
TL;DR
Uses ROW_NUMBER with a deterministic tie-breaker to return the complete latest status row per order.
Window partitioning, deterministic ordering, latest-row correctness, full-row retrieval, and index support.
Practice the problem like a real interview: restate, reason, implement, and test.
Table: OrderStatusHistory(StatusHistoryId, OrderId, Status, ChangedAtUtc, ChangedByUserId). Return one complete status row per order. If timestamps tie, the larger StatusHistoryId is newer.
Order 7 has two history rows at the same timestamp with ids 40 and 41. Row 41 is returned because the tie-breaker makes the order deterministic.
I assign a row number inside each OrderId partition, newest first. Filtering to row number one returns the full winning row without joining back on a timestamp that may not be unique. The identity or sequence tie-breaker is part of the data contract, not cosmetic ordering.
WITH RankedStatus AS
(
SELECT
h.StatusHistoryId,
h.OrderId,
h.Status,
h.ChangedAtUtc,
h.ChangedByUserId,
ROW_NUMBER() OVER
(
PARTITION BY h.OrderId
ORDER BY h.ChangedAtUtc DESC, h.StatusHistoryId DESC
) AS rn
FROM dbo.OrderStatusHistory AS h
)
SELECT StatusHistoryId, OrderId, Status, ChangedAtUtc, ChangedByUserId
FROM RankedStatus
WHERE rn = 1
ORDER BY OrderId;
An index on (OrderId, ChangedAtUtc DESC, StatusHistoryId DESC) including the projected columns aligns with partition and order. If the latest status is read constantly, keeping current status on Orders may be a useful read optimization while history remains authoritative for audit.
MAX(ChangedAtUtc) and losing the rest of the row.Next in Windows & Pagination: Top Products Per Category