Scrivio Interview library
ConceptIntermediate7 min read · updated 12 November 2026

Explain existsBy, countBy and the projection return types of derived queries. How can you make an existence check efficient?

existsBy... methods return boolean, and Spring Data runs a query that stops at the first matching row; countBy... methods return long from a count query. Derived queries can also return a single entity, Optional, List, Stream, Slice, Page, or an interface or DTO projection that reads only some columns. An existence check is efficient when the filtered columns are indexed, and when the goal is preventing duplicates under concurrency, a unique constraint is the correct tool, not an exists check.

Why this question is asked

Checking whether something exists is one of the most frequent things a service does: is this email taken, does this customer have open orders, has this event already been processed. Done badly, it loads whole entities or counts millions of rows just to answer yes or no. Interviewers ask about existsBy and countBy to see whether we know the cost of each, and about projections to see whether we can fetch only what we need. The concurrency point at the end tells them whether we know where checks stop working. In this answer, we will recap derived query subjects, look at the SQL behind existsBy and countBy, go through the return types including projections, make an existence check fast with an index, and see why a unique constraint beats a check-then-insert.

1A Quick Recap: The Subject of a Derived Query

A derived query method is a repository method whose name Spring Data turns into a query. The first word, the subject, decides what kind of query: find, read, get, query, search and stream return data; count returns a number; exists returns a boolean; delete and remove delete. The part after By describes the conditions on entity properties.

So existsByEmail(String email) and countByStatus(Status s) are full queries even though we wrote only their names. The question is what SQL they become.

2What existsBy and countBy Run

Here are both methods and the SQL Hibernate 6 produces for them on PostgreSQL. The exact SQL differs by version and dialect, but the shape is what matters.

Java
interface UserRepository extends JpaRepository<User, Long> {
boolean existsByEmail(String email);
long countByStatus(Status status);
}
userRepository.existsByEmail("ana@example.com");
// select u.id from users u where u.email = ? fetch first ? rows only -- limit 1
// -> true
userRepository.countByStatus(Status.ACTIVE);
// select count(u.id) from users u where u.status = ?
// -> 184233

Notice the difference in work. existsByEmail asks for at most one row, so the database can stop as soon as it finds a match. countByStatus must find every matching row to count them, so on a big table it reads far more. That is why existsBy is the right choice for a yes-or-no question, and why writing countByEmail(email) > 0 is a common mistake: it gives the same answer but may scan many more rows.

An older approach, a custom @Query("select count(u) > 0 ..."), still counts everything; Spring Data's derived exists avoids that.

3The Return Types a Derived Query Can Have

The return type of a find method tells Spring Data how to run the query and package the result. A single entity returns the match or null, and throws if there is more than one. Optional<T> is the same but makes the empty case explicit. List<T> and other collections return all matches. Stream<T> returns results lazily as we iterate, which saves memory for large results, but must be consumed inside a transaction and closed, usually with try-with-resources. Slice<T> and Page<T> take a Pageable: a Slice knows whether there is a next page, and a Page also runs a count query to know the total.

Projections let us select only some columns. An interface projection declares getters for the properties we want, and Spring Data selects just those. A DTO projection, often a Java record, does the same through its constructor. Both avoid loading full entities and avoid the persistence context tracking them.

Java
interface UserEmail { String getEmail(); } // interface projection
record UserCard(Long id, String email, Status status) { } // DTO projection
interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email); // entity or empty
List<UserEmail> findByStatus(Status s); // select u.email ...
List<UserCard> findTop20ByStatusOrderByIdDesc(Status s); // select u.id, u.email, u.status ...
Slice<User> findByStatus(Status s, Pageable p); // fetches size + 1 rows, no count
Page<User> findByCreatedAtAfter(Instant t, Pageable p); // plus select count(...)
Stream<User> streamByStatus(Status s); // lazy; consume in a transaction
}
Choosing a derived query return type
Return typeExtra queryUse it for
boolean (existsBy)None; stops at first rowYes or no questions
long (countBy)None; counts all matchesShowing a number
Optional<T>NoneZero or one result
List<T> / projectionNoneSmall result sets
Slice<T>One extra row fetchedNext page or infinite scroll
Page<T>A count queryPages with totals
Stream<T>None; lazyLarge results processed once
Pick the cheapest type that answers the caller's real question.

The two findByStatus methods have different parameter lists, so they can coexist. With a projection, the generated select lists only the needed columns, which is less data over the network and, with the right index, sometimes no table access at all.

4Making the Existence Check Fast

existsBy stops at the first match, but finding that first match can still be slow. If users has ten million rows and no index on email, the database must scan the table until it finds the address, and when the address does not exist, which is the common case for a sign-up check, it scans the whole table. The plan shows a sequential scan.

SQL
explain select u.id from users u where u.email = 'new@example.com' limit 1;
-- Seq Scan on users (rows=10000000) -- before the index
create unique index users_email_uk on users (email);
explain select u.id from users u where u.email = 'new@example.com' limit 1;
-- Index Only Scan using users_email_uk on users (rows=1) -- after

With an index on the filtered column, the database jumps straight to the place in the index where the value would be and answers in a few page reads, whether or not the value exists. For multi-column checks, such as existsByCustomerIdAndStatus, the index should cover both columns, with the equality columns first.

5Why a Unique Constraint Beats an Exists Check

A common pattern is: if not existsByEmail(email), then save a new user. Under concurrency it is broken. Two sign-up requests with the same email arrive at the same moment. Both run existsByEmail, both get false because neither has inserted yet, and both insert. Now there are two accounts with one email.

Step throughTwo requests race past an exists check
Request ADatabaseRequest B
existsByEmail(ana) -> false
existsByEmail(ana) -> false
insert user ana
insert user ana
both commit: duplicate email

5 messages in order. Play them, or step through them one at a time.

The check and the insert are separate steps, so another request fits between them.

6Relying on the Constraint

Transaction isolation does not save us here at the default READ COMMITTED level, because neither transaction can see the other's uncommitted row. The fix is to let the database enforce the rule with a unique constraint, the same unique index we created above, and handle the error.

Java
@Transactional
public User register(String email) {
try {
return userRepository.saveAndFlush(new User(email)); // flush to hit the constraint now
} catch (DataIntegrityViolationException e) {
throw new EmailTakenException(email); // the second request ends here
}
}

The exists check can still be useful before the insert to give a friendly message in the usual case, but the constraint is what guarantees correctness. saveAndFlush makes the insert happen inside the try block; with plain save the insert might be delayed until commit, outside our catch.

7Follow-up questions

Is existsById efficient?

Yes. CrudRepository's existsById runs a count or limited query on the primary key, which is always indexed. It does not load the entity, so it is cheaper than findById(id).isPresent() when we only need the answer.

When would you use countBy instead of existsBy?

Only when the caller needs the actual number, such as a badge showing 12 unread messages. For a yes or no question existsBy is cheaper. If the number can be large and only needs to be approximate, consider capping it, for example showing 99+ by counting a limited subquery.

Do projections still return managed entities?

No. Interface and DTO projections are read-only views of the selected columns. The persistence context does not track them, so changing a projection does nothing at commit. To update, load the entity or run an update query.

8Conclusion

In this answer, we saw that existsBy runs a query that stops at the first row while countBy counts every match, so existsBy is the right tool for yes or no questions. Derived queries can return entities, Optional, collections, Stream, Slice, Page and projections, each with its own cost. An index on the filtered columns makes the existence check fast, and a unique constraint, not a check, is what keeps duplicates out under concurrency.

What to say in the interviewAbout 100 seconds aloud

Open with

existsBy methods return a boolean, and Spring Data generates a query that limits to one row, so the database can stop as soon as it finds a match. countBy methods return a long from a select count, which has to visit every matching row, so using count greater than zero to test existence is wasteful.

Then, if they want more

Derived queries support many return types: a single entity or Optional for zero or one result, List for several, Stream for large results processed lazily inside a transaction, Slice which fetches one extra row to know if there is a next page, and Page which also runs a count query for totals.

They can also return projections, either an interface with getters or a record DTO, so only the needed columns are selected and nothing is tracked by the persistence context. To make an existence check fast, the columns in the condition need an index.

Without one, checking an email that does not exist scans the whole table, which is exactly the common case in a sign-up form. With a unique index on email it is a few page reads. And one important point: if the goal is preventing duplicates, exists then insert is a race. Two requests can both see false and both insert.

The database must enforce it with a unique constraint, and I catch DataIntegrityViolationException, using saveAndFlush so the error happens inside my try block. The exists check is then just for a friendly message.

About this answer

Last updated
12 November 2026
Versions it names
Hibernate 6
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Explain existsBy, countBy and the projection return types of derived queries. How can...": https://scrivio-interview-library.netlify.app/databases/spring-data-jpa/ed082fdb37/