How do you write a query method for sorting in Spring Data JPA?

Spring Data JPA lets you express sorting directly in a derived query method name using the OrderBy keyword, followed by the entity property to sort on and an optional Asc or Desc suffix, without needing to write any JPQL.

Key Points

Example

A repository method that needs to always return users ordered alphabetically by last name can simply be named findByOrderByLastNameAsc(), and Spring Data JPA generates the correct query automatically.

public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByOrderByLastNameAsc();

    List<User> findByStatusOrderByCreatedAtDesc(String status);
}

Interview Tip

A concise interview answer is

I can bake sorting straight into a derived query method name using OrderBy followed by the property and Asc or Desc, like findByOrderByLastNameAsc(). For sort order that needs to change at runtime based on user input, I'd instead accept a Sort or Pageable parameter rather than hardcoding it in the method name.

Last updated: 11 November 2026

Previous question: What is the @Temporal annotation used for?

Next question: What does the @Transactional annotation do in Spring?

More Spring Data JPA interview questions

All Spring Data JPA questions