Giới thiệu
Từ khóa EXPLAIN hiển thị kế hoạch thực thi truy vấn, giúp tối ưu hóa hiệu suất bằng cách kiểm tra việc sử dụng chỉ mục (index).
1. Tạo bảng và chỉ mục
mysql> create table DemoTable1541 (
-> EmployeeId int,
-> EmployeeFirstName varchar(20) NOT NULL
-> );
Query OK, 0 rows affected (0.94 sec)
mysql> create index emp_name_index on DemoTable1541(EmployeeFirstName);
Query OK, 0 rows affected (0.75 sec)
Records: 0 Duplicates: 0 Warnings: 0
2. Chèn dữ liệu
mysql> insert into DemoTable1541 values(1,'Robert'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable1541 values(2,'Adam'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable1541 values(3,'Mike'); Query OK, 1 row affected (0.14 sec)
3. Sử dụng EXPLAIN
mysql> explain select * from DemoTable1541 where EmployeeFirstName='Mike';
4. Kết quả phân tích
+----+-------------+---------------+------------+------+----------------+----------------+---------+-------+------+----------+-------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+---------------+------------+------+----------------+----------------+---------+-------+------+----------+-------+ | 1 | SIMPLE | DemoTable1541 | NULL | ref | emp_name_index | emp_name_index | 62 | const | 1 | 100.00 | NULL | +----+-------------+---------------+------------+------+----------------+----------------+---------+-------+------+----------+-------+ 1 row in set, 1 warning (0.00 sec)
Giải thích các cột quan trọng:
| Cột | Ý nghĩa | Giá trị ví dụ |
|---|---|---|
| type | Loại truy cập | ref (tra cứu chỉ mục không duy nhất) |
| possible_keys | Chỉ mục có thể dùng | emp_name_index |
| key | Chỉ mục thực tế dùng | emp_name_index |
| key_len | Độ dài khóa dùng (byte) | 62 (varchar(20) utf8mb4 = 20*3 + 2) |
| rows | Số hàng ước lượng quét | 1 (rất tốt) |
| Extra | Thông tin thêm | NULL (không có filesort, temporary) |
Kết luận: Truy vấn sử dụng chỉ mục hiệu quả (type=ref, rows=1). Nếu type=ALL → cần thêm index.