SQL Server索引使用问题

Chr*_*ris 2 sql-server performance query-optimization

假设如下:

/*

drop index ix_vouchers_nacsz on dbo.vouchers;
drop index ix_vouchers_nacsz2 on dbo.vouchers;

create index ix_vouchers_nacsz on dbo.Vouchers(
    FirstName, LastName,
    Address, Address2, City,
    State, Zip, Email
);

create index ix_vouchers_nacsz2 on dbo.Vouchers(
    Email, FirstName, LastName,
    Address, Address2, City,
    State, Zip
);

*/

select count(firstname) from vouchers
    with (index(ix_vouchers_nacsz))
where 
    firstname = 'chris' and
    lastname = '' and
    address = '' and
    address2 = '' and
    city = '' and
    state = '' and
    zip = ''

select count(firstname) from vouchers
    with (index(ix_vouchers_nacsz2))
where 
    firstname = 'chris' and
    lastname = '' and
    address = '' and
    address2 = '' and
    city = '' and
    state = '' and
    zip = ''
Run Code Online (Sandbox Code Playgroud)

为什么第二个索引会导致索引扫描,而第一个索引会导致索引搜索?键的顺序有什么不同?

And*_*mar 5

第二个索引以电子邮件字段开头,但您没有过滤电子邮件.这使得索引无用.

索引通常是允许您进行二分查找b树.b树按其索引字段排序.因此,如果您知道第一个字段,则可以快速查找.在第一个字段的相同值内,您可以非常快速地查找第二个字段.

这就像一本按姓氏排序的电话簿.您无法使用它来搜索特定的电话号码.