Difference between 2 indexes with columns defined in reverse order

后端 未结 5 1925
梦毁少年i
梦毁少年i 2021-01-02 04:07

Are there any differences between following two indexes?

  • IDX_IndexTables_1
  • IDX_IndexTables_2

If there are any, what are the difference

5条回答
  •  有刺的猬
    2021-01-02 04:38

    What you have is a composite index. The order is important when your WHERE clause is not using all columns in the composite index.

    Consider this query:

    SELECT val1
    FROM IndexTables
    WHERE val1 = 'MyValue'
    

    In order to know what index might be considered read from left to right the columns in your composite indexes. If the column doesn't exist in your query before you read all the columns in your query then the index won't be used.

    IDX_IndexTables_1 (val1, val2): Reading from left to right val1 exists and it is our only column so this index would be considered

    IDX_IndexTables_2 (val2, val1): Reading from left to right val2 doesn't exist in this query so it won't be used.

提交回复
热议问题