Showing posts with label Locking. Show all posts
Showing posts with label Locking. Show all posts

Wednesday, 3 January 2007

SQL Server Locking Modes

SQL Server supports acquires different locking modes depends on the type of operation we perform on the Data. The list of locking modes acquired by SQL Sever for each type of operation is given below.

Shared Lock

  • Acquired for reading data.
  • Other transactions can acquire shared lock on the same resources.
  • No other transaction can modify data.

Exclusive Lock

  • Acquired to modify data (INSERT, DELETE and MODIFY).
  • No other transaction can modify or read data.

Update Lock

  • Acquired to execute a data modification operation but first needs to search the table.
  • No other transaction can acquire an update lock or an exclusive lock.

Schema Lock

  • Modification lock - Acquired for DDL queries.
  • Stability lock – Acquired when compiling queries.

Bulk Update Lock

  • Acquired for performing bulk copy of data

Tuesday, 2 January 2007

SQL Server Locking Tips

SQL Server uses locking to support concurrency of data in Multi user environment .The locking can be applied to the Database resources such ROWS, INDEX, PAGE, EXTENT, TABLE or the Database itself. SQL Server automatically escalates row, key, or page locks to table locks as appropriate to protects system resources and increases efficiency. Locking at smaller granularity increases concurrency but create high overhead on the Database on the other hand Locking at larger granularity reduces overhead but expense in terms of concurrency.The best practice is to avoid lock escalation .The following tips can be useful to minimize locking

  • Keep all Transact-SQL transactions as short as possible.
  • Avoid interleaving reads and database changes in same transaction.
  • Do all the conditional logic and variable assignment outside of a Transaction.
  • Encapsulate all transactions within stored procedures.
  • Avoid Transact-SQL statements inside the transaction that affect large numbers of rows at once.
  • Although WHILE nesting transactions is perfectly legal avoid using inside the transactions.
  • For lookup tables consider altering the default lock level for the table (Use SP_INDEXOPTION).
  • Do not create temporary tables from within a stored procedure that is invoked by the INSERT INTO #temp EXECUTE statement.