Search code examples
sql-serversql-server-2008indexingclustered-index

SqlServer clustered index storage ( >1 columns )?


lets say i have a table like this :

a | b | c | d 
______________
1 | 2 | 4 | 5
6 | 2 | 5 | 5
3 | 5 | 2 | 5

[a] column has clustered index

so the physical order which its stored is :

a | b | c | d 
______________
1 | 2 | 4 | 5
3 | 5 | 2 | 5
6 | 2 | 5 | 5

now lets enhance the [a] index to be [a,c] ( still as clustered).

now , I can't udnerstand how it can be stored since [a] column is already sorted and [c] column cant be sorted ( because sorting of [a] hurts the sorting of [c])

so how does sqlServer will store it ?

2'nd question : do I need to open another index for [c] ?


Solution

  • Composite indexes produce lexicographical order: the records are additionally ordered on c when values of a are considered "equal".

    a c
    1 2
    2 3 -- Within this block, records are sorted on [c]
    2 5 --
    2 7 --
    3 7
    4 1
    5 6 -- Within this block, records are sorted on [c]
    5 8 --
    

    This is how dictionaries sort.

    You need an additional index on c if you want to speed up queries not involving a:

    SELECT  *
    FROM    mytable
    WHERE   c = @some_value