# Search, filters & pagination

> Keep catalogs, admin tables, and booking lists instant at thousands of rows using server-side search, faceted filters, indexes, and stable pagination.

- Canonical: https://exaspark.ai/docs/search-filtering-pagination/

## Client-side vs server-side filtering

Early prototypes often load an entire table into the browser and filter in memory. With 25 test items that feels instant, yet at 4,000 orders it downloads megabytes per visit, lags on mobile, and risks exposing hidden rows in DevTools.

Moving search, filters, sorting, and pagination to the **server** lets database indexes return strictly the 20 to 50 rows visible on the current page.

| Factor | Client-side filtering | Server-side search & pagination |
| --- | --- | --- |
| **Sweet spot** | Static lists under ~100 rows (countries, 12 studio classes) | Growing catalogs, bookings, member directories, orders, logs |
| **Network payload** | Downloads the full table on every visit | Sends one page (20–50 rows) plus total counts |
| **Freshness** | Stale until full page refresh | Reflects live stock, prices, and cancellations immediately |
| **Data privacy** | Risky — hidden rows may remain in browser JSON | Safe — server enforces row ownership before paginating |
| **URL sharing** | Easily lost on refresh unless wired manually | Syncs cleanly with query params for links and Back clicks |

## Designing clean URL-driven query parameters

Always store active search text, filter chips, sort order, and page number in the browser URL — never only in temporary component state.

When a shopper filters your store to `?q=ceramic&category=mugs&min_price=1500&sort=price_asc&page=2`, clicks a mug to read its details, and presses **Back**, URL-driven state returns them to page 2 with their exact filters intact. It also lets customers paste filtered views into messages and helps search engines index key category pages cleanly.

Design one predictable request and response contract for every paginated endpoint:

```http
GET /api/products?q=ceramic&category=mugs&in_stock=true&sort=price_asc&page=2&page_size=24
```

```json
{
  "items": [
    { "id": "prod_8f2a", "title": "Stoneware Coffee Mug", "price_cents": 2800, "in_stock": true }
  ],
  "pagination": {
    "page": 2,
    "page_size": 24,
    "total_items": 87,
    "total_pages": 4,
    "has_next": true,
    "has_prev": true
  },
  "facets": {
    "categories": [
      { "slug": "mugs", "label": "Mugs", "count": 87 },
      { "slug": "bowls", "label": "Bowls", "count": 41 }
    ]
  }
}
```

Returning `total_items`, `has_next`, and category `facets` from the server lets your UI display accurate result counts ("Showing 25–48 of 87 mugs") without fetching the remaining 63 records.

## Pagination strategies: offset vs cursor

Not every list should be paginated the same way. Pick **offset pagination** for catalogs and admin tables, and **cursor pagination** for rapidly changing feeds or deep logs.

| Strategy | How it works | Best for | Trade-offs |
| --- | --- | --- | --- |
| **Offset (`page` + `page_size`)** | Skips `(page - 1) * page_size` rows and returns the next slice | Store catalogs, search results, admin tables where users jump to page 4 | Slows down at very deep offsets (page 500+); new inserts can shift items slightly between pages |
| **Cursor (`after` token + `limit`)** | Fetches rows strictly after the last item's sort value and ID | Activity feeds, chat history, webhook logs, mobile "Load more" lists | Constant speed even at 100,000+ rows and zero duplicate skips; cannot jump straight to page 9 |

### Always include a deterministic tie-breaker sort

If twenty products share the exact price `$25.00` — or ten orders share the same `created_at` second — sorting only by `price_cents ASC` lets tied rows shuffle between pages, causing duplicates or missing items.

Always include the unique primary key as a **stable tie-breaker**, such as `ORDER BY price_cents ASC, id ASC` or `ORDER BY created_at DESC, id DESC`.

## Fast search, multi-facet filters, and indexes

Great search feels effortless to visitors because a handful of quiet backend and UI details work together.

### Debounce search input and reset page numbers

Never fire a fresh server query on every single keystroke. Wait **250–300 milliseconds** after the visitor stops typing (debounce), cancel any stale in-flight request if they type again, and always reset `page` back to `1` whenever the search term, filter, or sort order changes.

### Whitelist sort columns and clamp page sizes

Never pass a raw `sort` query string directly into a database query, and never let a caller request `?page_size=50000` to scrape or stall your server.

- **Map sort keys through an allowlist** (`newest`, `price_asc`, `price_desc`, `popular`) on the server, falling back cleanly to a safe default.
- **Clamp `page_size`** to a sensible maximum (such as `100` for admin tables and `48` for consumer catalogs).

### Add indexes matching your actual filters

Without an index, the database scans every row in the table on every search. Request targeted indexes alongside your filters so queries stay under a few milliseconds even at 50,000 rows:

- **Single-column indexes** on high-frequency filters like `status`, `category_id`, `slug`, and foreign keys (`user_id`, `workspace_id`).
- **Composite indexes** matching your most common filter + sort pair — such as `(workspace_id, status, created_at DESC)` for a SaaS task table or `(category_id, is_active, price_cents ASC)` for a storefront.
- **Case-insensitive text search** across `title`, `sku`, and `description` so searching `"espresso"` matches `"Matte Espresso Cup"` reliably.

## Building a fast catalog or admin directory

Follow four concrete steps to wire search, multi-facet filtering, and pagination cleanly in your ExaSpark project.

1. **Define filters, sort options, and page size** — List exact filter facets (category, status, date range, price range), allowed sort keys, and default rows per page (typically 20–24).
2. **Sync UI controls to URL query params** — Connect the search input (with 300ms debounce), filter chips, sort dropdown, and pager directly to URL parameters, resetting `page=1` on any filter change.
3. **Add matching indexes and tie-breaker sorts** — Ask ExaSpark to create composite indexes for your filter-and-sort combinations and include `id` as the tie-breaker on every `ORDER BY`.
4. **Stress-test with 200+ seeded Preview rows** — Empty or 5-row tables hide pagination bugs. Seed realistic volume in **Preview**, click through pages, press Back, and check mobile filter drawers before publishing.

> **Example prompt (App):** Upgrade our `/products` catalog to server-side search, multi-facet filtering, sorting, and pagination. Support URL query params `q` (case-insensitive search across `title`, `sku`, and `description` with 300ms debounce), `category`, `min_price`, `max_price`, `in_stock`, `sort` (whitelisted to `newest`, `price_asc`, `price_desc`), `page`, and `page_size` (default 24, max 48). Always reset `page=1` when any filter changes, apply a stable `id` tie-breaker to every sort, add composite database indexes on `(is_active, category_id, price_cents)`, show active filter chips with a one-click "Clear all" button, and seed 180 sample products in Preview so we can test pagination end to end.

## Common search & pagination bugs

Even experienced teams run into these five subtle issues once real data fills a table. Keep this diagnosis table handy during Preview QA.

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| **Filtering while on page 4 shows "No results found" even though matches exist** | Filter change kept `page=4` in the URL while the narrowed result set only has 1 page | Automatically reset `page=1` whenever `q`, any filter, or `sort` changes |
| **Same item appears at the bottom of page 1 and top of page 2** | Sorting by a non-unique column (like `price_cents` or `status`) without a tie-breaker | Add `id` as a secondary sort column (`ORDER BY price_cents ASC, id ASC`) |
| **Typing fast shows outdated results flickering back** | Earlier slower API response resolved after a newer keystroke response | Debounce input by 250–300ms and abort/ignore superseded requests |
| **Category filter count shows 80 items, but only 12 appear** | Facet count ignored another active filter (such as `is_active = true` or `in_stock = true`) | Apply base visibility filters consistently to both the item query and facet counts |
| **Admin orders screen stalls at 5,000 rows** | Missing composite index on `(status, created_at DESC)` or unpaginated query loading full table | Enforce server pagination (max 100 rows/page) and add a composite index matching the default sort |

> **Note:** **Design great empty states.** Distinguish clearly between "No products exist yet" (first-run zero state) and "No matches for your current filters" (include a one-click **Reset filters** button so visitors never hit a dead end).

## Next steps

- [Database & data modeling](https://exaspark.ai/docs/accounts-and-data/) — Core schema habits, indexes, and avoiding N+1 query loops.
- [Table relationships guide](https://exaspark.ai/docs/table-relationships/) — Structure linked categories, tags, and workspaces cleanly for faceted filters.
- [Page speed & Core Web Vitals](https://exaspark.ai/docs/page-speed-and-core-vitals/) — Keep catalog pages fast and responsive across mobile connections.

## From the blog

- [How to make a website load faster](https://exaspark.ai/blog/how-to-make-a-website-load-faster/) — Practical speed wins from smaller payloads to snappy server responses.
- [What is a database?](https://exaspark.ai/blog/what-is-a-database/) — How tables, queries, and indexes turn raw records into fast screens.
- [What is an API?](https://exaspark.ai/blog/what-is-an-api/) — Designing clean query parameters and predictable JSON endpoints.
