Row Restriction with LIMIT and OFFSET
Implements keyset pagination using LIMIT and OFFSET for efficient page-by-page result retrieval, with a fallback to cursor-based pagination for large datasets.
Code
-- Page 3 with 20 items per page (offset-based)
SELECT
product_id,
product_name,
unit_price,
created_at
FROM products
WHERE category_id = 1
ORDER BY created_at DESC, product_id ASC
LIMIT 20 OFFSET 40;
-- Keyset (cursor) pagination - more efficient for large offsets
SELECT
product_id,
product_name,
unit_price,
created_at
FROM products
WHERE category_id = 1
AND (created_at, product_id) < ('2025-01-10', 500)
ORDER BY created_at DESC, product_id ASC
LIMIT 20;Report a problem with this exampleOpens a pre-filled issue on GitHub.