Sorting by one or more fields
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A customer opens the product list sorted by price, highest first. If two products cost the same, the database may put them in any order, and the pages cut from that order can repeat or lose rows.
Sort.by("price").descending().and(Sort.by("name"))
Sort is an ordered list of sort orders, each a property name with a direction. It runs before the page is cut, and Spring Data turns Sort.by("price").descending().and(Sort.by("name")) into ORDER BY price desc, name.
A sort is a list of orders: price descending first, then name ascending, which only matters when two prices are equal.
Example 1 · lab/SortDemo.java: two orders, two ways
Runs in: the page-lab practice project (Spring Boot 4.1 with the ShopLite database)
package com.shoplite.lab;
import org.springframework.data.domain.Sort;import org.springframework.stereotype.Component;
import com.shoplite.product.ProductRepository;
@Component("sort")class SortDemo implements LabDemo {
private final ProductRepository products;
SortDemo(ProductRepository products) { this.products = products; }
@Override public void run() { // Most expensive first; equal prices by name A to Z Sort byPrice = Sort.by("price").descending().and(Sort.by("name")); System.out.println(byPrice); products.findAll(byPrice).stream().limit(3) .forEach(p -> System.out.println(" " + p.getPrice() + " " + p.getName()));
// Out of stock first; among equal stock, the most expensive first Sort byStock = Sort.by(Sort.Order.asc("stock"), Sort.Order.desc("price")); System.out.println(byStock); products.findAll(byStock).stream().limit(3) .forEach(p -> System.out.println(" " + p.getStock() + " " + p.getPrice() + " " + p.getName())); }}$ java -jar target/page-lab-0.1.0.jar --demo=sort price: DESC,name: ASC DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 order by p1_0.price desc,p1_0.name 69900.00 iPhone 15 128GB 64990.00 HP Victus 15 Gaming 42990.00 Lenovo IdeaPad Slim 3 stock: ASC,price: DESC DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 order by p1_0.stock,p1_0.price desc 0 849.00 Logitech M331 Silent Mouse 0 199.00 USB-C Cable 1m 5 64990.00 HP Victus 15 Gaming
What this code does
Sort.toString()shows the orders:price: DESC,name: ASC. The SQL getsorder by p1_0.price desc,p1_0.name(ascending is MySQL's default, so noascis printed).Sort.Order.asc("stock")andSort.Order.desc("price")build the same kind of sort from a list of orders.- Both products with stock 0 come first; between them the higher price (849.00) wins, which is the second order at work.
The names are entity property names (price, fullName, createdAt), not column names (full_name, created_at); Spring Data maps them through your @Column mappings. For several orders at once, Sort.by(Sort.Order.asc("stock"), Sort.Order.desc("price")) reads well.
Be careful with .descending() on a combined sort: Sort.by("price").and(Sort.by("name")).descending() flips both orders, so name becomes descending too.
Type-safe sorting with Sort.sort(Product.class).by(...)
TypedSort is a sort built from getters instead of strings: Sort.sort(Product.class).by(Product::getName). A typo such as Product::getNmae is a compile error, and renaming the field in the IDE renames the sort too.
Give the sort a getter reference instead of a string, so the Java compiler checks the property name.
Example 2 · lab/TypedSortDemo.java: typed sorts on String, int and BigDecimal
Runs in: the page-lab practice project (Spring Boot 4.1 with the ShopLite database)
package com.shoplite.lab;
import org.springframework.data.domain.Sort;import org.springframework.stereotype.Component;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Component("typedsort")class TypedSortDemo implements LabDemo {
private final ProductRepository products;
TypedSortDemo(ProductRepository products) { this.products = products; }
@Override public void run() { Sort byName = Sort.sort(Product.class).by(Product::getName).ascending(); System.out.println(byName + " -> " + products.findAll(byName).get(0).getName());
Sort byStock = Sort.sort(Product.class).by(Product::getStock).descending(); System.out.println(byStock + " -> " + products.findAll(byStock).get(0).getName());
try { Sort byPrice = Sort.sort(Product.class).by(Product::getPrice).descending(); System.out.println(byPrice); } catch (RuntimeException e) { System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage()); } }}$ java -jar target/page-lab-0.1.0.jar --demo=typedsort DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 order by p1_0.name name: ASC -> Atomic Habits DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 order by p1_0.stock desc stock: DESC -> boAt Airdopes 141 AopConfigException: Could not generate CGLIB subclass of class java.math.BigDecimal: Common causes of this problem include using a final class or a non-visible class
What this code does
by(Product::getName)becomes the propertyname, andby(Product::getStock)becomesstock: both run and give the expected first product.by(Product::getPrice)throwsAopConfigException: the recorder cannot subclass the final classBigDecimal. UseSort.by("price")for such properties.- The SQL line prints before the result line because
findAllruns while the string is being built.
A typed sort works by recording which getter you called on a proxy object. In Spring Data Commons 4.1.1 that works for String and primitive properties, but for a BigDecimal property such as Product::getPrice it fails at runtime: the recorder tries to create a subclass of the return type, and BigDecimal is a final class. Example 2 shows the real exception.
So use typed sorts where they work and plain names elsewhere. Either way, the property list a client may use still needs an allow-list, as the last section shows.
Sorting inside a Pageable, and a unique tiebreaker (id)
A tiebreaker is a last sort order on a unique column, usually id, so that no two rows are ever equal for the sort. It keeps the order, and so the pages, the same on every request.
PageRequest.of(page, size, sort) carries the sort with the page, and the sort runs before LIMIT cuts the page. Put id last.
Example 3 · Equal sort values without and with a tiebreaker (MySQL)
Runs in: MySQL 8.4 (a scratch database named practice)
mysql -u root -p -B practice -e "SET cte_max_recursion_depth = 5000;CREATE TABLE test_orders (id INT AUTO_INCREMENT PRIMARY KEY, status VARCHAR(10), note VARCHAR(200));INSERT INTO test_orders (status, note) WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 3000) SELECT ELT(1 + i % 3, 'PLACED', 'SHIPPED', 'DELIVERED'), REPEAT('x', 100) FROM n;SELECT GROUP_CONCAT(id) AS page_0 FROM (SELECT id FROM test_orders ORDER BY status LIMIT 10) p;SELECT GROUP_CONCAT(id) AS page_1 FROM (SELECT id FROM test_orders ORDER BY status LIMIT 10 OFFSET 10) p;SELECT GROUP_CONCAT(id) AS page_0 FROM (SELECT id FROM test_orders ORDER BY status, id LIMIT 10) p;SELECT GROUP_CONCAT(id) AS page_1 FROM (SELECT id FROM test_orders ORDER BY status, id LIMIT 10 OFFSET 10) p;"Enter password: page_0 26,2,29,17,5,14,8,20,23,11 page_1 56,26,14,59,38,17,44,23,20,47 page_0 2,5,8,11,14,17,20,23,26,29 page_1 32,35,38,41,44,47,50,53,56,59
What this code does
- 3000 orders, 1000 per status. Sorted only by
status, page 0 and page 1 both contain orders 26, 14, 17, 20 and 23, and orders such as 32 and 35 appear on neither page. - With
ORDER BY status, idevery row has one fixed place: page 0 holds ids 2 to 29 and page 1 continues with 32 to 59, no overlap. - Your ids may differ with another MySQL version or settings; the overlap without a tiebreaker is the point. Run it in a scratch
practicedatabase (CREATE DATABASE practice).
Example 4 · lab/StablePagesDemo.java: a sort with id inside a PageRequest
Runs in: the page-lab practice project (Spring Boot 4.1 with the ShopLite database)
package com.shoplite.lab;
import org.springframework.data.domain.Page;import org.springframework.data.domain.PageRequest;import org.springframework.data.domain.Sort;import org.springframework.stereotype.Component;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Component("stablepages")class StablePagesDemo implements LabDemo {
private final ProductRepository products;
StablePagesDemo(ProductRepository products) { this.products = products; }
@Override public void run() { // Low stock first; id breaks ties, so every row has exactly one place Sort lowStockFirst = Sort.by("stock").and(Sort.by("id")); for (int page = 0; page < 2; page++) { Page<Product> p = products.findByActiveTrue(PageRequest.of(page, 3, lowStockFirst)); System.out.println("Page " + page + ": " + p.getContent().stream() .map(x -> "#" + x.getId() + " (stock " + x.getStock() + ")").toList()); } // A shortcut: one direction for several properties System.out.println(PageRequest.of(0, 3, Sort.Direction.DESC, "price", "id")); }}$ java -jar target/page-lab-0.1.0.jar --demo=stablepages DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.is_active=true order by p1_0.stock,p1_0.product_id limit ? DEBUG org.hibernate.SQL : select count(p1_0.product_id) from products p1_0 where p1_0.is_active=true Page 0: [#8 (stock 0), #5 (stock 5), #3 (stock 8)] DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.is_active=true order by p1_0.stock,p1_0.product_id limit ?,? DEBUG org.hibernate.SQL : select count(p1_0.product_id) from products p1_0 where p1_0.is_active=true Page 1: [#4 (stock 12), #14 (stock 15), #13 (stock 18)] Page request [number: 0, size 3, sort: price: DESC,id: DESC]
What this code does
- The SQL ends with
order by p1_0.stock,p1_0.product_id: low stock first, and the id decides between equal stock values. - Page 1 continues exactly after page 0:
#8, #5, #3, then#4, #14, #13. PageRequest.of(0, 3, Sort.Direction.DESC, "price", "id")applies one direction to every property: hereidis descending too, which is still a valid tiebreaker.
Without a tiebreaker, rows with equal values may come back in any order, and MySQL may choose a different order for LIMIT 10 than for LIMIT 10 OFFSET 10. Example 3 shows it on a table of 3000 orders: page 0 and page 1 share 5 orders, and 5 other orders are on no page at all. The ShopLite contract therefore says "ties are broken by id ascending, so pages never overlap".
The fix is cheap: Sort.by("stock").and(Sort.by("id")). Add id after every sort field except id itself.
Find the bug
Find the sort bug
Tap the wrong line, then check the fix.
Pages of products sorted by stock must never overlap.
Round 1 of 3Untrusted sort fields and a whitelist
An allow-list (also called a whitelist) is the fixed set of sort fields a list endpoint accepts. Every other name is rejected with a clear 400 before it reaches Sort.by(...).
Map each API sort name to one entity property, in one place, and reject everything else.
Example 5 · src/main/java/com/shoplite/product/ProductSorts.java: the allow-list
Runs in: the page-lab practice project (Spring Boot 4.1 with the ShopLite database)
package com.shoplite.product;
import java.util.Map;
import org.springframework.data.domain.Sort;
/** The only sort fields the product list accepts, mapped to entity properties. */public final class ProductSorts {
private static final Map<String, String> ALLOWED = Map.of( "id", "id", "name", "name", "price", "price", "stock", "stock");
private ProductSorts() { }
/** "price" or "price,desc" -> a Sort with id as the tiebreaker. Anything else -> IllegalArgumentException. */ public static Sort parse(String text) { String[] parts = text.split(","); String property = ALLOWED.get(parts[0]); boolean validDirection = parts.length == 1 || (parts.length == 2 && (parts[1].equals("asc") || parts[1].equals("desc"))); if (property == null || !validDirection) { throw new IllegalArgumentException("sort must be one of id, name, price, stock"); } Sort.Direction direction = parts.length == 2 && parts[1].equals("desc") ? Sort.Direction.DESC : Sort.Direction.ASC; Sort sort = Sort.by(direction, property); return property.equals("id") ? sort : sort.and(Sort.by("id")); }}(no output: Example 6 uses it)
What this code does
ALLOWEDmaps the API field name to the entity property. Only these four can reach theORDER BY.- The direction must be missing,
ascordesc; anything else is rejected with the same message the contract uses for 400 validation-failed. - Every sort except
idgetsidadded as the tiebreaker, so callers cannot forget it.
Example 6 · lab/UntrustedSortDemo.java: raw client text vs the allow-list
Runs in: the page-lab practice project (Spring Boot 4.1 with the ShopLite database)
package com.shoplite.lab;
import java.util.List;
import org.springframework.data.domain.PageRequest;import org.springframework.data.domain.Sort;import org.springframework.stereotype.Component;
import com.shoplite.product.ProductRepository;import com.shoplite.product.ProductSorts;
@Component("badsort")class UntrustedSortDemo implements LabDemo {
private final ProductRepository products;
UntrustedSortDemo(ProductRepository products) { this.products = products; }
@Override public void run() { // 1. The client's text goes straight into Sort.by: the query fails at runtime try { products.findByActiveTrue(PageRequest.of(0, 5, Sort.by("cost"))); } catch (RuntimeException e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); }
// 2. The allow-list decides first for (String text : List.of("price,desc", "name", "cost", "price,sideways")) { try { System.out.println(text + " -> " + ProductSorts.parse(text)); } catch (IllegalArgumentException e) { System.out.println(text + " -> 400: " + e.getMessage()); } } }}$ java -jar target/page-lab-0.1.0.jar --demo=badsort org.springframework.data.core.PropertyReferenceException: No property 'cost' found for type 'Product' price,desc -> price: DESC,id: ASC name -> name: ASC,id: ASC cost -> 400: sort must be one of id, name, price, stock price,sideways -> 400: sort must be one of id, name, price, stock
What this code does
Sort.by("cost")fails before any SQL is sent:PropertyReferenceException: No property 'cost' found for type 'Product'. In a controller that is a 500 unless you handle it.- Through
ProductSorts.parse, valid text becomes aSortwith theidtiebreaker, andcostorprice,sidewaysbecome a clear 400 message. - With a
@Querymethod the same mistake fails a little later, inside Hibernate:Could not resolve attribute 'cost' of 'com.shoplite.product.Product'.
Without an allow-list, the client's text goes straight into Sort.by(...). A typo or a guess such as cost fails inside the query with No property 'cost' found for type 'Product', which a default Spring Boot app answers with 500, not 400. Spring Data does refuse SQL in a sort (price; drop table products is rejected unless you use JpaSort.unsafe), but a client could still sort by any property, including ones that have no index and make the database sort millions of rows.
The same place adds the id tiebreaker, and the API name can stay the same even when you rename the entity field.
Next step
Check your understanding
11 quick questions