Wrong Query Execution Plan

Marios Pavlidis 51 Reputation points
2021-06-29T12:00:35.517+00:00

Hi,

A query using clustered index key has performed an index scan instead of seek. The query was captured by heavy queries Extended Event and had Physical reads that matched the size of the table. Also the execution time was several minutes.

Statement is similar to the following:
(@P1 bigint)INSERT INTO ProductionTable WITH(ROWLOCK) ("ALL", "THE", "COLUMNS" FROM (DELETE FROM HistoricTable WITH(ROWLOCK) OUTPUT deleted.* WHERE ClusterKey = @P1) AS deleted

Both tables have the same Cluster key and it is used to fetch the row.

We actually retrieve a row from the historic table to the production one.

Running the query will execute in milliseconds and use clustered index seek ( as it should). It once happened (until now) to scan the table and I cannot imagine why.

  • Is there something special I miss when using output ? Should we change the statement to 2 simple insert , delete statements?
  • There is a possibility for statistics were updated during the execution time. Is there any way this could impact the optimizer although we are using the cluster key in the query?

Thank you in advance,
Marios

SQL Server | Other
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Erland Sommarskog 128.7K Reputation points MVP Volunteer Moderator
    2021-06-29T13:05:16.793+00:00

    This is very hard to answer without seeing the actual execution plan and knowing the exact tables and indexes. And for that matter the exact statement.

    But I will ask one question: is ClusterKey a unique key? If it is non-unique, it is possible that the optimizer could get the idea that it's cheaper to scan a non-clustered index, because it thinks the value for which the plan has been sniffed would hit many rows.

    I fail to see that the OUTPUT clause and the composable DML could have anything to do with it.


  2. Erland Sommarskog 128.7K Reputation points MVP Volunteer Moderator
    2021-06-30T08:33:27.68+00:00

    It the key is unique, the only answer I can think of things like someone was fooling around and had dropped the clustered index at the time, or that there were some data type mismatch that precluded a seek of the index.

    More realistically, I think we have to close this as unresolved, as there is not enough information to tell what may have happened.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.