We have a table (T) with ~3 million rows and just two INT columns (ID1 and ID2), which together are set as a composite clustered key.
Early in a stored procedure we create a table variable (@A) which consists of a list of INTs.
The slow query is the following
SELECT T.ID1, T.ID2
FROM T
INNER JOIN @A AS A
ON A.ID = T.ID1
@A will have just a few hundred rows, and T contains a few million rows. The problem is that T gets a scan count of several hundred. I don't know how to make that go away.
I have tried to create another index on T with column ID1 and ID2 included, but it does not help (the execution planner shows that the new index is used).
What can be done to reduce the scan count on table T?
(We are using SQL Server 2014, Web Edition)
Try creating an included (covering index):
create index idx_t_id1 on t(id1) include id2
This will allow your query to find everything it needs in the index pages and will not have to search in the main table. By the way is there a clustered index on table t?
You could try phrasing the query like this:
select a.id as id1,
(select t.id2
from t
where t.id1 = a.id
) as id2
from @a a;
This should scan @a
and use the index for the lookup.
Two notes:
cross apply
instead. You should try temp table (#table) instead of table var (@table). SQL Server Always estimate @table as 1 row table and this could impact you query performance a lot. Another benefit to use #table is that you can create index on that;)
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.