← Back to Questions
Spring Boot

What is sorting in Spring Data JPA?

Learn What is sorting in Spring Data JPA? with simple explanations, real-time examples, interview tips and practical use cases.

What is Sorting in Spring Data JPA?

Sorting in Spring Data JPA is a feature used to arrange database records in a specific order such as ascending or descending order.

In simple words:

β€œSorting organizes records based on one or more fields.”

Why Sorting is Needed

Modern applications display large amounts of data such as:

  • Products
  • Students
  • Interview questions
  • Orders
  • Transactions

Without sorting:

  • Records appear randomly
  • User experience becomes poor
  • Finding important data becomes difficult

Sorting improves data organization and readability.


Real-Time Example

E-commerce application may display:

  • Products sorted by price
  • Latest orders first
  • Top-rated products first

Types of Sorting

Spring Data JPA supports:

  • Ascending sorting
  • Descending sorting
  • Multiple field sorting

Ascending Sorting

Arranges records from:

  • Small β†’ Large
  • A β†’ Z

Descending Sorting

Arranges records from:

  • Large β†’ Small
  • Z β†’ A

Entity Example

@Entity
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private Integer marks;
}

What is Sort Class?

Spring Data JPA provides:

Sort

class to perform sorting operations.


Ascending Sort Example

Sort sort =
        Sort.by("name").ascending();

Descending Sort Example

Sort sort =
        Sort.by("marks").descending();

Repository Example

public interface StudentRepository
        extends JpaRepository<Student, Long> {

}

Find All with Sorting

List<Student> students =
        studentRepository.findAll(
                Sort.by("name")
        );

Generated SQL Query

SELECT *
FROM students
ORDER BY name ASC

Descending Order Example

List<Student> students =
        studentRepository.findAll(
                Sort.by("marks")
                        .descending()
        );

Generated SQL

SELECT *
FROM students
ORDER BY marks DESC

Multiple Field Sorting

Spring Data JPA supports sorting by multiple fields.


Example

Sort sort =
        Sort.by("name")
            .ascending()
            .and(
                Sort.by("marks")
                    .descending()
            );

Generated SQL

SELECT *
FROM students
ORDER BY name ASC,
         marks DESC

Sorting with Pagination

Sorting is commonly used with pagination.


Pagination + Sorting Example

Pageable pageable =
        PageRequest.of(
                0,
                10,
                Sort.by("name").ascending()
        );

Page<Student> students =
        studentRepository.findAll(pageable);

Generated SQL

SELECT *
FROM students
ORDER BY name ASC
LIMIT 10 OFFSET 0

Sorting with Custom Query

Sorting can also be applied in JPQL queries.


JPQL Sorting Example

@Query("""
SELECT s
FROM Student s
ORDER BY s.name ASC
""")
List<Student> getStudentsSorted();

Native Query Sorting Example

@Query(
    value = """
        SELECT *
        FROM students
        ORDER BY marks DESC
    """,
    nativeQuery = true
)
List<Student> getStudentsByMarks();

Dynamic Sorting Example

Users can choose sorting dynamically.


Example

public List<Student> getStudents(
        String field
) {

    return studentRepository.findAll(
            Sort.by(field)
    );
}

REST API Example

@GetMapping("/students")
public List<Student> getStudents(

        @RequestParam String sortBy
) {

    return studentRepository.findAll(
            Sort.by(sortBy)
    );
}

API Request Example


GET /students?sortBy=name

Sorting Directions

Spring Data JPA provides:

  • Sort.Direction.ASC
  • Sort.Direction.DESC

Direction Example

Sort.by(
        Sort.Direction.DESC,
        "marks"
)

Case-Insensitive Sorting

Sorting can ignore letter case.


Example

Sort.by("name")
    .ascending()
    .ignoreCase()

Advantages of Sorting

  • Improves user experience
  • Better data organization
  • Easier searching and filtering
  • Useful for reporting
  • Enhances frontend display

Disadvantages of Improper Sorting

  • Slow queries on huge datasets
  • Performance issues without indexing
  • Complex sorting logic

Importance of Database Indexing

Sorting large datasets without indexes can:

  • Reduce database performance
  • Increase query execution time

Indexed Column Example

CREATE INDEX idx_student_name
ON students(name)

Real-Time Example in E-Commerce Application

E-commerce applications may support:

  • Price low to high
  • Newest products first
  • Highest-rated products

Sorting helps users quickly find products.


Real-Time Example in Interview Portal

Interview portals may sort:

  • Latest interview questions
  • Most viewed tutorials
  • Top-ranked courses

Best Practices for Sorting

  • Use sorting with pagination
  • Index frequently sorted columns
  • Avoid sorting huge datasets unnecessarily
  • Use dynamic sorting carefully
  • Validate user-provided sorting fields

Difference Between Sorting and Pagination

Feature Sorting Pagination
Purpose Arrange records Divide records into pages
Main Classes Sort Pageable, Page
Improves Readability Performance

Common Interview Questions on Sorting

What is sorting in Spring Data JPA?

Sorting arranges records in ascending or descending order.

Which class is used for sorting?

Sort class.

How do you sort records in descending order?

Using:

Sort.by("field").descending()

Can sorting be combined with pagination?

Yes.

Why are indexes important for sorting?

They improve sorting performance on large datasets.


Conclusion

Sorting is one of the most important features in Spring Data JPA for organizing and displaying data efficiently.

It helps developers:

  • Improve user experience
  • Display ordered data
  • Enhance search functionality
  • Build scalable enterprise applications

Understanding sorting is essential for Spring Boot developers because almost every enterprise application requires properly organized data display.

Proper use of sorting improves:

  • Database efficiency
  • Frontend usability
  • Application scalability
  • API performance

Why this Spring Boot question is important?

This interview question helps candidates understand real-time backend development concepts, practical problem solving, coding fundamentals, system design basics and production-ready application behavior.

Practice this question carefully for Java backend roles, Spring Boot developer interviews, microservices interviews, company interviews and full-stack developer preparation.

About the Author

Naresh Kumar is a Senior Java Backend Engineer with experience building enterprise applications using Java, Spring Boot, Microservices, Docker, Kubernetes and Cloud technologies.