Home / Learn React / Search, Sort and Pagination with MySQL

Search, Sort and Pagination with MySQL

Never load a whole table into React. Let MySQL search and cut the data into pages with LIMIT and OFFSET.

In shortSend q and page to PHP. MySQL runs WHERE ... LIKE, ORDER BY and LIMIT/OFFSET and returns one page plus the total count. React shows the page and buttons.

Theory in plain words

Search and pageUser types or clicks pagewait 300 ms (debounce)GET ?q=sql&page=2LIMIT 10 OFFSET 10JSON rows + totalReact shows page
Search and page

What it is

Pagination means showing a big list a page at a time. Search means sending the user text to the server so MySQL filters the rows.

Why we use it

A table can have 100,000 rows. Downloading all of them makes the page slow and wastes mobile data. The database is built to find the right 10 rows quickly.

How it works

The SQL is WHERE title LIKE :q ORDER BY id DESC LIMIT 10 OFFSET 20. OFFSET is (page - 1) * perPage. A second query COUNT(*) gives the total so React can compute the number of pages.

Where it is used

  • Product lists, admin tables, blog archives, search boxes
  • Any list that can grow past about 50 rows

The SQL

Page 3, 10 per page
SELECT id, title FROM notes
WHERE title LIKE '%sql%'
ORDER BY id DESC
LIMIT 10 OFFSET 20;        -- (3 - 1) * 10

SELECT COUNT(*) FROM notes WHERE title LIKE '%sql%';

The PHP side is already in api/notes.php from the previous lesson. It reads q and page, uses prepared statements and returns total, page and per.

Careful:LIMIT and OFFSET must be integers. Cast with (int) and bind with PDO::PARAM_INT. Never put the sort column from the URL straight into SQL. Use a whitelist: $cols = ['id', 'title']; $col = in_array($_GET['sort'] ?? '', $cols) ? $_GET['sort'] : 'id';

React: search box with debounce and page buttons

Server style search and pagination (fake server)Try it Yourself

The cancelled flag stops an old slow answer from replacing a newer one. The debounce waits until the user stops typing so you do not hit the database on every key.

Tip:For very large tables, OFFSET gets slow on deep pages. Switch to keyset pagination: WHERE id < :lastId ORDER BY id DESC LIMIT 10.

Quick quiz

1. How do you compute OFFSET?

2. Why debounce the search box?

Common questions

How do you compute OFFSET?

(page - 1) * per. Page 1 starts at offset 0.

Why debounce the search box?

To avoid a request on every key press. It waits until typing pauses.