MySQL Index and Sorting Mechanism: Filesort and Index Sort Deep Dive
Two Sorting Methods Overview
filesort Sorting Method
Used when index cannot be used for sorting:
- Data retrieval phase
- Sort processing phase
- Result return phase
index Sorting Method
Utilizing the ordered nature of the index itself:
- Directly uses index
- No additional overhead
- Significant performance advantage
Conditions
- ORDER BY clause must exactly match index column order
- Sort direction must be consistent with index definition
filesort Algorithm Explained
Two-pass Sorting
- First disk scan: Only reads sorting fields and row pointers
- Sort phase: Sorts in sort buffer
- Second disk scan: Table lookup to read complete data
Single-pass Sorting
- Single disk scan: Reads all columns at once
- Memory sorting
- Result return
Optimization Suggestions
-- Avoid using SELECT *
SELECT id, name, create_time FROM large_table ORDER BY create_time DESC;
-- Increase sort buffer size
SET sort_buffer_size = 4 * 1024 * 1024;
EXPLAIN Analysis
Using filesort
Indicates file sort operation is used.
Using index
Indicates query uses covering index, the ideal situation.
Examples
-- Can use index
EXPLAIN select id from wzk_user order by id;
-- Uses filesort
EXPLAIN select id from user_info order by username;
Relationship Between Index and Sorting
Situations Where Index Cannot Be Used for Sorting
- Inconsistent sort direction
- Field order mismatch
- Mixed use of ASC and DESC
- Contains non-indexed fields
ASC DESC
- ASC: Ascending order
- DESC: Descending order