Will SQL Server use a compound index when only a single column is in the WHERE clause?

萝らか妹 提交于 2019-12-05 06:38:09

can/does SQL Server use the index (LastName, FirstName) for queries on just LastName as well as queries on both?

Yes, the database will use the index (LastName, FirstName) for queries on LastName. It will not use this index for queries only on FirstName though.

Does it store compound index parts left-to-right or right-to-left?

Storage is in a B-Tree. Whether you think of it as being stored right-to-left or left-to-right is just a useful visualization aid, and not related to the actual data storage.

Yes, if you query on LastName alone it should use the (LastName, FirstName) index. So it would be used both when querying by LastName alone, or LastName and FirstName together.

General guideline is to ensure the column with the greatest selectivity appears first in the compound index as this provides the most benefit/narrows the resultset down sooner before the following, less selective columns.

Depending on the actual query you're sending, a composite index on two columns may be used even if you search for the 2nd column only. However, you won't get an index seek, but most likely an index scan. If this is "good enough" for you, depends on your specific environment. Indexing is more of a art than a science and a lot of different factors influence your decision on how to index a table. It's always a trade-off as having too many indices on a table is just as bad as having too few. Make sure that your most crucial queries are covered well and then decide on a case by case basis whether any additional index is worth its cost.

Also, as it hasn't been mentioned yet and provided you're at least on SQL Server 2005: Let me throw in the INCLUDE clause for nonclustered indices. It is an overlooked, but really useful addition to any indexing strategy.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!