Monday, February 10, 2014

Locking In SQL Server

Locking

Locking is a part of SQL Server operations. When a row is read by a query, a lock will be placed on that row to prevent any modifications which reading. If we issue an update statement on a single row, a lock will be placed on that row to prevent reading that data which is being updated. Different types of locks issued by SQL Server DB engine to determine how the resources can be accessed by concurrent transactions.

The main resources that SQL Server can lock are a row, a page, a table, there are other locks as well such as Database and Extent but these locks will have little effect on user experience with the Server. Extent locks are used with allocating new extents to get more pages for an index or tables, SQL Server uses database lock to calculate when a database is in use by one ore more users.

SQL Server locks resources using different lock modes that determine how the resources can be accessed by concurrent transactions. SQL Server uses these resource lock modes:

SQL Server has two levels of locking,

Page Level Locks & Table Level Locks

Page Level Locks are less restrictive when compared to table level locks. Page Level lock locks all rows in a page, whereas table level lock locks all rows in the table. SQL Server tries to use page level lock as much as possible by providing data to concurrent sessions to improve concurrency.

Table Level locks are being placed by SQL Server when large amount of table being utilized or most of the table pages will be accessed by the transaction, If UPDATE or DELETE has no useful index then it does a table scan and places a table lock, Sometimes If UPDATE or DELETE statement uses index and it was trying to acquire many page locks or it reaches locks threshold then it escalates to table lock. 

Shared (S), Update (U), Exclusive (X), Intent, Schema, Intent (I), Intent Shared (IS), Intent Exclusive(IX), Shared with Intent Exclusive (SIX) and Bulk Update (BU).

No comments: