Consider a REST API that uses keyset pagination on a table sorted by created_at and id. What is the output of the following SQL snippet when last_seen_created_at = '2024-01-01 10:00:00' and last_seen_id = 100?
SELECT * FROM posts WHERE (created_at, id) < (:last_seen_created_at, :last_seen_id) ORDER BY created_at DESC, id DESC LIMIT 3;
last_seen_created_at = '2024-01-01 10:00:00' last_seen_id = 100 -- Assume posts table has these rows sorted by created_at DESC, id DESC: -- (2024-01-01 10:00:00, 100), (2024-01-01 09:59:59, 105), (2024-01-01 09:59:59, 102), (2024-01-01 09:59:58, 110), (2024-01-01 09:59:57, 101)
Remember that keyset pagination uses the tuple comparison to get rows strictly less than the last seen key.
The query fetches rows where the tuple (created_at, id) is less than (2024-01-01 10:00:00, 100) in descending order. So it excludes the last seen row and gets the next 3 rows with smaller tuples.
Which of the following is the main reason to prefer keyset pagination over offset pagination in REST APIs?
Think about how offset pagination slows down as the offset grows.
Offset pagination becomes slower with large offsets because the database must scan and skip many rows. Keyset pagination uses the last seen key to efficiently fetch the next set without scanning skipped rows.
Find the bug in this keyset pagination SQL query snippet:
SELECT * FROM messages WHERE created_at < :last_seen_created_at ORDER BY created_at DESC LIMIT 5;
Assume last_seen_created_at is the timestamp of the last message from the previous page.
Think about what happens if multiple messages share the same timestamp.
The query only filters by created_at < last_seen_created_at, so messages with the same timestamp as the last seen message are skipped entirely, causing missing data. Keyset pagination should include a tie-breaker column like id to avoid this.
Which option correctly implements a keyset pagination WHERE clause for sorting by created_at DESC and id DESC with last seen values :last_created_at and :last_id?
Remember that for descending order, smaller tuples come after larger ones.
Option D correctly expresses the tuple comparison for descending order by checking if created_at is less than last_created_at or equal but id is less. Option D is invalid syntax in many SQL dialects. Options C and D use the wrong comparison direction.
You have a REST API endpoint that returns a list of products sorted by updated_at DESC and product_id DESC. You want to implement keyset pagination. Which approach correctly returns the next page token and the next page of results?
Keyset pagination uses the last seen key to fetch the next page efficiently.
Option B correctly uses the last product's keys as a cursor token and filters the next page with a tuple comparison in descending order. Option B uses offset pagination, which is less efficient. Option B is unrelated to keyset pagination. Option B uses the first product's keys and the wrong comparison direction.