TATECHATLAS
◎ English
Data & databases / Guide

Using LIMIT and OFFSET in PostgreSQL: Best Practices, Performance Impacts, and Alternatives

LIMIT caps returned rows; OFFSET skips rows in the query result. SQL does not require ORDER BY syntactically, but repeatable page boundaries need a unique ordering. For an API, choose between page-number navigation and continuation from the last key; neither strategy alone provides a snapshot. Measure deeper pages before setting a performance cutoff.

On this page

LIMIT caps returned rows; OFFSET skips rows in the query result. SQL does not require ORDER BY syntactically, but repeatable page boundaries need a unique ordering. For an API, choose between page-number navigation and continuation from the last key; neither strategy alone provides a snapshot. Measure deeper pages before setting a performance cutoff.

Basic Functionality of LIMIT and OFFSET in PostgreSQL

For an API page size of 20, page six corresponds to OFFSET 100. The database skips the first hundred rows of the ordered result and returns at most twenty, not necessarily exactly twenty. The example assumes blog_posts contains id, title and a non-null created_at, and id is unique. ORDER BY created_at DESC, id DESC breaks timestamp ties deterministically within a fixed dataset.

SELECT id, title, created_at
FROM blog_posts
ORDER BY created_at DESC, id DESC
LIMIT 20 OFFSET 100;

Use Cases for LIMIT/OFFSET in Paginated Workflows

Page numbers are useful when users need to jump to a known page or revisit a small stable list. Bound the accepted page size and offset, reject invalid parameters, and bind values rather than interpolating SQL. A total-count query is separate work and can be more expensive than retrieving a page. Decide whether the interface actually needs an exact total before computing it on every request.

Unique ordering for repeatable pages

ORDER BY is optional SQL syntax, but without it PostgreSQL does not promise row order. Ordering by created_at alone is also insufficient when timestamps tie. Adding a unique id makes the order total for unchanged data; it still cannot prevent page boundaries moving after concurrent insertions or deletions. Keep filter and sort semantics identical throughout continuation.

Performance Impact of Large OFFSET Values

Skipped OFFSET rows still need to be computed, so deeper pages can require more work even with an ordering index. There is no universal threshold of 1000 rows at which pagination becomes unacceptable. Compare actual plans and elapsed times for representative filters, offsets and data sizes. Index choice, row width, selectivity, cache state and the required response time all affect the decision.

Alternative Pagination: Cursor-Based Methods

A keyset query continues after the last sort key instead of counting past earlier rows. For descending created_at and id, use (created_at,id) < (last_created_at,last_id) with the same ORDER BY. The cursor must preserve both keys and the original filters. An appropriate index may make this efficient, but a cursor alone is not a performance guarantee. Non-null, immutable keys avoid additional continuation ambiguities.

Best Practices for Safe LIMIT/OFFSET Usage

The second query is a schema fragment using parameter placeholders; bind the actual last keys from the preceding page in the client. With three rows sharing timestamp t and ids 9, 8, 7, a two-row first page ends at (t,8), so the next predicate includes (t,7). Timestamp-only comparison would skip it. This illustrates why the tie-breaker must be in both sorting and the cursor predicate.

SELECT id, title, created_at
FROM blog_posts
WHERE (created_at, id) < (%(last_created_at)s, %(last_id)s)
ORDER BY created_at DESC, id DESC
LIMIT %(page_size)s;

Common Pitfalls to Avoid

Neither unique ordering nor keyset pagination freezes the dataset between HTTP requests. New records before an already passed boundary can be missed; editing sort keys can move rows across it. A feed may accept these semantics, whereas export or synchronization needs an explicit snapshot, fixed watermark or change-tracking contract. Also verify that a cursor cannot alter tenant or authorization filters.

When to Replace LIMIT/OFFSET with Other Methods

Keep OFFSET for bounded lists and direct page navigation when its measured cost is acceptable. Choose keyset for sequential continuation when the API can carry stable keys and users do not require arbitrary page jumps. GitHub endpoints have different pagination contracts, including page/per_page and Link headers; their documentation does not establish a universal cursor standard for all APIs.

Things to check

  • The fixed dataset has a unique ordering, including timestamp ties
  • The continuation contains every sort key and preserves filters and access scope
  • Accepted LIMIT/OFFSET values are bounded and bound as query parameters
  • Representative shallow and deep pages are measured before choosing a cutoff

Neither method supplies a cross-request snapshot by itself. Keyset performance depends on predicates and suitable indexes; nullable or changing sort keys require additional design. Numbers in the example illustrate ordering, not a measured benchmark or a universal offset limit.

Sources

  1. PostgreSQL: LIMIT and OFFSET ↗
  2. PostgreSQL: indexes and ordering ↗
  3. PostgreSQL: EXPLAIN ↗
  4. GitHub REST: endpoint-specific pagination ↗
Back to top ↑