MySQL Index Types and Practical Guide: Principles, Classification, Application and Optimization
Main Functions of Indexes
- WHERE Query: Index can quickly locate data rows matching conditions
- ORDER BY Sorting: Use index’s ordering to directly obtain sorted results
Index Type Classification
By Storage Structure
- BTree Index: Most common index type
- Hash Index: Suitable for equi-joins
- FULLTEXT Index: Used for full-text search
- RTree Index: Used for spatial data indexing
By Application Layer
- Regular Index: Most basic index type
- Unique Index: Requires index column values to be unique
- Primary Key Index: Special unique index, does not allow NULL values
- Composite Index: Index established on multiple columns
By Data Storage
- Clustered Index: Leaf nodes directly store row data
- Non-clustered Index: Leaf nodes store primary key values
Regular Index
CREATE INDEX index_name ON table_name(column_name);
ALTER TABLE table_name ADD INDEX index_name(column_name);
CREATE TABLE table_name (
column1 datatype,
INDEX index_name (column_name)
);
Unique Index
CREATE UNIQUE INDEX index_name ON table_name(column_name);
ALTER TABLE table_name ADD UNIQUE (column_name);
Primary Key Index
CREATE TABLE users (
user_id INT NOT NULL,
PRIMARY KEY (user_id)
);
Composite Index
CREATE INDEX idx_name ON table_name(column1, column2);
-- Leftmost prefix principle
SELECT * FROM table WHERE column1 = 'xxx';
SELECT * FROM table WHERE column1 = 'xxx' AND column2 = 'yyy';
Full-text Index
ALTER TABLE wzk_user ADD FULLTEXT INDEX ft_username (username);
SELECT * FROM wzk_user WHERE match(username) against('wzk');