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...

Keyboard Shortcuts

Navigation
Next / previous item
j/k
Open post
oorEnter
Preview post
v
Post Actions
Love post
a
Like post
l
Dislike post
d
Undo reaction
u
Recommendations
Add interest / feed
Enter
Not interested
x
Go to
Home
gh
Interests
gi
Feeds
gf
Likes
gl
History
gy
Changelog
gc
Settings
gs
Browse
gb
Search
/
General
Show this help
?
Submit feedback
!
Close modal / unfocus
Esc

Press ? anytime to show this help