Lesson 23 of the SQL Optimization Course: Index Cardinality and Selectivity

For relational databases, the design of tables and SQL is written are particularly crucial. It wouldn’t be an exaggeration to say that they account for 90% of performance. So this time, specifically targeting these two major knowledge areas, we’ll conduct a detailed analysis for you, peeling back the layers.
This Series uses plain and understandable language and selects a large number of examples to elaborate on the subtleties for you.
🧑💻 Target audience:
We will use MySQL as the demonstration database.
Definition:
Index cardinality refers to the estimated number of unique values in an index. High cardinality means unique values dominate (e.g., primary keys), while low cardinality indicates many duplicate values (e.g., status flags).
MySQL relies on cardinality to determine optimal query execution plans. Outdated or inaccurate cardinality values can lead to suboptimal performance, such as full table scans instead of index usage.
Data Distribution:
Update Frequency:
ANALYZE TABLE
or SHOW INDEX
are sometimes necessary.Composite Indexes:
(col1, col2)
computes cardinality for col1
, then (col1,col2)
, etc.).
|
|
Problem: Filtering on a low-cardinality column (status) leads to full table scans.
|
|
Solution: Avoid indexing low-cardinality columns unless combined with high-cardinality fields.
Problem: Queries on date ranges may ignore indexes if cardinality is low.
|
|
Workaround: Use covering indexes or partitioning for large date ranges.
TABLE_SCHEMA | TABLE_NAME | INDEX_NAME | CARDINALITY |
---|---|---|---|
your_db | users | PRIMARY | 10000 |
your_db | users | idx_email | 5000 |
your_db | orders | idx_status | 50 |
Prioritize High-Cardinality Columns:
Avoid Over-Indexing:
Monitor Cardinality Trends:
👋 See you in the next lesson.
SQLFlash is your AI-powered SQL Optimization Partner.
Based on AI models, we accurately identify SQL performance bottlenecks and optimize query performance, freeing you from the cumbersome SQL tuning process so you can fully focus on developing and implementing business logic.
Join us and experience the power of SQLFlash today!.