I am using SQL Server 2008, RTM. I have a simple table defined as
create table t(id integer not null primary key)
This table has 50,000 records, just in case. When I issue an update transaction like
begin transaction
Update t
set id=50001
where id=5;
with no commit/rollback, it shows me one row affected. When I take a look at the result of the sp_locks, I and see there are two X locks on the KEY type granted, the Resource values for them are different from each other, the spid is the same.
Why there are two X locks on the key while there is only one row updated? Thanks.
Best Answer
Because you're taking one key value, and assigning it another key value.
It's 2017, so I'm not going to use sp_lock. I'm going to use sp_WhoIsActive.
If we run it like this:
EXEC sp_WhoIsActive @get_locks = 1
we can get lock information.If we update one key value:
The lock information looks like this:
Two key locks! One key lock to get the key value we're modifying, and one lock to reserve the key value we're modifying it to.
If we modify two values...
We end up with four key locks. This pattern will continue if we do 3 or 4. There will be two key locks for each ID touched.
Hitting three values:
Hitting four values:
At least up until we modify everything.
Then the lock type changes!
This is due to the magic of the split, sort, and collapse operations, which you can see in the query plan here.
Hope this helps!