Bird
Raised Fist0
Spring Bootframework~10 mins

Pagination and sorting with Pageable in Spring Boot - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Pagination and sorting with Pageable
Client sends request with page, size, sort
Controller receives Pageable object
Repository queries DB with Pageable
DB returns page of sorted data
Controller returns Page<T> response
Client receives paged, sorted data
The client sends paging and sorting info, the controller uses Pageable to query the database, and returns a page of sorted data.
Execution Sample
Spring Boot
Pageable pageable = PageRequest.of(0, 5, Sort.by("name"));
Page<User> page = userRepository.findAll(pageable);
List<User> users = page.getContent();
This code requests the first page with 5 users sorted by name, then gets the list of users from the page.
Execution Table
StepActionPage NumberPage SizeSort FieldSort DirectionResult
1Create Pageable with page=0, size=5, sort by name ascending05nameASCPageable object ready
2Call repository findAll with Pageable05nameASCQuery DB for first 5 users sorted by name
3DB returns users sorted by name, limited to 505nameASCPage<User> with 5 users
4Extract content list from Page<User>05nameASCList<User> with 5 users
5Client receives paged, sorted user list05nameASCUsers displayed in sorted order
💡 Completed fetching first page of 5 users sorted by name ascending
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
pageablenullPageRequest(page=0, size=5, sort=name ASC)SameSameSameSame
pagenullnullPage<User> with 5 sorted usersSameSameSame
usersnullnullnullnullList<User> with 5 usersSame
Key Moments - 3 Insights
Why does the page number start at 0 instead of 1?
Page numbers in Pageable are zero-based, so page=0 means the first page. See execution_table step 1 where page=0 is set.
How does sorting work with Pageable?
Sorting is part of the Pageable object. In step 1, Sort.by("name") sets sorting by the 'name' field ascending, which the repository uses in the DB query (step 2).
What if the requested page has fewer items than the page size?
The Page object will contain only the available items. For example, if only 3 users remain, the page content list will have 3 users instead of 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the page size after step 2?
A5
B0
C10
DUndefined
💡 Hint
Check the 'Page Size' column in execution_table row for step 2
At which step does the database return the sorted user data?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look for the step describing DB returning data in execution_table
If we change Sort.by("name") to Sort.by("age").descending(), what changes in the execution_table?
ASort Field changes to 'age' and Sort Direction to 'DESC'
BPage Number changes to 1
CPage Size changes to 10
DNo changes
💡 Hint
Look at the 'Sort Field' and 'Sort Direction' columns in execution_table step 1
Concept Snapshot
Pagination and sorting with Pageable in Spring Boot:
- Use PageRequest.of(page, size, Sort) to create Pageable
- Page numbers start at 0 (first page)
- Sort can be ascending or descending by any field
- Repository returns Page<T> with content and metadata
- Extract list with page.getContent() for display
Full Transcript
In Spring Boot, pagination and sorting are handled by the Pageable interface. The client sends parameters for page number, page size, and sorting. The controller creates a Pageable object using PageRequest.of, specifying the page index (starting at 0), the number of items per page, and the sorting field and direction. This Pageable is passed to the repository's findAll method, which queries the database accordingly. The database returns a Page object containing the requested slice of data sorted as specified. The controller extracts the list of items from the Page and returns it to the client. This process allows efficient loading of large datasets in manageable chunks with sorting applied.

Practice

(1/5)
1. What is the main purpose of using Pageable in Spring Boot?
easy
A. To fetch data in small chunks with optional sorting
B. To connect to the database directly
C. To write SQL queries manually
D. To handle user authentication

Solution

  1. Step 1: Understand Pageable's role

    Pageable is used to request data in pages, not all at once.
  2. Step 2: Recognize sorting feature

    It also supports sorting data by fields while fetching pages.
  3. Final Answer:

    To fetch data in small chunks with optional sorting -> Option A
  4. Quick Check:

    Pageable = Pagination + Sorting [OK]
Hint: Pageable means small pages + sorting [OK]
Common Mistakes:
  • Thinking Pageable connects to database
  • Confusing Pageable with authentication
  • Assuming Pageable writes SQL queries
2. Which of the following is the correct way to create a Pageable object for page 2, size 5, sorted by "name" ascending?
easy
A. PageRequest.of(1, 5, Sort.by("name"))
B. PageRequest.of(2, 5, Sort.asc("name"))
C. PageRequest.of(2, 5, Sort.by("name"))
D. PageRequest.create(2, 5, Sort.by("name"))

Solution

  1. Step 1: Understand zero-based page index

    Page numbers start at 0, so page 2 means index 1.
  2. Step 2: Check method and sorting syntax

    Use PageRequest.of(page, size, Sort.by("field")) for ascending sort.
  3. Final Answer:

    PageRequest.of(1, 5, Sort.by("name")) -> Option A
  4. Quick Check:

    Page index zero-based + Sort.by correct [OK]
Hint: Page index starts at 0, so page 2 is index 1 [OK]
Common Mistakes:
  • Using page number directly instead of zero-based index
  • Using non-existent methods like Sort.asc
  • Using PageRequest.create instead of PageRequest.of
3. Given this repository method call:
repository.findAll(PageRequest.of(0, 3, Sort.by("age")))
What will be the result?
medium
A. Error because Sort direction is missing
B. First 3 records sorted by age descending
C. All records without sorting
D. First 3 records sorted by age ascending

Solution

  1. Step 1: Analyze PageRequest parameters

    Page 0 means first page, size 3 means 3 records, Sort.by("age") defaults to ascending.
  2. Step 2: Understand repository behavior

    findAll with Pageable returns that page of sorted data.
  3. Final Answer:

    First 3 records sorted by age ascending -> Option D
  4. Quick Check:

    Page 0 + size 3 + ascending sort = first 3 sorted [OK]
Hint: Sort.by defaults to ascending if direction not set [OK]
Common Mistakes:
  • Assuming descending sort without direction
  • Thinking all records are returned
  • Expecting error due to missing direction
4. What is wrong with this code snippet?
Pageable pageable = PageRequest.of(1, 10, Sort.asc("date"));
medium
A. Page index should start at 0, not 1
B. Sort.asc() method does not exist
C. Page size cannot be 10
D. PageRequest.of requires 4 parameters

Solution

  1. Step 1: Check Sort method usage

    Spring Data uses Sort.by(), not Sort.asc().
  2. Step 2: Verify other parameters

    Page index 1 and size 10 are valid; PageRequest.of takes 3 parameters here.
  3. Final Answer:

    Sort.asc() method does not exist -> Option B
  4. Quick Check:

    Use Sort.by() for sorting [OK]
Hint: Use Sort.by(), not Sort.asc() [OK]
Common Mistakes:
  • Using Sort.asc() or Sort.desc() which don't exist
  • Thinking page index must be 0 always
  • Believing PageRequest.of needs 4 parameters
5. You want to fetch the third page of size 4, sorted by "price" descending and then by "name" ascending. Which Pageable creation is correct?
hard
A. PageRequest.of(2, 4, Sort.by("price", "name"))
B. PageRequest.of(3, 4, Sort.by("price").descending().and(Sort.by("name")))
C. PageRequest.of(2, 4, Sort.by(Sort.Order.desc("price"), Sort.Order.asc("name")))
D. PageRequest.of(2, 4, Sort.by("price").desc().and(Sort.by("name").asc()))

Solution

  1. Step 1: Identify zero-based page index

    Third page means index 2 (0,1,2).
  2. Step 2: Create Sort with multiple orders

    Use Sort.by(Order.desc("price"), Order.asc("name")) to combine sorting directions.
  3. Step 3: Check syntax correctness

    PageRequest.of(2, 4, Sort.by(Sort.Order.desc("price"), Sort.Order.asc("name"))) uses correct PageRequest.of and Sort.by with orders.
  4. Final Answer:

    PageRequest.of(2, 4, Sort.by(Sort.Order.desc("price"), Sort.Order.asc("name"))) -> Option C
  5. Quick Check:

    Page 2 + size 4 + multi-sort orders correct [OK]
Hint: Use Sort.Order for multi-direction sorting [OK]
Common Mistakes:
  • Using page number 3 instead of index 2
  • Trying to chain .desc() or .asc() methods that don't exist
  • Passing multiple fields without specifying order