Paging results with LIMIT and OFFSET from Java
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A shop with lakhs of products cannot send every row to every screen. How do you show 20 at a time, with "Page 2 of 3", without skipping or repeating rows?
Why findAll without a limit fails once data grows
Paging means reading a list one fixed-size page at a time: 20 products now, the next 20 when the user asks.
findAll on 15 products is instant, so the problem hides during development. Example 1 adds 2,00,000 test products to a practice copy of the database and compares.
Example 1 · src/main/java/com/shoplite/app/BigTableDemo.java
Runs in: the shoplite-console project with a practice copy of the ShopLite database
package com.shoplite.app;
import com.shoplite.config.ConnectionFactory;import com.shoplite.config.DatabaseConfig;import com.shoplite.dao.JdbcProductDao;import com.shoplite.dao.JdbcTransactionManager;import com.shoplite.model.Page;import com.shoplite.model.Product;
import java.math.BigDecimal;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;
/** Fills a practice copy of the database with 200,000 extra products, then compares. */public class BigTableDemo {
public static void main(String[] args) throws SQLException { ConnectionFactory connections = new ConnectionFactory(DatabaseConfig.load()); addTestProducts(connections, 200_000); JdbcProductDao dao = new JdbcProductDao(new JdbcTransactionManager(connections)); dao.findActive(1, 1); // warm-up: driver and first connection
long start = System.nanoTime(); List<Product> all = findAllActive(connections); System.out.println("findAll: " + all.size() + " objects in memory, " + ms(start) + " ms");
start = System.nanoTime(); Page<Product> first = dao.findActive(1, 20); System.out.println("page 1: " + first.items().size() + " objects in memory, " + ms(start) + " ms");
start = System.nanoTime(); Page<Product> deep = dao.findActive(10_000, 20); System.out.println("page 10000: " + deep.items().size() + " objects in memory, " + ms(start) + " ms"); }
private static long ms(long start) { return (System.nanoTime() - start) / 1_000_000; }
/** The old findAll: every active row becomes an object in memory. */ static List<Product> findAllActive(ConnectionFactory connections) throws SQLException { String sql = "SELECT product_id, sku, name, category_id, price, stock, is_active FROM products" + " WHERE is_active = TRUE ORDER BY name, product_id"; List<Product> list = new ArrayList<>(); try (Connection con = connections.getConnection(); PreparedStatement ps = con.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { while (rs.next()) { list.add(new Product(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getInt(4), rs.getBigDecimal(5), rs.getInt(6), rs.getBoolean(7))); } } return list; }
static void addTestProducts(ConnectionFactory connections, int count) throws SQLException { String sql = "INSERT INTO products (sku, name, category_id, price, stock) VALUES (?, ?, 4, ?, 10)"; try (Connection con = connections.getConnection(); PreparedStatement ps = con.prepareStatement(sql)) { con.setAutoCommit(false); for (int i = 1; i <= count; i++) { ps.setString(1, String.format("GEN-%06d", i)); ps.setString(2, String.format("Test cable %06d", i)); ps.setBigDecimal(3, new BigDecimal("199.00")); ps.addBatch(); if (i % 5_000 == 0) { ps.executeBatch(); } } con.commit(); } }}findAll: 200014 objects in memory, 1551 ms page 1: 20 objects in memory, 415 ms page 10000: 20 objects in memory, 724 ms
What this code does
- The old
findAllturns all 2,00,014 active rows intoProductobjects to show 20 of them. Time and memory grow with the table, forever. - A page always brings back 20 objects. Page 1 still takes some time because
productshas no index onname, so MySQL sorts every row before it can return the first 20; an index on the sort columns (see the indexes module) fixes that. - Page 10,000 is slower than page 1: MySQL walks past 1,99,980 rows to reach it. Run this only on a practice database, and load the ShopLite script again afterwards.
An unbounded query returns every row of a table: each call sends all rows over the network, builds an object for each one and holds them all in memory, while the screen shows only 20. Loading everything takes seconds and fills memory; one page brings back 20 objects. With many users at once, the unbounded version is how an app runs out of memory.
LIMIT.LIMIT ? OFFSET ? from page number and page size
LIMIT n returns at most n rows, and OFFSET k skips the first k rows of the sorted result. A paged query takes both as ? parameters.
For page numbers that start at 1, the offset is (page − 1) × size: page 1 skips 0 rows, page 2 skips one page. Both values are set with setInt.
String sql = "SELECT " + COLUMNS + " FROM products WHERE is_active = TRUE" + " ORDER BY name, product_id LIMIT ? OFFSET ?";try (ConnectionLease lease = tx.lease(); PreparedStatement ps = lease.connection().prepareStatement(sql)) { ps.setInt(1, size); // LIMIT: how many rows ps.setInt(2, (page - 1) * size); // OFFSET: how many rows to skip ...}Size 5: page 1 gives LIMIT 5 OFFSET 0 (rows 1 to 5), page 2 gives OFFSET 5 (rows 6 to 10) and page 3 gives OFFSET 10 (rows 11 to 15). A page past the end returns an empty list, not an error.
Predict the output
Which LIMIT and OFFSET?
Page numbers start at 1. Pick the values the DAO sends.
Round 1 of 3
Page 3 with a page size of 20.
A Page<T> record with items, page, size and total
Page<T> is a generic record that holds one page of results: items, page, size and totalItems. It works out totalPages() and hasNext() from them.
The menu must print "Page 2 of 3" and know whether to offer "next". Example 2 builds the Page record in memory, and Example 3 uses it with MySQL.
Example 2 · The Page record and in-memory paging
import java.util.List;
record Page<T>(List<T> items, int page, int size, long totalItems) {
int totalPages() { return (int) ((totalItems + size - 1) / size); // rounded up }
boolean hasNext() { return page < totalPages(); }
boolean hasPrevious() { return page > 1; }}
public class PageRecordDemo { static <T> Page<T> pageOf(List<T> all, int page, int size) { int from = Math.min((page - 1) * size, all.size()); int to = Math.min(from + size, all.size()); return new Page<>(all.subList(from, to), page, size, all.size()); }
public static void main(String[] args) { List<String> products = List.of("Atomic Habits", "boAt Airdopes 141", "Clean Code", "Cotton Kurta", "HP Victus 15 Gaming", "iPhone 15 128GB", "Lenovo IdeaPad Slim 3", "Logitech M331 Silent Mouse", "Mi Power Bank 20000mAh", "Prestige Pressure Cooker 3L", "Redmi Note 13 5G", "Running Shoes", "Samsung Galaxy M35", "The Pragmatic Programmer");
for (int p = 1; p <= 4; p++) { Page<String> page = pageOf(products, p, 5); String first = page.items().isEmpty() ? "-" : page.items().get(0); System.out.println("Page " + page.page() + " of " + page.totalPages() + ": " + page.items().size() + " items, first " + first + ", hasNext=" + page.hasNext()); } System.out.println("0 rows -> " + new Page<String>(List.of(), 1, 5, 0).totalPages() + " pages"); System.out.println("15 rows -> " + new Page<String>(List.of(), 1, 5, 15).totalPages() + " pages"); System.out.println("16 rows -> " + new Page<String>(List.of(), 1, 5, 16).totalPages() + " pages"); }}Page 1 of 3: 5 items, first Atomic Habits, hasNext=true Page 2 of 3: 5 items, first iPhone 15 128GB, hasNext=true Page 3 of 3: 4 items, first Redmi Note 13 5G, hasNext=false Page 4 of 3: 0 items, first -, hasNext=false 0 rows -> 0 pages 15 rows -> 3 pages 16 rows -> 4 pages
What this code does
(totalItems + size - 1) / sizerounds up with whole numbers: 14 rows make 3 pages, 15 make 3, 16 make 4, and 0 rows make 0 pages.- Page 4 is past the end, so it is empty and
hasNextis false. The record is the same one ShopLite's DAO returns, so the menu code works for both.
Example 3 · src/main/java/com/shoplite/app/PagingDemo.java
Runs in: the shoplite-console Maven project with the MySQL driver and the ShopLite database
package com.shoplite.app;
import com.shoplite.config.ConnectionFactory;import com.shoplite.config.DatabaseConfig;import com.shoplite.dao.JdbcProductDao;import com.shoplite.dao.JdbcTransactionManager;import com.shoplite.model.Page;import com.shoplite.model.Product;
public class PagingDemo {
public static void main(String[] args) { JdbcTransactionManager tx = new JdbcTransactionManager(new ConnectionFactory(DatabaseConfig.load())); JdbcProductDao dao = new JdbcProductDao(tx);
for (int page = 1; page <= 4; page++) { Page<Product> result = dao.findActive(page, 5); System.out.printf("Page %d of %d, %d items, hasNext=%b%n", result.page(), result.totalPages(), result.items().size(), result.hasNext()); for (Product p : result.items()) { System.out.println(" " + p.id() + " " + p.name()); } } }}Page 1 of 3, 5 items, hasNext=true 11 Atomic Habits 6 boAt Airdopes 141 9 Clean Code 12 Cotton Kurta 5 HP Victus 15 Gaming Page 2 of 3, 5 items, hasNext=true 3 iPhone 15 128GB 4 Lenovo IdeaPad Slim 3 8 Logitech M331 Silent Mouse 7 Mi Power Bank 20000mAh 14 Prestige Pressure Cooker 3L Page 3 of 3, 4 items, hasNext=false 1 Redmi Note 13 5G 13 Running Shoes 2 Samsung Galaxy M35 10 The Pragmatic Programmer Page 4 of 3, 0 items, hasNext=false
What this code does
findActiverunsLIMIT 5 OFFSET 0,5,10and15plus aCOUNT(*)for each page. 14 of the 15 products are active (the USB-C cable is not), so there are 3 pages.- "boAt" sorts between "Atomic" and "Clean": the table's collation (
utf8mb4_0900_ai_ci) ignores letter case. A JavaStringcomparison would put "boAt" after every capital letter.
The total needs a second query, SELECT COUNT(*) with the same WHERE, run on the same connection. The number of pages is a rounded-up division: 14 products in pages of 5 is 3 pages, which in integer maths is (14 + 5 − 1) / 5.
Find the bug
Find the Page bug
Each method of the Page record gives wrong answers. Tap the wrong line.
14 rows in pages of 5 must give 3 pages.
Round 1 of 2A stable ORDER BY so pages never repeat or skip rows
A tie-breaker is a unique column, usually the primary key, added at the end of ORDER BY so every row has exactly one fixed position.
Each page is a separate query, so the rows must come back in the same order every time. Example 4 pages a tied sort, with and without a tie-breaker.
Example 4 · src/main/java/com/shoplite/app/TieOrderDemo.java
Runs in: the shoplite-console Maven project with the MySQL driver and the ShopLite database
package com.shoplite.app;
import com.shoplite.config.ConnectionFactory;import com.shoplite.config.DatabaseConfig;
import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Set;
/** "Budget picks first": products under Rs 1000 on top, in pages of 3. */public class TieOrderDemo {
public static void main(String[] args) throws SQLException { ConnectionFactory connections = new ConnectionFactory(DatabaseConfig.load()); for (String orderBy : new String[] {"price < 1000 DESC", "price < 1000 DESC, product_id"}) { List<Integer> seen = new ArrayList<>(); try (Connection con = connections.getConnection()) { for (int page = 1; page <= 5; page++) { String sql = "SELECT product_id FROM products ORDER BY " + orderBy + " LIMIT 3 OFFSET ?"; try (PreparedStatement ps = con.prepareStatement(sql)) { ps.setInt(1, (page - 1) * 3); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { seen.add(rs.getInt(1)); } } } } } Set<Integer> distinct = new HashSet<>(seen); System.out.println("ORDER BY " + orderBy + ": " + seen); System.out.println(" rows shown " + seen.size() + ", different products " + distinct.size()); } }}ORDER BY price < 1000 DESC: [10, 15, 9, 11, 12, 15, 1, 2, 3, 4, 5, 6, 7, 13, 14] rows shown 15, different products 14 ORDER BY price < 1000 DESC, product_id: [8, 9, 10, 11, 12, 15, 1, 2, 3, 4, 5, 6, 7, 13, 14] rows shown 15, different products 15
What this code does
- "Budget picks first" sorts by a yes/no value, so seven products tie at "under Rs 1000" and eight at "not under". For each
OFFSETMySQL was free to order the tied rows differently: product 15 appeared on pages 1 and 2, and product 8 (the mouse) never appeared. - Adding
product_idgives every row one fixed place, and the five pages show all 15 products exactly once. The string concatenation is safe here only because bothORDER BYtexts are fixed in the code, never user input.
Without ORDER BY, SQL promises no order at all. With ORDER BY on a column that has ties (many products share a category or a price band), MySQL may put the tied rows in a different order for different OFFSETs, so one row appears on two pages while another appears on none. ORDER BY name, product_id gives every row exactly one position, so the pages fit together perfectly.
Fix the error
Fix the paged ORDER BY
Many products share a category. Pick the line that keeps the pages stable.
Replace the highlighted line.
Error
No error, but a product shows on pages 1 and 2 while another one never shows.
Validating page input and the cost of large offsets
Keyset paging asks for the rows after the last one shown, with a condition such as WHERE (name, product_id) > (?, ?), instead of skipping rows with OFFSET.
Page and size come from users, so the service validates them. Example 5 shows a service refusing page 0 and size 1,000,000.
Example 5 · The service validates page and size
import java.util.List;
record Page<T>(List<T> items, int page, int size, long totalItems) {}
interface ProductDao { Page<String> findActive(int page, int size);}
// Records what it was asked, so we can see the SQL valuesclass RecordingProductDao implements ProductDao { String lastCall = "none";
@Override public Page<String> findActive(int page, int size) { lastCall = "LIMIT " + size + " OFFSET " + (page - 1) * size; return new Page<>(List.of(), page, size, 14); }}
class ProductService { static final int MAX_PAGE_SIZE = 50; private final ProductDao dao;
ProductService(ProductDao dao) { this.dao = dao; }
Page<String> listProducts(int page, int size) { if (page < 1) { throw new IllegalArgumentException("Page must be 1 or more"); } if (size < 1 || size > MAX_PAGE_SIZE) { throw new IllegalArgumentException("Page size must be between 1 and " + MAX_PAGE_SIZE); } return dao.findActive(page, size); }}
public class PageInputDemo { public static void main(String[] args) { RecordingProductDao dao = new RecordingProductDao(); ProductService service = new ProductService(dao);
int[][] requests = {{1, 20}, {3, 20}, {0, 20}, {1, 0}, {1, 1000000}}; for (int[] r : requests) { try { service.listProducts(r[0], r[1]); System.out.println("page " + r[0] + ", size " + r[1] + " -> " + dao.lastCall); } catch (IllegalArgumentException e) { System.out.println("page " + r[0] + ", size " + r[1] + " -> refused: " + e.getMessage()); } } }}page 1, size 20 -> LIMIT 20 OFFSET 0 page 3, size 20 -> LIMIT 20 OFFSET 40 page 0, size 20 -> refused: Page must be 1 or more page 1, size 0 -> refused: Page size must be between 1 and 50 page 1, size 1000000 -> refused: Page size must be between 1 and 50
What this code does
- Page 0 would give
OFFSET -20, which MySQL rejects withYou have an error in your SQL syntax ... near '-20'. The service refuses it first with a clear message. - Size 1000000 is refused by the maximum. Without it, one request could load the whole table, which is exactly what paging was meant to stop.
The service accepts page 1 or more, and a size from 1 to a maximum (50 in ShopLite). Without the maximum, a request for size 1000000 is findAll again under another name.
OFFSET is not free: to return page 10,000, MySQL still finds and throws away the 1,99,980 rows before it, so deep pages get slower (Example 1). For "next" buttons and endless scrolling, remember the last row shown and ask for rows after it, WHERE (name, product_id) > (?, ?) ORDER BY name, product_id LIMIT 20. Page numbers stay fine for screens where people rarely go past the first few pages.
Order of execution
Order a paged request
Arrange what happens when the menu asks for a page, from first to last.
Next step
Check your understanding
12 quick questions