Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should i use an index on a column with limited number of values?

Reading this I now understand when to use indexes and when not to use them. But i have a question; would using an index on a column with a limited number of possible values help speedup queries (SELECT-ing) ? Consider the following:

Table "companies": id, district_id, name
Table "districts": id, name

The number of districts would never pass 5 entries. Should i use an index on companies.district_id then or not? I read somewhere (can't find the link :( ) that it wont help since the values are not that many and it would actually slow down the query in many cases.

PS: both tables are MyISAM

like image 948
Dewan159 Avatar asked Nov 15 '25 08:11

Dewan159


1 Answers

Almost never is an INDEX on a low-cardinality column used by the optimizer.

On the other hand, a "compound index" may be useful. For example, does INDEX(district_id, name) have any use?

Having INDEX(district_id) will slow down INSERTs because the index is added to whenever a row is inserted. It will not slow down SELECTs, other than the minor amount of time for the Optimizer to notice the index and reject it.

(My statements apply to both MyISAM and InnoDB.)

More discussion of this answer: MySQL: Building the best INDEX for a given SELECT: Flags and Low Cardinality

like image 65
Rick James Avatar answered Nov 18 '25 11:11

Rick James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!