简体   繁体   中英

Query not doing index seek or scan

I am fairly new to Indexes. I have table following table [FORUM1]

    [msg_id] [int] IDENTITY(1,1) NOT NULL,
    [cat_id] [int] NULL,
    [msg_title] [nvarchar](255) NULL

And have created a non clustered index

CREATE NONCLUSTERED INDEX catindex ON forum1(cat_id)

Now when i run this simple query, i can see index is not being used

SELECT msg_title FROM forum1 where cat_id=4

Index only gets called if i create CI and include the MSG_TITLE fld. But the issue is that i have to run many more similar queries on actually table like date=something, userid=20, status=1. So including columns in every index doesn't good to me .

执行计划屏幕截图

The msg_title is not contained in the index -> any value found in the non-clustered index will need a key lookup into the actual data pages, which is an expensive operation - so therefore, most likely, a table scan is quicker. Plus: the "table scan" indicates you have a heap - a table without a clustered index - which is a bad thing (most of the time) to begin with. Why don't you have a clustered index?

You can fix this by eg including the msg_title in your index:

CREATE NONCLUSTERED INDEX catindex 
ON forum1(cat_id) INCLUDE(msg_title)

and now, I'm pretty sure, SQL Server will use that index (since it can find all the data needed for the query in the index structure - the index is said to be a covering index ). The benefit here is: the extra column is only included in the leaf level of the index, so it makes the index only minimally bigger. Yet, it can lead to the index being used just all that more often. Well worth it!

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