I have a database on which select, update and insert queries are run. At times it gave me deadlocks (key locks) while updating and selecting data from the table, it considered the select query to be the victim. After some research and examination of our queries, we added and removed certain indexes that would help in speeding up the queries. Now, after adding the indexes, I'm getting deadlocks (page locks) for the same select and update query. Why is this happening? Is there any way to reduce these deadlocks?
Deadlock is between
SELECT COUNT(*) AS [Id Count ] FROM TABLE WHERE ( ([name]) = 'abc' AND (([Id]) <> '4284167' OR [Id] IS NULL) AND ([Stage] <> 0) AND ( ([Result]) = 'P' OR ([Result] IS NULL OR [Result] = '') OR ([Result]) = 'Delay' ) ) ...and
UPDATE TABLE SET [Result] = 'C' WHERE [Id] = 4284027 AND [Result] = 'P' Before altering the indexes, these queries were deadlocked because of keylocks(Index).
Indexes involved due to deadlocks with Keylock
Primary key, Non Clustered on column
ID
Clustered Index on columns
[Date][Time]
Non Clustered index on column
[Result]
Non Clustered index on column
[Stage]
Objects that were involved in deadlocks were the Clustered Index on [Date][Time] and the Non Clustered Index on [Result].
Indexes involved due to deadlocks with PageLocks
Primary Key, Clustered Index on column
ID
Non Clustered Index on columns
[Date][Time]
Non Clustered Index on columns:
ReffdDateTimetypeQueryResultStageAnswer(Included Column)FollowUpdate(Included Column)
Objects that were involved in deadlocks were Primary Key on [Id] and a Page
Query Plan for Keylock - Pagelock
- https://www.brentozar.com/pastetheplan/?id=ByK26kfyj[1]
- https://www.brentozar.com/pastetheplan/?id=SyzygeGJi
Query Plan for Pagelock - Pagelock
1.https://www.brentozar.com/pastetheplan/?id=S1wSNXzkj 2.https://www.brentozar.com/pastetheplan/?id=H1WhXmGys
INCLUDEtheResultcolumn, also you probably want to change index #4 to(name, Result) INCLUDE (Id, Stage, SomeMoreColumnsHere)