Pagination, filtering and search end to end

Intermediate · 5 min

Make Taskboard's task list handle thousands of rows: cursor pagination, filters and search from the URL to the SQL, and why offset pages repeat items.

Before thisShaping queries for screens

Supabase · 5 min

Pagination, filtering and search end to end

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by SupabaseReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Offset pagination can repeat or skip rows when data changes between page requests, and it gets slower on deep pages.
  • Cursor pagination asks for rows after the last one you saw, using a stable sort key, so inserts do not shift the pages.
  • Filters, search text and the cursor all belong in the URL, so a page can be reloaded, shared and navigated with the back button.
  • Changing a filter or a search term must reset the cursor, because the old cursor points into a different result set.
  • User search text must have its wildcard characters escaped before it reaches ILIKE, or a percent sign matches everything.

A list that grows

Taskboard’s project page worked with 20 tasks. A real project has 2,000. Sending all of them is slow to query, slow to ship over the network, and slow to render, and nobody reads past the first screen. So the list needs to come in pieces, and people need ways to narrow it: by status, by assignee, by a word in the title.

This crosses every layer, which is why it’s a full-stack lesson. The URL says what the person wants. The API turns it into a query. The database does the narrowing. The client shows the next piece. The API-design roadmap covers the contract in pagination, filtering and sorting. Here we follow one request all the way through.

Offset pagination, and where it breaks

The obvious design is a page number: ?page=2, which becomes LIMIT 5 OFFSET 5, “skip the first five.” It is easy to build and lets people jump to page 40.

Here is the failure. I paged a project’s tasks newest first, five per page, on a database of 100 tasks. Page 1 returned ids [100, 99, 98, 96, 95]. Then someone else created a task. Page 2 returned:

page 2 after an insert: [95, 94, 92, 91, 90]

Task 95 appeared on both pages. The new row went to the top of the list and pushed everything down by one, so “skip five” skipped one fewer of the old ones. With a delete instead of an insert, a row would be skipped and never shown. Offset pagination on a list that changes gives wrong pages.

It has a second problem: to skip 5,000 rows, the database reads and discards 5,000 rows first, so deep pages get slower. The video below makes the case against OFFSET on large tables.

Cursor pagination

Instead of “skip N”, say “give me the rows after the one I last saw.” The last-seen row is the cursor. With newest-first ordering by id:

const limit = 10;
const rows = await db
  .select()
  .from(tasks)
  .where(and(eq(tasks.projectId, 1), cursor ? lt(tasks.id, cursor) : undefined))
  .orderBy(desc(tasks.id))
  .limit(limit + 1);

return {
  items: rows.slice(0, limit),
  nextCursor: rows.length > limit ? rows[limit - 1].id : null,
};

Three things to notice.

lt(tasks.id, cursor). “Rows with an id below the last one I saw.” A new row has a larger id, so it can never land inside a page you are partway through. This is a keyset query, and a database can run it with an index lookup instead of skipping rows.

limit + 1. Ask for one more row than you will return. If you get it, another page exists. You drop it and set nextCursor. If you don’t get it, nextCursor is null. That avoids a separate count(*) just to know whether to show a “load more” button.

A stable sort key. The sort must give every row a distinct, unchanging position. id does. If you sort by something that can tie or change, such as created_at alone or a title, add id as a tie-breaker and make the cursor carry both values. Without a unique order, rows get dropped or repeated at the boundaries.

I ran it on the seeded data. The first page gave [100, 99, 98, 96, 95, 94, 92, 91, 90, 88] with nextCursor 88, and the second page began at 87. No overlap.

The price: you can’t jump to page 40, only go forward from where you are. For an inbox or an activity feed that is fine. For a table where people need “go to page 12”, offset may still be the right trade, on data that doesn’t change much or is small enough not to matter.

Add the narrowing conditions to the same query. Each one is optional, and undefined inside and(...) drops out:

.where(and(
  eq(tasks.projectId, 1),
  status ? eq(tasks.status, status) : undefined,
  q ? ilike(tasks.title, `%${q}%`) : undefined,
  cursor ? lt(tasks.id, cursor) : undefined,
))

Searching for invoice returned the five seeded titles that contain it, Task 091 invoice down to Task 011 invoice.

Two catches.

Wildcards. In ILIKE, % and _ mean “anything” and “one character.” If the user types a literal %, you’ve handed them a wildcard. I searched for % and got 101 of 101 rows back. Escape those characters before building the pattern:

const esc = (s: string) => s.replace(/[\\%_]/g, "\\$&");

With that, the same search returned 0 rows, which is right. This isn’t SQL injection, since the value is still a bound parameter. It’s a correctness bug, and a slightly nasty one because it looks like the search “works.”

Speed. ILIKE '%invoice%' can’t use an ordinary index because the pattern starts with a wildcard. EXPLAIN reported Seq Scan on tasks with a filter. That’s fine at a few thousand rows and a problem at millions. Postgres has full-text search and trigram indexes for when it matters, and the backend roadmap covers search engines and full-text search. Start simple and measure.

The URL is the state

Filters, search and cursor are the page’s state, and people expect to reload, share and press Back. Put them in the query string:

/projects/1?status=doing&q=invoice&after=88

The client reads them from the URL, calls the API with them, and renders the answer. The API validates them with the same shared schema idea from earlier: status must be one of the three values, q has a maximum length, and limit has a ceiling (say 50) whatever the client asks for, so nobody requests a million rows.

Two behaviours to get right:

  • Changing a filter or the search text resets the cursor. The old cursor points into a different result set. Dropping after when anything else changes is the fix.
  • The response says what to ask next. The client should not compute the next cursor. It takes nextCursor from the response and puts it in the next request, unchanged. The cursor is opaque to the client.

If you worry about clients depending on what a cursor is, encode it (base64 of a small JSON object) so nobody builds logic on it.

Totals are expensive

“Showing 1 to 10 of 2,431” needs count(*) over the filtered set. Counting is a full pass, and it runs on every page request if you let it. Options: skip the total (“load more”), show it approximately, or fetch it once when the filter changes and not on every page. Pick based on whether the number helps anyone. I ran a count for one project and got 76 instantly on 101 rows; that tells you nothing about 10 million.

What the video covers

Supabase’s “SQL Pagination With Offset Might Be Making Your App 400x Slower” is under five minutes, published March 2026. Its description says OFFSET can slow down a whole database and that, for large datasets, a relative cursor is the alternative, and it links a Shopify engineering post on relative-cursor pagination. That is the core of the pagination half of this lesson, on a Postgres-based platform. It is a company channel, so expect a product plug. The filtering, URL, client and search parts are my own. I could not read a transcript, so I rely on the title and description. Andrey Fadeev’s Postgres full-text-search video, about thirteen minutes, is linked for the search half, and ByteByteGo’s three-minute animation as a second view of API pagination.

Where this fits

The data layer can now filter, search and page a list without lying. One more kind of data doesn’t fit in a table: files. Next, the last lesson of this group, follows an upload from the browser to storage and back: file uploads from browser to storage and back.

Check yourself

  1. 01What went wrong with offset pagination when a task was inserted between two page requests?

    Page 2 started with an item already shown on page 1, because the new row at the top pushed everything down by one.

  2. 02What does a cursor-paginated response need to include besides the items?

    A next cursor, such as the id of the last item, or null when there are no more rows, so the client knows what to ask for next.

  3. 03Why fetch limit plus one rows?

    The extra row tells you whether another page exists without a separate count query. You return only limit rows and set the cursor if the extra one was there.

  4. 04Why escape the user's search text before using ILIKE?

    Percent and underscore are wildcards. Unescaped, searching for a percent sign matched every row, 101 of 101 in my test, instead of none.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark