SQLite's indexing mechanism has a significant impact on query performance:
-
Index Types
- B-Tree Index: Default index type, suitable for range queries and sorting
- Hash Index: Only available in in-memory databases, suitable for equality queries
- R-Tree Index: Used for spatial data, supports geographic information queries
- Full-Text Index (FTS): Used for full-text search functionality
-
Index Creation
sql-- Create single column index CREATE INDEX idx_name ON table_name(column_name); -- Create composite index CREATE INDEX idx_composite ON table_name(col1, col2); -- Create unique index CREATE UNIQUE INDEX idx_unique ON table_name(column_name); -
Index Usage Principles
- Create indexes on columns frequently used in WHERE clauses, JOIN conditions, ORDER BY, GROUP BY
- Columns with high selectivity (many unique values) are more suitable for indexing
- Avoid creating indexes on small tables
- Composite indexes follow the leftmost prefix principle
-
Index Optimization Techniques
- Use
EXPLAIN QUERY PLANto analyze query execution plans - Avoid using functions or expressions on indexed columns
- Using
LIKE 'prefix%'can utilize indexes,LIKE '%suffix'cannot - Reasonably use covering indexes to avoid table lookups
- Use
-
Index Maintenance
- Indexes add overhead to INSERT, UPDATE, DELETE operations
- Regularly use the
ANALYZEcommand to update statistics - Use
REINDEXto rebuild fragmented indexes - Delete unused indexes to save space and improve write performance
-
Primary Keys and Auto Indexes
- Declaring PRIMARY KEY when creating a table automatically creates a unique index
- UNIQUE constraints also automatically create indexes
- WITHOUT ROWID tables can avoid creating hidden rowid indexes
Proper use of indexes can significantly improve query performance, but requires finding a balance between query performance and write performance.