Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

A developer calls repository.deleteById(id) for 10,000 ids in a loop and it takes minutes. What SQL runs, and what are faster options?

Each deleteById(id) call loads the entity with a SELECT and then removes it through the EntityManager, which issues a DELETE and also cascades to mapped children, so 10,000 ids mean at least 20,000 statements and 10,000 entities tracked in memory. The faster options are deleteAllByIdInBatch, which issues one DELETE with an IN clause, or a @Modifying JPQL delete with a where clause; both bypass the persistence context, cascades, lifecycle callbacks and orphan removal, so children must be handled by the database or explicitly, and very large deletes should be split into chunks.

Why this question is asked

This is a classic performance surprise. The code looks harmless, a loop calling a repository method, and works fine in tests with ten rows. In production, with 10,000 ids, it takes minutes and holds locks for the whole time. Interviewers ask it to see whether we can predict the SQL behind a Spring Data method instead of treating it as magic, and whether we know the trade-offs of bulk operations. In this answer, we will see what SQL deleteById really runs, measure why the loop is slow, look at the bulk alternatives, understand what they skip, and finish with chunking very large deletes.

1A Quick Recap: Deleting Through the Persistence Context

JPA deletes entities, not rows. To remove an entity, the EntityManager needs it as a managed object, an object it is tracking in the persistence context. That is because removing an entity can mean more than one statement: cascading the removal to child entities mapped with cascade = REMOVE or orphanRemoval, running @PreRemove callbacks, and updating any in-memory state.

Spring Data's deleteById is written on top of that model. It first finds the entity, then passes it to delete(), which calls entityManager.remove(). Nothing happens in the database for the remove itself until the transaction flushes, usually at commit.

2What SQL the Loop Runs

Here is the slow code and the log it produces for each id. Assume an Order entity with a list of OrderLine children mapped with cascade = CascadeType.ALL.

Java
@Transactional
public void purge(List<Long> ids) { // 10,000 ids
for (Long id : ids) orderRepository.deleteById(id);
}
// For each id:
// select o.* from orders o where o.id = ? -- load the order
// select l.* from order_line l where l.order_id = ? -- load lines to cascade
// At flush, for each id:
// delete from order_line where id = ? -- once per line
// delete from orders where id = ?

Notice how the statements add up. With an average of three lines per order, each id costs two selects and four deletes, so 10,000 ids produce about 60,000 statements, each a network round trip. On top of that, all 10,000 orders and 30,000 lines sit in the persistence context until commit, using memory, and Hibernate checks them all for changes at flush. If the loop is not in one transaction, it is even worse: each deleteById runs in its own transaction with its own commit.

In recent Spring Data versions, deleteById does not throw if the id does not exist; it simply does nothing after the select. Older versions threw EmptyResultDataAccessException, so check your version if code relies on that.

3Fast Option 1: deleteAllByIdInBatch

JpaRepository offers deleteAllByIdInBatch(Iterable<ID> ids). It does not load anything. It builds a single JPQL delete statement with an IN clause and runs it directly.

Java
orderLineRepository.deleteLinesOfOrders(ids); // @Modifying bulk delete of children, see below
orderRepository.deleteAllByIdInBatch(ids);
// delete from orders where id in (?, ?, ?, ... ) -- one statement

This turns 60,000 statements into a handful. The database does the work in one pass using the primary key index. deleteAllInBatch(Iterable<T> entities) does the same when we already hold the entities.

4Fast Option 2: A @Modifying JPQL Delete

When the rows to delete are described by a condition rather than a list of ids, a bulk JPQL delete is even better, because we do not need to fetch the ids at all. The @Modifying annotation tells Spring Data that the query changes data and should be run with executeUpdate rather than as a select.

Java
interface OrderRepository extends JpaRepository<Order, Long> {
@Modifying
@Query("delete from Order o where o.status = :status and o.createdAt < :before")
int deleteOld(@Param("status") Status status, @Param("before") Instant before);
}
int n = orderRepository.deleteOld(Status.CANCELLED, cutoff);
// delete from orders where status = ? and created_at < ?
// n = 10000

The method returns the number of rows deleted, which is useful for logging. It must run in a transaction, so call it from a @Transactional service method or mark the repository method @Transactional.

5What Bulk Deletes Skip

Bulk deletes are fast because they go around the persistence context, and that is also their danger. Hibernate does not load the entities, so it cannot cascade to children, cannot apply orphan removal, and does not call @PreRemove or @PostRemove callbacks. Entity listeners such as auditing hooks do not run either. If the orders table has child rows in order_line with a foreign key, the delete fails with a constraint violation, or, if there is no foreign key, leaves orphaned lines behind.

So we have to handle children ourselves. One way is to delete them first with their own bulk statement, as in the earlier example, where deleteLinesOfOrders is a @Modifying query such as delete from OrderLine l where l.order.id in :ids. Another is to let the database do it with ON DELETE CASCADE on the foreign key, which is fast and cannot be forgotten. If the rest of the transaction still holds some of the deleted orders in memory, they are now stale; adding clearAutomatically = true to @Modifying clears the persistence context after the statement, so later reads go back to the database.

Delete options compared for 10,000 orders
ApproachStatementsCascades and callbacksMemory
deleteById in a loopabout 60,000Yes, all runAll entities loaded
deleteAllByIdInBatch1 per chunkNoNothing loaded
@Modifying JPQL delete1NoNothing loaded
Database ON DELETE CASCADE1 plus database workDatabase handles childrenNothing loaded
Bulk options trade lifecycle behaviour for speed.

6Chunking Very Large Deletes

One statement is not always best. Deleting a million rows in a single transaction holds locks on all of them, grows the undo or WAL log, and can stall replicas. An IN clause also has limits: some databases cap the number of bind parameters, for example around 32,767 in PostgreSQL's protocol and fewer in some others, so check your database.

The usual pattern is to split the work into chunks of a few thousand ids, each in its own short transaction.

Java
List<List<Long>> chunks = partition(ids, 2_000);
for (List<Long> chunk : chunks) {
tx.executeWithoutResult(s -> {
orderLineRepository.deleteLinesOfOrders(chunk);
orderRepository.deleteAllByIdInBatch(chunk);
});
}
// 5 transactions of 2,000 ids each for 10,000 ids

Each chunk commits quickly, locks are released early, and if something fails we lose only one chunk's work and can resume from where we stopped.

7Follow-up questions

Why not keep deleteById but enable JDBC batching?

Batching with hibernate.jdbc.batch_size groups the delete statements into fewer round trips, which helps. But the selects that load each entity are still separate, and everything is still held in memory. It is a partial improvement; when cascades and callbacks are not needed, a bulk delete is much better.

Is a derived deleteByStatus method a bulk delete?

No. A derived delete method loads the matching entities and removes them one by one, so it behaves like the loop. For a real bulk delete we need deleteAllInBatch-style methods or a @Modifying @Query.

When would you keep the slow per-entity delete?

When the removal must run domain logic: callbacks that publish events, auditing listeners, or cascades across a deep graph that the database does not know about. Even then I would chunk it and keep each transaction short.

8Conclusion

In this answer, we saw that deleteById loads each entity and removes it through the persistence context, so a loop over 10,000 ids runs tens of thousands of statements and fills memory. deleteAllByIdInBatch and @Modifying JPQL deletes run one statement each, but skip cascades, orphan removal and callbacks, so children must be removed first or by the database, and very large deletes should be split into short chunked transactions.

What to say in the interviewAbout 80 seconds aloud

Open with

deleteById is not a simple delete statement. Spring Data first finds the entity, which is a select, and then calls entityManager.remove on it. Remove cascades to any children mapped with cascade remove or orphan removal, so Hibernate loads those too, and at flush it deletes each child and then the parent.

Then, if they want more

So for 10,000 ids we get at least 20,000 statements, often far more with children, and every entity sits in the persistence context until commit. That is why it takes minutes. The fast options skip the persistence context. deleteAllByIdInBatch builds one delete with an IN clause for the ids.

Or, if the rows are described by a condition, a @Modifying @Query with a JPQL delete removes them in one statement and returns the count.

The catch is that bulk deletes do not cascade, do not apply orphan removal and do not run entity callbacks or listeners, so I have to handle children myself, either by deleting them first with their own bulk statement or with ON DELETE CASCADE on the foreign key. I would also add clearAutomatically if the same transaction holds stale entities.

Finally, for really large deletes I would chunk the ids, say 2,000 per transaction, to keep locks short, stay under parameter limits and make the job restartable.

About this answer

Last updated
12 November 2026
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 "A developer calls repository.deleteById(id) for 10,000 ids in a loop and it takes...": https://scrivio-interview-library.netlify.app/databases/spring-data-jpa/ef1aadc6e2/