Ordering by last name then first name took a query from ~6 ms to ~95 ms. Separate indexes on each column didn't help.
Query time
~95 ms~6 ms
94% lower
Eloquent performanceLesson 14 of 28
Sorting by several columns? One compound index, in the same order.
2 min readIntermediateLesson
Ordering by last name then first name took a query from ~6 ms to ~95 ms. Separate indexes on each column didn't help.
Add one index covering both columns, in the same order as your ORDER BY.
$table->index('last_name');
$table->index('first_name');
// EXPLAIN: "Using filesort"
$table->index(['last_name', 'first_name']);
User::orderBy('last_name')->orderBy('first_name')->paginate();
Back to ~6 ms from ~95 ms. MySQL reads rows already in order instead of sorting them.
Query time
~95 ms~6 ms
94% lower
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.
['first_name', 'last_name'].orderBy when paginating. Without one, row order isn't guaranteed and records can skip between pages.
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.
Sorting by several columns? One compound index, in the same order.
You have an index on ['last_name', 'first_name']. Will it speed up orderBy('first_name')->orderBy('last_name')?
✓ Answer
No. The index order has to match the ORDER BY order.