Which column to put first in index? Higher or lower cardinality?

让人想犯罪 __ 提交于 2019-12-02 03:48:29

MySQL composite index lookups must take place in the order in which the columns are defined within the index. Since you want MySQL to be able to discriminate between records by performing as few comparisons as possible, with all other things being equal you will benefit most from from a composite index in which the columns are ordered from highest- to lowest-cardinality.

That is, assuming comparisons must eventually be performed against the highest cardinality column in order to discriminate records, why force comparisons to take place first against the lowest cardinality column when ultimately that may be unnecessary?

It does not matter in this case:

INDEX cs (city, state),
INDEX sc (state, city)

WHERE city = 'Atlanta'
  AND state = 'Georgia'

With either index, the drill-down in the BTree will be the same effort, and you will get to the one row just as fast.

(The order of clauses in WHERE does not matter.)

(If you are using a "range" test instead of = test, well, that's a different Question.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!