Mục đích
Dùng EXPLAIN để phân tích cách MySQL thực thi truy vấn ORDER BY, xem có sử dụng index, filesort, temporary table không.
Ví dụ
Tạo bảng có Primary Key trên Id:
CREATE TABLE DemoTable606 (
Id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
FirstName VARCHAR(100)
);
INSERT INTO DemoTable606(FirstName) VALUES
('John'), ('Robert'), ('Chris'), ('David');
Case 1: ORDER BY Primary Key
EXPLAIN SELECT * FROM DemoTable606 ORDER BY Id;
Kết quả quan trọng: type=index, key=PRIMARY, Extra=NULL (không filesort).
→ Tối ưu: Duyệt index PRIMARY theo thứ tự, không cần sort thêm.
Case 2: ORDER BY Primary Key + cột khác
EXPLAIN SELECT * FROM DemoTable606 ORDER BY Id, FirstName;
Kết quả: type=ALL, Extra=Using filesort.
→ Không dùng được index cho sort phụ → phải filesort.
Case 3: ORDER BY Primary Key + RAND()
EXPLAIN SELECT * FROM DemoTable606 ORDER BY Id, RAND();
Kết quả: type=ALL, Extra=Using temporary; Using filesort.
→ RAND() phá vỡ thứ tự index → cần temporary table + filesort (rất chậm).
Giải thích các cột EXPLAIN quan trọng
| Cột | Ý nghĩa |
|---|---|
| type | Loại join/access: ALL (full scan), index (index scan), ref, eq_ref, const... |
| key | Index thực tế được sử dụng |
| rows | Số dòng ước lượng phải đọc |
| Extra | Thông tin thêm: Using filesort, Using temporary, Using index, Using where... |
Best Practice cho ORDER BY
- ORDER BY theo cột index (hoặc prefix của composite index) → tránh filesort.
- Tránh ORDER BY expression (RAND(), function, calculation).
- Composite index:
INDEX (a, b)hỗ trợORDER BY a, bnhưng KHÔNG hỗ trợORDER BY b, a. LIMITkết hợp với ORDER BY trên index → rất nhanh (chỉ đọc N dòng đầu).