SQL Boy
TutorialsPlayground

Format & Validate

SQL FormatterSQL MinifierSyntax Validator

Convert

JSON to SQLCSV to SQLSQL to JSONRegex to SQLExcel to SQLSQL Dialect Convertersoon

Visualize

ER Diagram GeneratorSQL Schema Diff

Generate

SQL Mock Data Generator

Analyze

SQL Query ExplainerSQL Query Analyzer

Workflow hubs

FormattingConversionSchemaAnalysis
View all tools
Daily ChallengeInterviewsCheat SheetBlog

© 2026 SQL Boy. Built for developers.

ContactPrivacyTermsAI Usage PolicyEditorial StandardsAboutRSS Feed

New conversation

What can I help with?

Ask about this page, get a hint on a challenge, or explore SQL concepts.

I know what's on this page and can give answers grounded in SQL Boy content.

Current page

Optimizing Large Dataset Queries

/blog/optimizing-large-dataset-queries

Usage status will load after login
SQL Boy
TutorialsPlayground

Format & Validate

SQL FormatterSQL MinifierSyntax Validator

Convert

JSON to SQLCSV to SQLSQL to JSONRegex to SQLExcel to SQLSQL Dialect Convertersoon

Visualize

ER Diagram GeneratorSQL Schema Diff

Generate

SQL Mock Data Generator

Analyze

SQL Query ExplainerSQL Query Analyzer

Workflow hubs

FormattingConversionSchemaAnalysis
View all tools
Daily ChallengeInterviewsCheat SheetBlog
Back to Blog
Published 2025-12-24
6 min read

Optimizing Large Dataset Queries: The Pagination Problem

performanceoptimizationpaginationlarge-data

Author

SQL Boy Team

Editorial Team at SQL Boy

This article is maintained as part of SQL Boy's hands-on SQL library.

We aim to keep examples runnable, call out dialect differences, and revise unclear sections over time.

Read editorial standardsAbout SQL BoyRequest a correction

If a result or dialect note looks wrong, email [email protected] with the article URL and the section you want reviewed.

It's a familiar scenario: your "Recent Activity" feed works perfectly with 100 items. But when you have 10 million items, clicking "Page 5000" causes the database to time out.

Why? Because of how standard pagination (OFFSET) works.

In this guide, we'll explore why deep pagination kills performance and how to fix it using the Seek Method (also known as Keyset Pagination).

Keyset pagination vs OFFSET showing direct index jump
Keyset pagination vs OFFSET showing direct index jump

The Problem with OFFSET

Most developers learn pagination like this:

-- Get Page 2 (Items 11-20)
SELECT * FROM orders 
ORDER BY date DESC 
LIMIT 10 OFFSET 10;

This seems fine. But what happens when you need Page 100,000?

-- Get Page 100,000
SELECT * FROM orders 
ORDER BY date DESC 
LIMIT 10 OFFSET 1000000;

The Database's Hidden Work: To fulfill OFFSET 1,000,000, the database must:

  1. Fetch 1,000,000 rows.
  2. Sort them.
  3. Throw them away.
  4. Return the next 10.

It gets slower and slower the deeper you go. This is O(N) complexity for pagination.

The Solution: Seek Method (Keyset Pagination)

The Seek Method doesn't count rows. It simply asks: "Give me the 10 rows after the last one I saw."

If the last order on Page 1 had id=500, Page 2 asks:

SELECT * FROM orders
WHERE id < 500  -- Assuming we sort DESC
ORDER BY id DESC
LIMIT 10;

Why it's fast: The database jumps directly to id=500 using the index. It doesn't read or sort the previous 499 rows. This is O(1) complexity—constant time, regardless of how deep you paginate!

Interactive Comparison

Let's verify this conceptual difference. While our dataset is small, the logic holds for millions of rows.

1. OFFSET Method (The Slow Way)

Interactive SQL
Loading...

2. Seek Method (The Fast Way)

Faster, but requires knowing the last ID from the previous page.

Interactive SQL
Loading...

Trade-offs

FeatureOFFSETSeek Method
PerformanceSlows down as pages increaseConstant speed
JumpingCan jump to "Page 500" easilyCannot jump (must scroll linearly)
ConsistencyRows can shift if new data is addedMore stable results (anchored to ID)
ImplementationTrivialComplex (need to track last ID)

Why Stable Ordering Matters

Keyset pagination only works well when the ordering is stable and deterministic.

This means your query should sort by a column, or set of columns, that gives every row a predictable position. A timestamp alone is often not enough because multiple rows can share the same value.

A safer production pattern is:

SELECT id, created_at, title
FROM posts
WHERE (created_at, id) < ('2026-04-01 10:00:00', 98123)
ORDER BY created_at DESC, id DESC
LIMIT 20;

That extra tie-breaker column prevents duplicates and missing rows when many records share the same timestamp.

Multi-Column Cursors in Real Apps

Most infinite-scroll interfaces do not paginate on a single numeric ID forever. They paginate on a business order:

  • newest events first
  • highest score first
  • orders by created date inside one account

In those cases, your cursor usually needs to store more than one field. Common examples include:

  • (created_at, id)
  • (score, id)
  • (customer_id, created_at, id) for per-customer feeds

The rule is simple: your cursor must match the same columns and order used in ORDER BY.

If it does not, the database cannot jump cleanly to the next page.

OFFSET Is Not Always Wrong

It is easy to overcorrect and declare OFFSET forbidden. That is not true.

OFFSET is often perfectly acceptable when:

  • the table is small
  • the result set is already tightly filtered
  • the page depth stays shallow
  • you genuinely need random page access, such as "jump to page 17"

The real problem is using OFFSET on a query shape that has to scan, sort, and discard enormous numbers of rows repeatedly.

This is why pagination strategy belongs inside the broader performance conversation. It is not just a UI choice. It is a database access pattern.

A Practical Pagination Workflow

Use this checklist when a listing page gets slow:

  1. Check the ORDER BY clause. Is it backed by a useful index?
  2. Measure whether the slowdown happens only on deeper pages.
  3. Confirm whether the query uses OFFSET or a cursor/seek pattern.
  4. Decide whether the product actually needs random access to deep pages.
  5. If not, switch the interface to cursor-based navigation and optimize for the real browsing pattern.

Many teams discover that users do not actually need "page 5000." They need "load more recent results quickly."

Tool Workflow

Use tools when pagination problems are hiding inside a larger slow query

Pagination performance is usually tied to ordering, filtering, and plan shape. These tools help you inspect the surrounding query rather than treating LIMIT/OFFSET as an isolated feature.

SQL Query Analyzer

Check for the broader anti-patterns that often accompany slow paginated queries, such as SELECT * and expensive filters.

SQL Query Explainer

Break down the query clauses so it is easier to reason about ORDER BY, WHERE, and LIMIT together.

Related Interview Question

This concept is so important it's a dedicated interview question!

  • Slow Query Detection (Databricks) - While this question focuses on finding slow queries, understanding why queries are slow (like inefficient scans) is key to solving performance problems.

Related Articles

  • SQL Optimization Techniques for the wider checklist around sorting, indexing, batching, and query rewrites.
  • How to Read SQL Execution Plans for understanding how sorts and scans show up when pagination starts getting expensive.
  • Understanding Database Indexes for the indexing patterns that make seek-based pagination efficient.

Conclusion

If you're building an "Infinite Scroll" feed (like Instagram or Twitter), always use the Seek Method. It scales infinitely.

If you are building a small admin dashboard with < 1,000 items, OFFSET is perfectly fine and easier to code.

Rule of thumb: Optimization is about picking the right tool for the scale.

Share this article:

Topic Path

This article belongs to a larger cluster

If this page matches the problem you are working on, jump to the topic hub to see the surrounding articles in the same path instead of treating this as a one-off post.

Performance

Query performance and optimization

Start here if your goal is faster SQL. This path connects indexing, execution plans, anti-patterns, and production query tuning.

Open topic hub

Related Articles

performanceoptimization

Essential SQL Optimization Techniques for Faster Queries

Is your query taking forever? Learn proven optimization techniques: indexing strategies, JOIN optimization, subquery rewrites, and execution plan analysis.

Read more
performanceoptimization

Simulating Materialized Views in SQLite with Triggers

SQLite doesn't support materialized views, but you can build them yourself! Learn how to use triggers to create high-performance cached summary tables.

Read more
performanceoptimization

SQL Anti-Patterns: The Silent Performance Killers in Your Queries

Is your query working but slow? You might be using an Anti-Pattern. Learn about SARGability, Implicit Conversions, and why your WHERE clauses are bypassing your indexes.

Read more
Previous

Using Regular Expressions in SQL

Next

Year-over-Year Growth Analysis in SQL

Comments

© 2026 SQL Boy. Built for developers.

ContactPrivacyTermsAI Usage PolicyEditorial StandardsAboutRSS Feed