Spring Boot Pagination and Sorting Tutorial
Introduction
When applications contain thousands or even millions of records, loading all data in a single request can slow down your application and consume unnecessary memory. Pagination and sorting solve this problem by returning only the data users need while presenting it in an organized order.
Spring Data JPA provides built-in support for pagination and sorting, making it easy to build scalable REST APIs with minimal code.
In this tutorial, you'll learn how to implement pagination and sorting using Spring Boot and Spring Data JPA with practical examples.
What is Pagination?
Pagination divides a large dataset into smaller pages.
Instead of returning 10,000 records, the API might return:
- Page 1 → Records 1–10
- Page 2 → Records 11–20
- Page 3 → Records 21–30
This improves:
- Performance
- User experience
- Memory usage
- API response time
What is Sorting?
Sorting arranges records in a specific order.
Examples:
- Name (A–Z)
- Name (Z–A)
- Salary (Low to High)
- Created Date (Newest First)
Sorting helps users find information quickly.
How Pagination Works
Client Request ↓ ?page=0&size=10 ↓ Controller ↓ Service ↓ Repository ↓ Database ↓ 10 Records Returned
Add Maven Dependency
If you're already using Spring Data JPA, you likely have the required dependency.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
Employee Entity
@Entity public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String department; private Double salary; }
Repository
Extend JpaRepository.
@Repository public interface EmployeeRepository extends JpaRepository<Employee, Long> { }
JpaRepository already supports pagination and sorting.
Pageable Interface
Spring uses the Pageable interface to describe page number, page size, and sorting.
Example:
Pageable pageable = PageRequest.of(0,5);
This retrieves:
- First page
- Five records
Service Layer
public Page<Employee> getEmployees( int page, int size){ Pageable pageable = PageRequest.of(page,size); return repository.findAll(pageable); }
Controller Layer
@GetMapping("/employees") public Page<Employee> getEmployees( @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "10") int size){ return service.getEmployees(page,size); }
Test Using Browser
http://localhost:8080/employees?page=0&size=10
Second page:
http://localhost:8080/employees?page=1&size=10
Page Response
{ "content":[ { "id":1, "name":"Muhammad Zeeshan" } ], "totalElements":120, "totalPages":12, "size":10, "number":0 }
Sorting Records
Ascending order:
Sort.by("name")
Descending order:
Sort.by( Sort.Direction.DESC, "name")
Pagination with Sorting
Pageable pageable = PageRequest.of( 0, 10, Sort.by("salary") .descending());
This returns:
- First page
- 10 employees
- Highest salary first
Multiple Sorting Fields
Sort.by("department") .and(Sort.by("salary") .descending())
Example:
- Department A
- Highest salary first
Searching with Pagination
Repository:
Page<Employee> findByDepartment( String department, Pageable pageable);
Now users can filter and paginate simultaneously.
Common URL Examples
First page:
?page=0&size=10
Second page:
?page=1&size=10
Sort by name:
?page=0&size=10&sort=name
Descending:
?page=0&size=10&sort=name,desc
Best Practices
Choose a reasonable page size
Most APIs use 10–50 records per page.
Never return all records
Avoid loading very large datasets in one request.
Validate page parameters
Reject negative page numbers or invalid sizes.
Index frequently sorted columns
Database indexes improve query performance.
Combine filtering with pagination
Filtering large datasets before pagination improves efficiency.
Common Mistakes
Very large page sizes
Returning thousands of records can hurt performance.
Forgetting sorting
Without sorting, the order of results may not be predictable.
Using one-based page numbering
Spring Data JPA uses zero-based page numbering.
Interview Questions
What is Pageable?
An interface that describes page number, page size, and sorting information.
What is Page?
A Page contains the requested data and metadata such as total pages and total elements.
What is Sort?
A Spring Data class used to define the order of query results.
Can pagination improve performance?
Yes. It reduces memory usage and database load by returning smaller result sets.
FAQ
Does JpaRepository support pagination?
Yes. It includes built-in pagination and sorting support.
What is the default page number?
Page numbering starts at 0.
Can I sort by multiple fields?
Yes. Spring Data JPA supports multi-column sorting.
