简体   繁体   中英

SQL Server: SQL request returns after writing to t-log or after b-tree is updated

For mutating SQL statements (insert, update, delete), when does SQL returns response to client?

Is this

  1. after the change has been written to the transaction log but b-tree hasn't been updated, OR
  2. after the change has been written to the transaction log and b-tree index has been updated

I am confused because in order for seek operations to work, the b-tree index has to be up-to-date, so I would imagine #2 is correct.

But transaction log is also used to recover from crash. If SQL crashes in the middle of a mutating request, the client never receives success code anyway and the client can retry.

So in what scenario does the t-log provides disaster recovery, assuming there is no replication involved?

It is important to understand the step by step process of SQL Server making changes to the stored data.

SQL Server uses Write-Ahead Logging algorithm to make any changes to the stored data in SQL Server. Following are the steps taken to make sure each statement/transaction maintains the ACID property of SQL Server.

  1. A copy of the page(s) [Rows] that needs updating are loaded into buffer cache.ie all the related pages of the B-Tree and any non-clustered indexes(if any).
  2. Changes are made to the copy of pages in the buffer cache.
  3. At this point, the page is marked dirty.
  4. An entry is made in the Transaction log for each change made to the page in buffer cache.
  5. Return response to the client about the successful/unsuccessful change.

  6. Finally a checkpoint is issued (this could happen before the user response is sent or after, as this is a separate process), the process scans the buffer cache for dirty pages, write the changes to the disk and remove the dirty page records from the cache (process also knows as flushing the pages ). And only at this stage the changes are actually written to the disk.

The checkpoint process is the one that makes sure that no dirty pages ever get flushed. This process guarantees the ACID property of transactions in the SQL Server.

If the page has only been modified in the buffer cache and has not been written to the disk(dirty page) , at this point if SQL Server crashes, after coming back online SQL server will decide whether to roll forward or rollback the transaction but data is always left in the consistent state.

If the above mention process fails anywhere in the middle and cannot complete the whole process for any reason, SQL Server marks the data pages as suspect (database corruption) which does happen sometimes but not very often (at this point you will see your DBA sweating). But you shouldn't worry about this unless you are the DBA :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM