zoukankan      html  css  js  c++  java
  • The sequence of columns in an clustered index

      Simplily say, If you have a CI(clustered index) which is composed by 4 columns, Which one of the 4 would you put into the first one in the CI? and Which would be put into the last? Or you shouldn't consider this question at all, just put them casually togather to form a CI?
      Actually I never thought about this question before, until I came to a problem, and now let me describe it to you. I have a table A, and the table have a CI on it. I had many queries about the table, and all the queries used the CI, and they worked well. One day for some reason I have to add an new column into the table, and also I have to add the column into the CI. The old CI have 5 columns, and I insert the new column between the 1st CI column and 2nd CI column(This insertion make the new column very important to the table, which I didn't understand at that time). After add the new column and rebuild the index, the old querys became slow. That's  not surprising because they didn't use the new CI. Let's see the example code of a simple query:
    Select * from A
    where col1 = 'something'
    and col2 = 30
    and col3 = 50
    and col4 = 70
    and col5 between 30 and 40
    I changed the query to make it use the new CI:
    Select * from A
    where col1 = 'something'
    and newCol between 1 and 4
    and col2 = 30
    and col3 = 50
    and col4 = 70
    and col5 between 30 and 40
    When I run the new query, it's much slower than I had estimated. I checked the execution plan, the CI was used. But when I check the logic io, there was a huge logical read here.
    So what's the problem? The between operation for the new column seems a little suspected, but as you could see from the code above, in old querys we implemented between to col5 too, and it worked well! I tried to change the new query like this:
     Select * from A
    where col1 = 'something'
    and newCol in (select value from aEnumTable)
    and col2 = 30
    and col3 = 50
    and col4 = 70
    and col5 between 30 and 40
    And it is fast now, and the number of logical reads dramatically decreased to a very small value. So why can we put "between" operation on col5 but not on newCol? Now you got the anwser: Because they are not at the sequence in the CI. CI is builded as a B-Tree, and when the tree is builded, the columns which has smaller sequence number define the main order of all indexes.
     
  • 相关阅读:
    POST数据中有特殊符号导致数据丢失的解决方法
    Javascript中bind()方法的使用与实现
    Vue插件写、用详解(附demo)
    js自定义事件、DOM/伪DOM自定义事件
    对象可枚举和不可枚举属性
    js 数组 map方法
    Java源码学习(JDK 11)——java.util.concurrent.CopyOnWriteArrayList
    Java源码学习(JDK 11)——java.util.Collections
    Java源码学习(JDK 11)——java.util.Arrays
    Java源码学习(JDK 11)——java.lang.Collection
  • 原文地址:https://www.cnblogs.com/xingyukun/p/1144132.html
Copyright © 2011-2022 走看看