Page with a stable keyset cursor
Continue an ordered result from the last seen key without relying on an offset that shifts when earlier rows change.
What you are trying to do
A work API sorts by priority descending and task ID ascending. The client asks for the next page after priority 2, task 202.
Work through it
- Read the complete ordering tuple: Priority descending, then TaskId ascending.
- Compare the cursor predicate with both sort directions. A lower priority follows the cursor, while an equal priority needs a greater TaskId.
- Check TOP and the final ordering together.
- Change the cursor mentally and predict how the next page changes.
Check your work
The next page contains exactly task 203 at priority 2, then task 101 and task 102 at priority 1. Task 201 and task 202 are at or before the cursor and do not appear.
Practice SQL
Open in SQL FlowDECLARE @AfterPriority int = 2;
DECLARE @AfterTaskId int = 202;
WITH WorkItem AS (
SELECT TaskId, Priority
FROM (VALUES (301, 3), (201, 2), (202, 2), (203, 2), (101, 1), (102, 1)) AS v(TaskId, Priority)
)
SELECT TOP (3) TaskId, Priority
FROM WorkItem
WHERE Priority < @AfterPriority
OR (Priority = @AfterPriority AND TaskId > @AfterTaskId)
ORDER BY Priority DESC, TaskId ASC;
Knowledge check
Commands in this lesson
Next lesson Detect a competing update with rowversion