Interview question
Page orders with a stable keyset cursor
Implements descending keyset pagination with a compound cursor and stable ordering.
TL;DR
Implements descending keyset pagination with a compound cursor and stable ordering.
Keyset pagination, compound comparisons, descending order, first-page behavior, and index alignment.
Practice the problem like a real interview: restate, reason, implement, and test.
Table: Orders(OrderId, CustomerId, CreatedAtUtc, Status). Return @PageSize non-deleted orders ordered newest first. For the first page both cursor parameters are null. Later pages receive the last row's CreatedAtUtc and OrderId.
If the previous page ends at (2026-07-18 10:00, OrderId 42), the next page includes rows with an earlier timestamp, plus rows at 10:00 whose id is lower than 42.
CreatedAtUtc DESC, OrderId DESC.@PageSize rows.For descending order, rows after the cursor have an earlier timestamp, or the same timestamp and a smaller id. I keep both cursor values together because the timestamp alone is not unique. The matching composite index lets the database continue from the cursor instead of reading and discarding a large offset.
SELECT TOP (@PageSize)
o.OrderId,
o.CustomerId,
o.CreatedAtUtc,
o.Status
FROM dbo.Orders AS o
WHERE o.Status <> 'Deleted'
AND
(
@AfterCreatedAtUtc IS NULL
OR o.CreatedAtUtc < @AfterCreatedAtUtc
OR
(
o.CreatedAtUtc = @AfterCreatedAtUtc
AND o.OrderId < @AfterOrderId
)
)
ORDER BY o.CreatedAtUtc DESC, o.OrderId DESC;
An index on (CreatedAtUtc DESC, OrderId DESC) including the projected columns supports the ordered range. A filtered index may help if deleted rows are common and the database can match the filter. The null first-page branch may lead to plan variation, so production workloads should inspect actual plans.
OFFSET and calling it keyset pagination.Move to the linked follow-up, next path step, prerequisite, or deeper variant.
Practice the next layer of the same subject.