Thursday, October 25, 2007

SQL--Lock vs. Latch

Both lock and latch provide concurrency; at same time lock and latch maintain data consistency and integrity. Locking maintains the transactional integrity of the data while latching maintains the physical integrity of the data in memory.
Latch is a lock but with short period. Latch applies only to the page in RAM (data cache). Whereas lock applies to both RAM pages and stable media (storage).

Example

assume the following transaction affects only page 150. There is no index in the table.

BEGIN TRANSACTION
INSERT INTO tblTest VALUES (1)
COMMIT TRANSACTION

When SQL Server executes the statement: INSERT INTO tblTest VALUES(1), the following events occur:
  1. Page 150 is not currently present in the SQL Server cache so data page 150 is retrieved into the SQL Server data cache.
  2. Appropriate locks for the transaction are obtained and the page is latched.
  3. An Insert log record is built and added to the log cache.
  4. A new row is added to the data page and the page is marked dirty.
  5. The latch is released. All changes remain in volatile storage.

When SQL Server executes the statement: COMMIT TRANSACTION, transactional locks are released and the batch is considered complete.

If there are many statements in the transaction, many latches are obtained and released. SQL Server holds the latch for only the time necessary to perform the physical changes on the page. Depending on how many pages or tables are affected, the appropriate lock type is established to protect the row, range, page, or table as necessary through entire transaction period.