TechnicalEloquent performance

Eloquent performanceLesson 8 of 28

Getting LIKE to use an Index

No leading %. Use EXPLAIN to confirm the index is actually used.

2 min readIntermediateLesson

Eloquent performance08

The problem

The search takes 326 ms. Adding indexes on the name columns changed nothing (329 ms).

The fix

Run EXPLAIN to see which indexes are used, then drop the leading wildcard: term% instead of %term%.

✕ Instead of this

collect(explode(' ', $terms))->filter()->each(function ($term) use ($query) {
    $term = '%'.$term.'%';   // "contains": indexes can't help
    // ...
});

✓ Do this

collect(str_getcsv($terms, ' ', '"'))->filter()->each(function ($term) use ($query) {
    $term = $term.'%';       // "starts with": indexes can help
    // ...
});

The benefit

The name indexes become usable, and quoted phrases like "microsoft corp" stay together as one term.

Results

Search time

329 ms~275 ms

16% lower

still slow: see next lesson

More detail

Reading EXPLAIN: possible_keys are indexes that could be used. key is the one actually used. NULL means none.

Why it works

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.

Watch out

  • Now only the start of a value matches. That's usually how people search anyway.
  • Multi-word values like "Microsoft Corp" stop matching, hence str_getcsv for quoted phrases.
  • If indexes still aren't used, remove parts of the query one at a time until they are. That tells you the culprit.

Frame from lesson 8

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.

Key takeaway

No leading %. Use EXPLAIN to confirm the index is actually used.

Check yourself

EXPLAIN shows possible_keys with your index, but key is NULL. What does that mean?

Reveal answer

✓ Answer

MySQL could have used the index but chose not to. The query is still scanning rows.