✏️ Explanatory Question
Level: Advanced — A senior-level concept that explains WHY some indexes help and others don't.
Both terms describe how "unique" the values in a column are, which directly determines how effective an index will be.
Selectivity is calculated as:
$$ Selectivity = \frac{\text{Number of Distinct Values}}{\text{Total Number of Rows}} $$
The result ranges from just above 0 (very poor) to 1 (perfect, all unique). A value close to 1 means an excellent index candidate.
| Column | Distinct Values | Selectivity | Index Quality |
|---|---|---|---|
| 10,000 | 1.0 | Excellent | |
| last_name | 3,000 | 0.30 | Good |
| city | 50 | 0.005 | Weak |
| gender | 2 | 0.0002 | Poor |
-- Check cardinality of each index (see the Cardinality column)
SHOW INDEX FROM employees;
-- Count distinct values to estimate selectivity manually
SELECT
COUNT(DISTINCT email) AS email_distinct,
COUNT(DISTINCT gender) AS gender_distinct,
COUNT(*) AS total_rows
FROM employees;
-- Refresh cardinality statistics so the optimizer chooses wisely
ANALYZE TABLE employees;
-- High selectivity -> index is used
EXPLAIN SELECT * FROM employees WHERE email = 'a@x.com'; -- uses index
-- Low selectivity -> optimizer may skip the index
EXPLAIN SELECT * FROM employees WHERE gender = 'M'; -- may full scan