简体   繁体   中英

In this demo,should I create a index on each column or just one Nonclustered index (Index Scan、Seek)

Test DDL:

CREATE TABLE TestTable([col1] varchar(2), [col2] varchar(2), [col3] varchar(2));   
INSERT INTO TestTable ([col1], [col2], [col3]) VALUES ('a1', 'b1', 'c1');

example1(just one Nonclustered Index):

Create Nonclustered Index Index_TestTable  on  TestTable ([col1], [col2], [col3]) ;

select  [col2], [col3] from TestTable
where  [col2] = 'b1'  ;

result:

Index Scan

example2(two Nonclustered Index):

Create Nonclustered Index Index_TestTable  on  TestTable ([col1], [col2], [col3]) ;
Create Nonclustered Index Index_TestTable2  on  TestTable ([col2], [col1], [col3]) ;
select  [col2], [col3] from TestTable
where  [col2] = 'b1'  ;

result:

Index Seek

Q. Should I create a index on each column or just one index?

ps. select .. where col1,col2,col3 's columns-order are random.

如果您总是要使用col2查询表,那么您需要在索引中包括col1和col3,您可以为col2创建一个索引,如下所示:

Create Nonclustered Index Index_TestTable  on  TestTable ([col2]) ;

You have not provided any information on why you need an index on those columns, but as a general rule of thumb, I can tell you that creating an index on every single column of your table is not the right approach.

Non-clustered index could improve your search performance but would have a negative impact on your insert/update/delete operation (and you could waste storage space).

If you add a new non-clustered index to the table, in practice a new table is created to maintain that index. For example if you create a non-clustered index on LastName column, then you would have a new table created to store a sorted list of LastName s with a pointer to the corresponding row. This could improve your performance if you are searching the table on LastName but it has a negative impact on your table update, because every time you update the table you need to update/sort the index too.

Non-clustered index should only be created on a column that you regularly search on.

I totally agree with Hooman's comments. However, I just want to explain the reason why you got Index Seek in example2 as follows:

Since TestTable only contains three columns which are all included in the non-clustered index, their order in the index caused the differences.

In example2, since index Index_TestTable2 has [col2] first, only a single seek is performed (based on where [col2] = 'b1' ). Therefore, if you remove index Index_TestTable in example2, you should still get Index Seek. please refer to here for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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