I have a table with about 1000 cities. Sometimes, I need to search by city name and have therefore decided to make it an index. What would be the best practice to decide on the index length? 6 seems like the optimal choice, because there would be almost no duplicates.
Example Table:
cityID | cityName | countyID
1 | Bethlehem | 30
2 | Blairstown | 38
3 | Bloomfield | 32
4 | Bloomingdale | 34
5 | Bloomsbury | 30
6 | Bogota | 31
7 | Boonton | 33
8 | Botsford | 44
9 | Bound Brook | 35
10 | Branchburg | 35
11 | Branchville | 36
12 | Brantwood | 32
13 | Briarcliff Manor | 25
cityID – Primary Key
countyID – Key
cityName (6) – Key
Am I doing this right?
When I tried running
EXPLAIN SELECT *
FROM 'CITIES'
WHERE 'cityName' = 'Branchburg'
I got the following results:
id: 1
select_type: SIMPLE
table: CITIES
type: ref
possible_keys: cityName
key: cityName
key_len: 20
ref: const
rows: 2
Extra: Using where
Shouldn’t “key_len” be 6?
It depends on character set. For example, if you are using utf8, it is like 6 * 3 = 18 … thought, I’m not sure where 2 bytes came from