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.
Theory in plain words
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
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.
(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
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.
WHERE id < :lastId ORDER BY id DESC LIMIT 10.Quick quiz
1. How do you compute OFFSET?
Page 1 starts at offset 0.
2. Why debounce the search box?
It waits until typing pauses.
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.