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.

SqlData Fetching

Code

snippet
-- 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;

What the code does

What runs here is SELECT — products are the objects involved.

Concretely, the SQL combines: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size.

Applying it

Run the statement against the products table; the LIMIT keeps the probe cheap while you tune the predicates.

Statements that matter

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;
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;

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
The references are `products`.