MySQL Index Optimization: Table Lookup and Index Optimization
Table Lookup Query Explained
Basic Concepts
Indexes in InnoDB storage engine are divided into two types:
- Clustered Index: Leaf nodes store complete row record data
- Secondary Index: Leaf nodes only store index column values and corresponding record primary key values
Table Lookup Mechanism
Table lookup query refers to when using secondary index for queries, requiring two index tree accesses:
- First time: Find primary key value through secondary index
- Second time: Use primary key value to find complete record in clustered index
Performance Analysis
- Requires two index lookups
- May require two disk I/O operations
Covering Index Explained
Concept Definition
Covering index is an index optimization technique. When all columns required by a query are included in the index, index data can be directly used to satisfy the query.
Performance Advantages
- Reduces I/O operations
- Improves query speed
- Lowers resource consumption
Implementation Method
-- Create covering index
ALTER TABLE users ADD INDEX idx_name_age (name, age);
-- Use covering index
SELECT name, age FROM users WHERE name = 'John';
Leftmost Prefix Principle Explained
Principle Description
The leftmost prefix principle stipulates that when using composite indexes, query conditions must start from the leftmost column of the index to effectively utilize the index.
Specific Manifestations
- Query starting from leftmost column: Effectively uses index
- Skipping middle column becomes invalid: Can only use partial index
- Completely invalid without leftmost column: Index cannot be used
Special Cases
- Columns after range query become invalid
- Optimizer automatically adjusts
MySQL LIKE Query and Index Usage
Index Usage Situations
- ‘%name%’: Index does not work
- ‘%name’: Index does not work
- ‘name%’: Index can work
Impact of NULL Values on Indexes in MySQL
NULL Value Characteristics
- Cannot use ordinary equals (=) operator for comparison, must use IS NULL or IS NOT NULL
- Any arithmetic operation containing NULL results in NULL
- COUNT() does not count NULL value rows
Best Practices
- Try to set columns to NOT NULL and set reasonable default values
- NOT NULL columns usually have better query performance