Does the SQL Server clustered index replace the RID lookup “index”

前端 未结 3 2089
Happy的楠姐
Happy的楠姐 2021-01-04 06:51

When a table has a clustered index in SQL Server does that mean that all indexed queries will go via the clustered index?

For example if I have a table with a single

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-04 07:40

    When a table has a clustered index in SQL Server does that mean that all indexed queries will go via the clustered index?

    No.

    If a query only uses the fields covered by a secondary index and/or clustered index, the secondary index may (and most probably will) be preferred.

    CREATE TABLE test (id INT NOT NULL PRIMARY KEY, value1 INT NOT NULL, value2 INT NOT NULL)
    
    CREATE INDEX ix_test_value2 ON test (value2)
    
    SELECT  value2, id
    FROM    test
    

    The query above will most probably use ix_test_value2, since it contains all the information the query needs, but is less in size.

    This implies to me that the non-clustered index no longer 'terminates' with a RID at the leaf but with a clustering key of the clustered index? Is that right?

    Yes, with some little corrections:

    • If the clustered index is non-unique, the row pointer in the secondary index consists of the clustered key plus a special hidden column called uniquiefier (actually, this column is appended to the clustered index too).

    • If the secondary index covers some of the columns of the clustered index,, only the missing parts of the clustered key are appended as row pointers.

    • If the secondary index is declared UNIQUE, clustered key is appended only to the leaf-level records of the secondary index.

提交回复
热议问题