TechnicalEloquent performance

Eloquent performanceLesson 14 of 28

Faster Ordering With Compound Indexes

Sorting by several columns? One compound index, in the same order.

2 min readIntermediateLesson

Eloquent performance14

The problem

Ordering by last name then first name took a query from ~6 ms to ~95 ms. Separate indexes on each column didn't help.

The fix

Add one index covering both columns, in the same order as your ORDER BY.

✕ Instead of this

$table->index('last_name');
$table->index('first_name');
// EXPLAIN: "Using filesort"

✓ Do this

$table->index(['last_name', 'first_name']);

User::orderBy('last_name')->orderBy('first_name')->paginate();

The benefit

Back to ~6 ms from ~95 ms. MySQL reads rows already in order instead of sorting them.

Results

Query time

~95 ms~6 ms

94% lower

Why it works

Two separate indexes are like two separate phone books, one by surname and one by first name. To sort by both, you need one book sorted by surname then first name. EXPLAIN's "Using filesort" means MySQL is sorting every row itself.

Watch out

  • Column order matters. Sorting by first name first needs ['first_name', 'last_name'].
  • Always add an orderBy when paginating. Without one, row order isn't guaranteed and records can skip between pages.

Frame from lesson 14

EXPLAIN of order by last_name, first_name with two separate indexes: no key is used, ~99,100 rows are scanned, and Extra says Using filesort. The compound index fixes this.

Key takeaway

Sorting by several columns? One compound index, in the same order.

Check yourself

You have an index on ['last_name', 'first_name']. Will it speed up orderBy('first_name')->orderBy('last_name')?

Reveal answer

✓ Answer

No. The index order has to match the ORDER BY order.