简体   繁体   English

SQL Server:相同列性能的多个索引

[英]SQL Server: multiple index for the same columns performance

I have a table Person with columns personId, teamId, departmentId , among others. 我有一个表Person ,其中包括personId, teamId, departmentId列。 Most of the query use a combination of these columns on the where. 大多数查询在where上使用这些列的组合。

Example

Select * from .. where personId = 2 and departementId = 1
Select * from .. where personId = 2 and teamId = 1   
Select * from .. where departmentId = 2 and teamId = 1   

My question is, should I create an index for each of these column individually? 我的问题是,是否应该分别为每个列创建索引?

The quick answer is yes - just add an index for each column. 快速答案是肯定的-只需为每列添加一个索引。 Its not likely to be the most optimal solution but in most cases it won't be that far off and it probably won't cause any harm unless you already have many indexes on that table. 它可能不是最佳解决方案,但在大多数情况下,相距不远,除非在该表上已有许多索引,否则它不会造成任何危害。

The only slightly longer answer is that you should test your query against representative data - The SQL Server Database Engine Tuning Advisor can suggest indexes for you, but only you can check to make sure that these indexes are suitable for other all queries (including inserts / updates) - you need to balance the performance of reads against the cost of maintaining those indexes when writing to the database (as well as any storage / space constraints). 唯一稍长一点的答案是,您应该针对代表性数据 测试查询-SQL Server数据库引擎优化顾问可以为您建议索引,但只有您可以检查以确保这些索引适合其他所有查询(包括插入/更新)-您需要在读取性能与写入数据库时​​维护这些索引的成本(以及任何存储/空间限制)之间取得平衡。

Either one per column: SQL Server will use Index Intersection 每列任一:SQL Server将使用索引交集

Or, try something like this: three composite indexes. 或者,尝试如下操作:三个复合索引。 The first column of each is useful as a "single column index" too. 每个字段的第一列也可用作“单列索引”。

  • departmentId, teamId, personId
  • personId, departmentId, teamId
  • teamId, personId, departmentId

Notes: 笔记:

  • WHERE clause order doesn't matter WHERE子句顺序无关紧要
  • SELECT * is bad SELECT *不好

Also, it's a good idea to have foreign key columns indexed and either strategy will work 另外,对外键列进行索引也是一个好主意,任何一种策略都可以工作

I would not, as a rule, create 3 indexes on the variations of field usage, but that is just a general rule. 通常,我不会根据字段用法的变化创建3个索引,但这只是一条通用规则。

As far as the "how do I do this as a newbie" answer, I would create a workload and use the tuning advisor. 至于“我该如何做新手”答案,我将创建一个工作负载并使用调优顾问。 It is not an end all solution, and as someone learns more, they get beyond the wizard, but it is a good place to start with. 这不是最终的解决方案,随着人们的了解,他们超越了向导,但这是一个很好的起点。 Make sure you have a decent representative sample, as indexes can destroy performance on other queries, if done incorrectly. 确保您有一个不错的代表样本,因为索引做得不正确会破坏其他查询的性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM