🐥 Speeding up large Eloquent IN queries with temporary tables
yellowduck.be·15h
Flag this post

557 words, 3 min read

Filtering records by a list of primary keys is a common pattern in Eloquent:

$documents = Document::whereIntegerInRaw('documents.id', $documentIds)->get();

This works fine for a few hundred IDs. But once your $documentIds array grows beyond a few thousand items, MySQL performance drops dramatically. Even though id is indexed, a large IN (...) clause becomes slow because the optimizer expands it into a huge internal structure and may stop using the index altogether.

Let’s look at a better way.

Why WHERE id IN (...) becomes slow

When you pass thousands of IDs, MySQL must parse and sort them before matching against the index. For large lists, the optimizer may fall back to a full table scan, especially if it estimates that many rows will m…

Similar Posts

Loading similar posts...