- Chapter
- Chapter 2 — Query Methods
- Prerequisites
- Chapter 1
- You will be able to
- Write derived query methods with correct subjects, conditions, operators, ordering, limits and return types, and recognise when to switch to declared queries
- Covers
- Method Naming · Conditions · Operators
On this page
- 1. Concept / Definition
- 2. Why It Exists
- 3. Core Concepts
- 4. How It Works Internally
- 4A. Deep Dive — Return Types and Their Semantics
- 5. APIs / Features / Syntax
- 6. Practical Examples
- 7. Common Problems & Mistakes
- 8. Performance & Production Considerations
- 9. Architecture & Design Considerations
- 10. Interview Questions & Answers
1Concept / Definition
A derived query is a repository method whose query is generated from its name. Spring Data parses the name into a subject (what to do: find, count, exists, delete) and a predicate (conditions on entity properties combined with operators), then builds a JPA Criteria query.

public interface OrderRepository extends ListCrudRepository<Order, UUID> {
List<Order> findByCustomerIdAndStatusOrderByCreatedAtDesc(String customerId,
OrderStatus status);
Optional<Order> findFirstByCustomerIdOrderByCreatedAtDesc(String customerId);
long countByStatus(OrderStatus status);
boolean existsByExternalReference(String reference);
List<Order> findTop10ByTotalGreaterThanOrderByTotalDesc(BigDecimal min);
}2Why It Exists
Simple lookups — by id, by email, by status and customer — make up a large share of data access code. Writing JPQL for each is repetitive and error-prone. Derived queries let the method signature serve as the query definition, validated at start-up against the entity model, so typos in property names fail fast rather than at runtime.
3Core Concepts
3.1 Method naming

| Part | Syntax | Example |
|---|---|---|
| Subject | find…By, read…By, get…By, query…By, search…By, stream…By | findByEmail |
| Count / exists | count…By, exists…By | countByStatus, existsByEmail |
| Delete | delete…By, remove…By | deleteByCreatedAtBefore (loads then deletes) |
| Distinct | findDistinct…By | findDistinctCityBy… |
| Limiting | First, Top, TopN, FirstN | findTop5By…, findFirstBy… |
| Property paths | Nested with camel case or _ | findByCustomer_Address_City |
| Ordering | OrderBy<Property>Asc/Desc | OrderByCreatedAtDesc |
3.2 Conditions
Conditions reference entity properties (not columns) and are combined with And / Or. Parameters bind in declaration order:
List<Customer> findByLastNameAndCityOrEmail(String lastName, String city, String email);
// where (lastName = ?1 and city = ?2) or email = ?3 — And binds tighter than Or| Special parameter | Effect |
|---|---|
Pageable | Paging + sorting; return Page, Slice or List |
Sort | Dynamic ordering |
Limit (Spring Data 3.2+) | Dynamic maximum results |
ScrollPosition | Keyset/offset scrolling; return Window |

3.3 Operators

| Keyword | JPQL | Example |
|---|---|---|
Is, Equals (implicit) | = ? | findByStatus |
Not | <> ? | findByStatusNot |
LessThan, LessThanEqual, GreaterThan, GreaterThanEqual | <, <=, >, >= | findByTotalGreaterThan |
Between | between ? and ? | findByCreatedAtBetween |
Before, After | <, > (temporal) | findByCreatedAtAfter |
IsNull, IsNotNull | is null | findByShippedAtIsNull |
Like, NotLike | like ? (caller supplies %) | findByNameLike |
StartingWith, EndingWith, Containing | like ?%, %?, %?% | findByNameContaining |
In, NotIn | in (?) | findByStatusIn(Collection) |
True, False | = true/false | findByActiveTrue |
IgnoreCase, AllIgnoreCase | upper(x) = upper(?) | findByEmailIgnoreCase |
4How It Works Internally
1. At repository creation, PartTreeJpaQuery is created for each derived method; PartTree splits the name into subject and an OrPart of AndParts, each Part holding a property path and a type (keyword).
2. Property paths are resolved against the entity metamodel (PropertyPath), trying nested traversal when camel-case is ambiguous (_ forces a split). Unknown properties → start-up failure.
3. At invocation, JpaQueryCreator builds a Criteria query: predicates from parts, order by from the name and Sort, joins for nested paths (inner joins by default), limits from First/Top/Limit/Pageable.
4. Parameters are bound (with like wildcards added for Containing etc.); the result is converted to the declared return type (entity, Optional, List, Stream, Page, projection).
5. For Page results, a derived count query is executed as well.
4ADeep Dive — Return Types and Their Semantics
| Return type | Behaviour | Note |
|---|---|---|
T / Optional<T> | Single result; IncorrectResultSizeDataAccessException if more than one | Use First if several may match |
List<T>, Set<T> | All matches | Bound with limits/paging |
Stream<T> | Streams results lazily | Needs an open transaction; close the stream (try-with-resources) |
Page<T> | Content + count query | Extra query cost |
Slice<T> | Content + hasNext (fetches size + 1) | No count |
Window<T> | Scrolling result with positions | With ScrollPosition |
long, boolean | Count / exists | Efficient queries |
| Projection types | Interface/DTO/Class<T> dynamic | Topic 2.4 |
@Transactional(readOnly = true)
public void exportOpenOrders(Consumer<Order> sink) {
try (Stream<Order> orders = orderRepository.streamByStatus(OrderStatus.OPEN)) {
orders.forEach(o -> {
sink.accept(o);
entityManager.detach(o); // keep the persistence context small
});
}
}5APIs / Features / Syntax
| Element | Examples |
|---|---|
| Subjects | find, read, get, query, search, stream, count, exists, delete, remove |
| Modifiers | Distinct, First, Top<N>, IgnoreCase, AllIgnoreCase, OrderBy…Asc/Desc |
| Operators | And, Or, Between, LessThan, GreaterThan, Like, Containing, In, IsNull, True, Before, After, Not… |
| Special parameters | Pageable, Sort, Limit, ScrollPosition |
| Return types | Optional, List, Stream, Page, Slice, Window, projections |
6Practical Examples
6.1 Property path traversal
// Order → customer (ManyToOne) → address (Embedded) → city
List<Order> findByCustomer_Address_City(String city); // '_' disambiguates the path6.2 Dynamic limit and sort
List<Order> findByStatus(OrderStatus status, Sort sort, Limit limit);
orderRepository.findByStatus(OrderStatus.OPEN,
Sort.by("createdAt").descending(), Limit.of(50));6.3 Generated SQL (Hibernate)
-- findTop10ByTotalGreaterThanOrderByTotalDesc(100)
select o1_0.id, o1_0.customer_id, o1_0.status, o1_0.total, o1_0.created_at
from orders o1_0
where o1_0.total > ?
order by o1_0.total desc
fetch first ? rows only6.4 When the name gets too long
// Hard to read and maintain:
List<Order>
findByCustomerIdAndStatusInAndCreatedAtBetweenAndTotalGreaterThanOrderByCreatedAtDesc(
String customerId, Collection<OrderStatus> statuses,
Instant from, Instant to, BigDecimal min);
// Better: explicit query with named parameters (Topic 2.2) or a Specification (Topic 2.3)6.5 Derived queries for scrolling
Window<Order> findFirst50ByStatusOrderByCreatedAtAscIdAsc(OrderStatus status,
ScrollPosition position);
var window = repo.findFirst50ByStatusOrderByCreatedAtAscIdAsc(OPEN,
ScrollPosition.keyset());
while (!window.isEmpty()) {
window.forEach(this::process);
if (!window.hasNext()) break;
var next = window.positionAt(window.size() - 1);
window = repo.findFirst50ByStatusOrderByCreatedAtAscIdAsc(OPEN, next);
}Keyset scrolling avoids growing offsets when processing large sets in batches (Chapter 4).
6.6 Wrapping derived queries in domain language
public interface OrderRepository extends ListCrudRepository<Order, UUID> {
List<Order> findByStatusAndDueAtBefore(OrderStatus status, Instant instant);
default List<Order> findOverdue(Clock clock) { // domain name for callers
return findByStatusAndDueAtBefore(OrderStatus.AWAITING_PAYMENT,
Instant.now(clock));
}
}6.7 Keyword cheat sheet with generated predicates
| Method | Predicate |
|---|---|
findByEmailIgnoreCase(e) | upper(email) = upper(?) |
findByTagsContaining(t) (collection) | ? member of tags |
findByNameStartingWith(p) | name like 'p%' (index-friendly) |
findByDeletedFalse() | deleted = false |
findByCreatedAtBetween(a, b) | created_at between ? and ? |
findDistinctByLinesSku(s) | distinct … join lines l where l.sku = ? |
6.8 Testing derived queries against the real database
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Testcontainers
class OrderRepositoryTest {
@Container @ServiceConnection
static PostgreSQLContainer<?> db = new PostgreSQLContainer<>("postgres:17");
@Autowired OrderRepository repo;
@Test
void findsTopOrders() {
repo.saveAll(List.of(order("100"), order("250"), order("50")));
assertThat(repo.findTop10ByTotalGreaterThanOrderByTotalDesc(new BigDecimal("60")))
.extracting(Order::getTotal)
.containsExactly(new BigDecimal("250.00"), new BigDecimal("100.00"));
}
}7Common Problems & Mistakes
- Very long method names encoding complex logic.
- Single-result methods returning several rows (
IncorrectResultSizeDataAccessException). - Like without wildcards — behaves as equality.
- Containing on large text columns — leading
%prevents index use. - Derived deletes on large sets.
- Streams outside transactions or not closed.
Each of these problems has a recognisable symptom. Long names are a maintenance problem first: they hide precedence, because And always binds tighter than Or and there are no parentheses, and every new filter forces a new method. A findBy or Optional method that suddenly returns two rows fails with IncorrectResultSizeDataAccessException in production, typically after data that was assumed unique stops being so; use First or a unique constraint. Like passes the argument through untouched, so findByNameLike("smith") matches only exact values, while Containing adds wildcards on both sides and turns an indexed lookup into a full scan on large tables. Derived deletes read every matching entity into the persistence context before removing it, and Stream results hold a database cursor and connection open, so they must run inside a transaction and be closed with try-with-resources.
8Performance & Production Considerations
| Concern | Guidance |
|---|---|
| Indexes | Every frequently used derived query needs an index on its condition/order columns |
| Joins | Nested paths create inner joins — check SQL for unexpected joins |
| Counts | Prefer Slice/exists…By over Page/count…By when totals aren't needed |
| Case-insensitive search | IgnoreCase wraps columns in upper() — needs function-based index or case-insensitive collation |
| Entity loading | Return projections for read-only use (Topic 2.4) |
9Architecture & Design Considerations
- Derived queries for simple finders only; team convention on maximum complexity.
- Method names as domain language (
findActiveByCustomer…) — or wrap in default methods with domain names. - Review generated SQL in tests for important queries.
- Keep repositories cohesive — many special-purpose finders may indicate a missing query service.
10Interview Questions & Answers
What is a derived query in Spring Data?
A derived query is a repository method whose query Spring Data generates from the method name, so the signature is the query definition. When the repository is created, the name is split into a subject, such as find, count, exists or delete, and a predicate made of conditions on entity properties joined with And and Or, plus modifiers such as Distinct, Top10, IgnoreCase and OrderBy. For example, findByCustomerIdAndStatusOrderByCreatedAtDesc becomes a query filtering on two properties and sorting by creation time, with parameters bound in declaration order. Property names are validated against the entity model at start-up, so typos fail fast. Derived queries suit short, stable finders; complex ones belong in @Query or Specifications.
How do you limit the number of results?
There are three ways, chosen by whether the limit is fixed or dynamic. A fixed limit goes in the method name with First or Top, optionally with a number: findFirstByCustomerIdOrderByCreatedAtDesc returns one row and findTop10ByTotalGreaterThanOrderByTotalDesc returns ten, translated into fetch first rows only in SQL. A dynamic maximum uses a Limit parameter, available since Spring Data 3.2, for example findByStatus(status, sort, Limit.of(50)). For pages, pass a Pageable and return Page, Slice or List; Page also runs a count query, while Slice fetches one extra row to know whether more exist. Always combine a limit with an explicit OrderBy or Sort, otherwise which rows you get is undefined.
How are And and Or combined?
And binds tighter than Or, so the predicate is a disjunction of conjunctions. findByLastNameAndCityOrEmail means (lastName = ?1 and city = ?2) or email = ?3, with parameters bound in declaration order. Internally the PartTree holds an OrPart made of AndParts, which is exactly that shape. There are no parentheses in method names, so a condition such as status = ? and (city = ? or email = ?) cannot be written directly; you would have to repeat the common condition, as in findByStatusAndCityOrStatusAndEmail, passing status twice. That is legal but already hard to read, and it is the point at which a @Query with named parameters or a Specification is the better choice.
What happens if a derived method references a non-existent property?
The repository cannot be created, so the application fails at start-up. When Spring Data builds the PartTree for the method, it resolves each property path against the entity's metamodel; an unknown name throws PropertyReferenceException, for example No property 'statu' found for type 'Order', wrapped in a QueryCreationException naming the method. Two nuances matter. With deferred or lazy repository bootstrap modes, the failure can move to the first use of the repository, so slice tests with @DataJpaTest should still create every repository. And renaming an entity field without renaming the methods breaks start-up, which is good, but a field renamed into another valid property can silently change meaning.
How do you traverse nested properties?
With a property path: chain the property names in camel case, as in findByCustomerAddressCity, and Spring Data resolves the path against the entity model. Camel case can be ambiguous, so the parser tries the longest matching property first and backtracks; if the entity also has a customerAddress property, it may pick the wrong path. An underscore forces the split, so findByCustomer_Address_City always means customer, then address, then city. For associations, the query creator adds joins, inner joins by default, so orders without a customer are excluded, which matters for optional relationships. Embedded objects add no join. For collection paths, such as findByLinesSku, duplicates can appear, so add Distinct or check the generated SQL.
Why can derived delete methods be slow?
Because a derived deleteBy method does not issue a single DELETE statement. It runs the derived select, loads every matching entity into the persistence context, and calls EntityManager.remove on each one, so cascades, orphan removal, entity listeners and lifecycle callbacks all run, and Hibernate flushes one DELETE per row, For a nightly job removing two million expired sessions that means heavy memory use, long transactions and millions of statements. When callbacks and cascades are not needed, use a @Modifying @Query bulk delete, which runs as one statement, then clear the persistence context, or delete in batches by key range. Bulk deletes bypass the persistence context, so loaded entities may become stale.
When should a derived query be replaced?
Replace it when the name stops being an honest, readable description of a simple query. My rule of thumb is more than two or three conditions, an Or that needs parentheses, or a name that wraps in the editor. Other triggers are needs the grammar cannot express: joins beyond simple property paths, fetch joins to avoid N+1 selects, aggregates and grouping, subqueries, database-specific functions or hints, and dynamic optional filters, where derived methods multiply into one per combination. For fixed complex queries, use @Query with named parameters; for dynamic filters, Specifications or Querydsl; for reporting and heavy reads, a dedicated query service with JdbcClient or a read model. Keep derived methods for simple finders.
How would you govern query methods in a large codebase?
I would treat query methods as part of the data access design, not personal style. Conventions come first: derived queries only for simple finders with at most two or three conditions, @Query with named parameters beyond that, Specifications for dynamic filters, and projections instead of entities for read-only use. Every repository gets @DataJpaTest tests against the real database with Testcontainers, and queries on large or hot tables need SQL review, an execution plan and a matching index before merge. Hibernate statistics and slow-query logs in production feed back into the review. Finally, complex reporting moves to dedicated query services or read models, so repositories stay cohesive instead of accumulating hundreds of finders.
Test your knowledge on this topic →Flashcards from this topic's 8 questions, filtered by level and type.