Does Order of Fields of Multi-Column Index in MySQL Matter

前端 未结 3 961
一个人的身影
一个人的身影 2020-12-13 12:46

I know the importance of indexes and how order of joins can change performance. I\'ve done a bunch of reading related to multi-column indexes and haven\'t found the answer t

3条回答
  •  暖寄归人
    2020-12-13 13:05

    The two indexes are different. This is true in MySQL and in other databases. MySQL does a pretty good job of explaining the different in the documentation.

    Consider the two indexes:

    create index idx_lf on name(last_name, first_name);
    create index idx_fl on name(first_name, last_name);
    

    Both of these should work equally well on:

    where last_name = XXX and first_name = YYY
    

    idx_lf will be optimal for the following conditions:

    where last_name = XXX
    where last_name like 'X%'
    where last_name = XXX and first_name like 'Y%'
    where last_name = XXX order by first_name
    

    idx_fl will be optimal for the following:

    where first_name = YYY
    where first_name like 'Y%'
    where first_name = YYY and last_name like 'X%'
    where first_name = XXX order by last_name
    

    For many of these cases, both indexes could possibly be used, but one is optimal. For instance, consider idx_lf with the query:

    where first_name = XXX order by last_name
    

    MySQL could read the entire table using idx_lf and then do the filtering after the order by. I don't think this is an optimization option in practice (for MySQL), but that can happen in other databases.

提交回复
热议问题