SQL pagination with joins: 1431ms down to 61ms

SQL pagination with joins splits records across pages when LIMIT counts joined rows. Page the parent ids first: one history endpoint went from 1431ms to 61ms.

By

SQL pagination with joins has a trap that shows up the first time a page ends in the middle of a record. LIMIT 10 counts rows, and once a parent table is joined to its children, a row is no longer a record. It is one child of one record. I hit this on the workout history endpoint of a fitness app, where each workout carries many exercises. The endpoint was slow for a different reason, and fixing that meant moving the paging into SQL. This post covers why the naive version breaks, the two-step query I use instead, and how I proved the new pages matched the old output before shipping.

SQL pagination with joins: why LIMIT splits records

Picture a history screen that lists workouts, each with its exercises. The query joins workouts to exercises, so a workout with six exercises comes back as six rows. Put LIMIT 10 OFFSET 0 on that and you get ten rows, which might be one full workout, plus four exercises of the next one. The rest of that second workout lands on page two.

The client now has half a workout at the bottom of one page and the other half at the top of the next. Depending on how it merges pages, the user sees a workout with missing exercises, or the same workout twice. Neither looks like a paging bug from the outside, which is why this one tends to ship.

The same thing happens with any one-to-many join: orders and line items, posts and tags, users and roles. The page size you asked for is in records. The database is counting joined rows.

The slow version: build everything, then slice

The endpoint I was fixing avoided the split by not paging in SQL at all. It loaded the user's whole history window, built every workout in application code, and then sliced the array to the requested page.

That is correct, and on a small account it is fine. The cost is that every request builds the entire window regardless of page size. A request for 10 workouts did the work for all of them. On the account I measured, a 10 row page took 1431ms.

How do you paginate a query with joins?

Page the parent records first, then fetch their children. Select only the ids of the records you want on this page, with the ORDER BY, LIMIT and OFFSET applied to that id query. Then load those records whole, joins included, with a WHERE id IN (...) filter, so the joins can no longer cut a record in half.

Page the ids first, then fetch the records whole

This is the shape of the new query, with names simplified:

-- 1. The page, counted in workouts
SELECT w.id
FROM user_workouts w
WHERE w.user_id = $1
  AND w.completed_at >= $2
ORDER BY w.completed_at DESC, w.id DESC
LIMIT $3 OFFSET $4;

-- 2. Those workouts, whole
SELECT w.id, w.completed_at, e.id AS exercise_id, e.name, s.reps, s.weight
FROM user_workouts w
JOIN workout_exercises e ON e.user_workout_id = w.id
JOIN exercise_sets s ON s.workout_exercise_id = e.id
WHERE w.id = ANY($5)
ORDER BY w.completed_at DESC, w.id DESC, e.position, s.position;

In the real endpoint, the page is selected as distinct workout ids before the workouts are fetched whole. If the id query needs a filter on a child table, use EXISTS or SELECT DISTINCT so a parent with three matching children still counts once.

Two details matter more than they look:

  • The order must be total. Sorting by date alone lets two workouts with the same timestamp swap places between requests, and then a row can appear on two pages or none. Adding the primary key as a tie-breaker fixes that. The PostgreSQL LIMIT and OFFSET documentation is blunt about it: without an ORDER BY that fixes the order, you get an unpredictable subset of rows.
  • Both queries sort the same way. ANY($5) does not keep the order of the id list, so the second query repeats the ORDER BY.

With paging in SQL, the 10 row page dropped from 1431ms to 61ms. Most of the gain comes from no longer building the full window on every request.

OFFSET gets slower the deeper you page, because the database still walks the skipped rows. For a history screen that people scroll a few pages into, it is fine. For deep feeds, my default is keyset pagination: pass the last (completed_at, id) the client saw and query for rows after it.

Proving the new pages tile the old result

A paging rewrite can be wrong in quiet ways: a gap between pages, a duplicate at a boundary, a different order. So I compared output instead of reading the code and hoping.

I captured 384 responses across 8 users, both unit systems and 12 query shapes, before and after the change. 272 were byte identical. The other 112 differed only by an intended change to the default date window, from 7 to 90 days, and 0 differences were unexplained. Then I paged through the largest account: all 1040 rows across 11 pages, with no gaps and no duplicates, in the same order as a single large page.

That last check is the one I would never skip for a paging change. Fetch every page, concatenate them, and compare with one big request. I described the general method in verifying a refactor by diffing old and new output.

One query, not two copies

The paging fix came with a cleanup that mattered just as much. Two profile endpoints rendered the same payload for the same app screen, but each carried its own copy of the query and shaping code, about 470 lines each. They had drifted. One defaulted to a 7 day window and the other to 90, and one returned a field the other never emitted.

Both now call a single history builder, parameterised on the three things that actually vary: whose workouts to read, the viewer's units and timezone, and whether editing may be offered. Each controller keeps its own auth checks and response envelope, so neither contract changed.

Sharing the builder did not catch everything on its own. A week later I found that the own-profile endpoint never passed the page and page size through, so it took the unpaged branch and returned the whole window with no pagination envelope. The fix was a few lines, mirroring the other endpoint. Shared code still needs every caller to pass the right arguments.

A smaller version of the same drift showed up in date ranges. The map from a range like "3months" to a number of days was duplicated across five call sites, so I moved it into one utility. An unrecognised range now falls back to the 7 day default instead of silently widening the window. A bad input that quietly returns more data costs time on every request.

If your slow endpoint is a dashboard doing totals in application code, the related fix is moving the aggregation into Postgres. And once the query is right, an index audit on a production snapshot tells you whether the id query can use an index for its sort.

Where I'd start

  1. Find every endpoint that pages a joined query, or that pages by slicing an array in application code.
  2. Split it into an id query with a total ORDER BY and LIMIT, and a second query that loads those ids whole.
  3. Before shipping, capture responses from the old and new versions, and check that every page together equals one large request.
  4. If two endpoints build the same payload, give them one shared builder before they drift further.

This kind of backend performance work is a large part of what I do through my services.

Want this kind of work on your product?

Get in touch