The search takes 326 ms. Adding indexes on the name columns changed nothing (329 ms).
Search time
329 ms~275 ms
16% lower
still slow: see next lesson
Eloquent performanceLesson 8 of 28
No leading %. Use EXPLAIN to confirm the index is actually used.
2 min readIntermediateLesson
The search takes 326 ms. Adding indexes on the name columns changed nothing (329 ms).
Run EXPLAIN to see which indexes are used, then drop the leading wildcard: term% instead of %term%.
collect(explode(' ', $terms))->filter()->each(function ($term) use ($query) {
$term = '%'.$term.'%'; // "contains": indexes can't help
// ...
});
collect(str_getcsv($terms, ' ', '"'))->filter()->each(function ($term) use ($query) {
$term = $term.'%'; // "starts with": indexes can help
// ...
});
The name indexes become usable, and quoted phrases like "microsoft corp" stay together as one term.
Search time
329 ms~275 ms
16% lower
still slow: see next lesson
Reading EXPLAIN: possible_keys are indexes that could be used. key is the one actually used. NULL means none.
An index is sorted, like a phone book. You can quickly find names that start with "Jo", but finding names that contain "jo" means reading every page.
str_getcsv for quoted phrases.
EXPLAIN in TablePlus: the users row is type ALL, scanning ~99k rows with possible_keys and key both NULL. The company lookups are DEPENDENT SUBQUERYs using only PRIMARY, so the new indexes are ignored.
No leading %. Use EXPLAIN to confirm the index is actually used.
EXPLAIN shows possible_keys with your index, but key is NULL. What does that mean?
✓ Answer
MySQL could have used the index but chose not to. The query is still scanning rows.