Everyday Data Science
Latest
Agentic workflows now power a third of surveyed enterprise automationAfrica's AI startup ecosystem posts record funding yearNew benchmark results reshape the coding-agent leaderboardNigeria launches national AI strategy with major investment planRwanda's sovereign AI cloud enters public betaThe future of AI agents: from tools to teammates
Careers & SkillsTutorial

Pagination Traps: Five Ways LIMIT Quietly Changes the Answer

Part 12 of The Practical Data Analyst. On a 12-row orders table, a top-5 cut splits a tie in half, one insert makes OFFSET repeat a row, and a median built from a single OFFSET row is wrong by $5.

Ibrahim Denis FofanahIbrahim Denis FofanahData Scientist & AI Researcher8 min read·The Practical Data Analyst · Careers
Part 9 of 13The Practical Data AnalystView path →

Pagination looks like the safest part of a query. You sort, you take a page, you move on. The traps in this piece are quiet because none of them raise an error. Each query runs, returns rows, and looks finished. The problem is which rows.

This is Part 12 of The Practical Data Analyst. Earlier parts covered window functions, validation checks, JOIN traps, date traps, aggregation traps, EXPLAIN QUERY PLAN, string traps, CTE traps, NULL traps, subquery traps, and GROUP BY traps. This part is about the last lines of the query: ORDER BY, LIMIT, and OFFSET.

The setup

The table holds 12 orders. Amounts were chosen so ties sit exactly where a page or a top-N cut lands.

CREATE TABLE orders (
  id INTEGER PRIMARY KEY,
  customer TEXT,
  amount REAL,
  created TEXT
);
 
INSERT INTO orders VALUES
  (1, 'A', 100, '2026-01-01'),
  (2, 'B', 100, '2026-01-02'),
  (3, 'C', 100, '2026-01-03'),
  (4, 'D', 100, '2026-01-04'),
  (5, 'E',  90, '2026-01-05'),
  (6, 'F',  90, '2026-01-06'),
  (7, 'G',  80, '2026-01-07'),
  (8, 'H',  80, '2026-01-08'),
  (9, 'I',  80, '2026-01-09'),
  (10, 'J', 70, '2026-01-10'),
  (11, 'K', 60, '2026-01-11'),
  (12, 'L', 50, '2026-01-12');

Ground truth, checked before any trap: 12 rows, $1,000 total. Sorted amounts run 50, 60, 70, 80, 80, 80, 90, 90, 100, 100, 100, 100. Keep those counts in mind. Every trap below breaks one of them in a way you can count.

Trap 1: LIMIT without ORDER BY asks for rows that do not exist as a set

SELECT id FROM orders LIMIT 3;
-- returned: 1, 2, 3

That result looks stable, and on a small table it usually is. It is still not a promise. Without ORDER BY, the SQL documentation for both SQLite and PostgreSQL treats the row order as undefined. The engine returns rows in the order it happens to read them, which can change after an index is added, a table is rebuilt, or a query plan changes.

The practical failure is a report that says "the first three orders" when the query never defined first. First by what? Entry order, date, amount, and id are four different answers. If the question contains a word like first, latest, or top, the query needs an ORDER BY that matches that word.

Trap 2: A top-N cut through a tie picks a winner at random

SELECT id, amount FROM orders
ORDER BY amount DESC
LIMIT 5;
-- 1 ($100), 2 ($100), 3 ($100), 4 ($100), 5 ($90)

Four orders tie at $100. Two orders tie at $90, in positions five and six. LIMIT 5 keeps id 5 and drops id 6. Both orders are $90. The query has no basis for choosing between them, and a different plan can choose the other one.

Add a unique tiebreaker and the choice becomes a rule you can defend:

SELECT id, amount FROM orders
ORDER BY amount DESC, id ASC
LIMIT 5;

Now id 5 wins because its id is smaller, every time, on every engine. That may still be the wrong business rule. If the report says "top five orders," tied orders at the boundary deserve a decision: include both tied rows (six rows), rank them and report the tie, or state the tiebreaker in the report. What you cannot do is let the engine decide silently.

The RANK() function shows why this matters. On this table RANK() gives all four $100 orders rank 1, both $90 orders rank 5, and the three $80 orders rank 7. There is no rank 2, 3, or 4. A "top five" by rank and a "top five" by row count are different sets.

Trap 3: OFFSET counts positions, so one insert repeats a row

This trap needs a second table, a feed of 12 posts paged newest first, four per page.

-- page 1
SELECT id FROM feed ORDER BY id DESC LIMIT 4 OFFSET 0;
-- 12, 11, 10, 9

Now one new post arrives, id 13, before page 2 is requested. That is normal for any live feed, inbox, or orders list.

-- page 2, after the insert
SELECT id FROM feed ORDER BY id DESC LIMIT 4 OFFSET 4;
-- 9, 8, 7, 6

Id 9 was the last row of page 1. It is also the first row of page 2. The insert shifted every position down by one, and OFFSET counts positions, so the boundary row moved into the next page. Run the same pattern with a delete instead and a row is skipped entirely. No error appears in either case. A user scrolling a feed sees a duplicate. An analyst paging through an export gets one order counted twice and another never counted at all.

Keyset pagination fixes this by remembering a value, not a position. Page 1 ended at id 9, so page 2 asks for rows after that point:

SELECT id FROM feed
WHERE id < 9
ORDER BY id DESC
LIMIT 4;
-- 8, 7, 6, 5

No repeat, and the new post does not disturb pages that were already read. The trade-off is real: keyset pagination cannot jump straight to page 40, because there is no page 40, only a continuation from the last row seen. For numbered reports on a static table, OFFSET is fine. For a live list a user scrolls forward, keyset is the safer default.

Trap 4: Paging by a non-unique column splits a tie across pages

Page the orders table by amount, four rows per page:

SELECT id, amount FROM orders
ORDER BY amount DESC LIMIT 4 OFFSET 4;
-- page 2: 5 ($90), 6 ($90), 7 ($80), 8 ($80)
 
SELECT id, amount FROM orders
ORDER BY amount DESC LIMIT 4 OFFSET 8;
-- page 3: 9 ($80), 10 ($70), 11 ($60), 12 ($50)

The three $80 orders are split: ids 7 and 8 on page 2, id 9 on page 3. Inside a tie, the order is undefined, so which $80 order lands on which page is not guaranteed. Rebuild the table or change the plan and id 9 can trade places with id 7. Any per-page subtotal, per-page chart, or "page 2 orders" list built on this ordering is built on sand.

The fix is the same tiebreaker rule as Trap 2, applied to paging: ORDER BY amount DESC, id ASC makes every row's position unique and repeatable. A page boundary can still cut through a tie, but it now cuts at the same place every time, and you can see and document where.

Trap 5: A median from one OFFSET row is wrong when the count is even

A common median recipe sorts the values and takes the middle row:

SELECT amount FROM orders
ORDER BY amount
LIMIT 1 OFFSET 5;
-- $80

With 12 rows there is no single middle row. The middle is the average of the 6th and 7th sorted values, which are $80 and $90. The median is $85. The one-row recipe returns $80, wrong by $5, and it returns it confidently, with no sign that the count was even.

The correct version takes both middle rows for an even count:

SELECT AVG(amount) FROM (
  SELECT amount FROM orders
  ORDER BY amount
  LIMIT 2 OFFSET 5
);
-- $85

For an odd count the one-row recipe happens to work, which is why this bug survives. It passes every test on a 5-row or 11-row sample and fails the first time the real table has an even number of rows. Any OFFSET-based percentile has the same shape: check whether the position lands on one row or between two before you trust it.

The safe pattern

Four checks cover all five traps:

  1. Every LIMIT carries an ORDER BY that matches the words in the request: first, latest, top, or largest.
  2. Every ORDER BY used with LIMIT or OFFSET ends in a unique tiebreaker, usually the primary key.
  3. Before reporting a top-N list, check for a tie at the boundary. If the row at position N and the row at position N+1 share the sort value, decide the rule and write it down.
  4. For a live list, paginate by keyset on the last value seen. For a median or percentile, handle the even-count case explicitly.
-- top orders, deterministic, tie at the boundary visible
SELECT id, amount FROM orders
ORDER BY amount DESC, id ASC
LIMIT 5;
 
-- next page of a live feed, anchored on a value
SELECT id FROM feed
WHERE id < :last_seen_id
ORDER BY id DESC
LIMIT 4;

The verdict

LIMIT and OFFSET do exactly what they say. They take rows by position from an ordering you supply. Every trap in this piece came from treating a position as if it were a property of the row: assuming the first three rows exist without an ordering, assuming a top-5 boundary respects ties, assuming position 9 stays position 9 after an insert, or assuming a 12-row table has a middle row. Supply a total ordering, anchor live paging on values, and count the rows before you take the middle one, and all five traps close.

Key takeaways

  1. LIMIT without ORDER BY returns an undefined set. It is a peek, not an answer.
  2. A top-N cut through a tie keeps one tied row and drops another with no rule. Add a unique tiebreaker or include the full tie.
  3. OFFSET counts positions. One insert before page 2 repeated id 9 in the measured run. Keyset pagination returned 8, 7, 6, 5 with no repeat.
  4. Paging by a non-unique column splits ties across pages at places that can change between runs.
  5. With an even row count there is no middle row. The measured median is $85, the average of $80 and $90. The single-row recipe returned $80.

When you page through results, do you use OFFSET or a keyset cursor, and have you ever caught a duplicate or a missing row in a paged export?

Related on Everyday Data Science:

Sources: SQLite LIMIT and OFFSET, SQLite Tutorial, Pagination at Scale: OFFSET Versus Keyset, Kinda Technical

About the writer

Ibrahim Denis Fofanah
Ibrahim Denis Fofanah

Data Scientist & AI Researcher

3 followers

Data scientist and AI researcher at Pace University. I coined Artificial Frictional Unemployment, and built the first machine learning model for crop yield prediction in Sierra Leone. Author of Understanding Agentic AI. I write about agentic systems and applied ML, with a bias toward what actually works, and who gets left out when it doesn't.

Share

Found this useful? Passing it on to someone who builds is the best way to help the publication grow.

Built something worth sharing? Write it up for us →