SQL

Pagination with LIMIT / OFFSET

admin by @admin ADMIN
7m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`LIMIT N OFFSET M` is universal — but degrades on deep pages (the DB still has to scan past M rows). Keyset (cursor) pagination is much faster for huge tables.
SQL
Raw
-- Page 3 of 25 results (offset = (page - 1) * page_size)
SELECT id, title, created_at
FROM   posts
ORDER  BY created_at DESC, id DESC
LIMIT  25 OFFSET 50;

-- Pagination metadata in one query (PostgreSQL window function)
SELECT id, title, COUNT(*) OVER() AS total_rows
FROM   posts
ORDER  BY created_at DESC
LIMIT  25 OFFSET 0;

-- Keyset (cursor) pagination — faster, immune to inserts shifting pages
-- The caller passes the last-seen (created_at, id) tuple from the prior page.
SELECT id, title, created_at
FROM   posts
WHERE  (created_at, id) < ('2025-03-12 14:00:00', 12345)
ORDER  BY created_at DESC, id DESC
LIMIT  25;
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.