SQL Server Transaction Management Denise McInerney San Francisco SQL Server User Group April 9, 2008
Introduction What is a transaction Auto-commit Explicit transactions Nested transactions Catching errors Coding efficient transactions Isolation levels Conclusion Agenda
Introduction 10 years SQL Server DBA MCDBA/MCTS Web-based OLTP applications Focus on performance tuning Development DBA  www.intuitmarket.com PASS volunteer Women in Technology SIG Chairperson
Single, logical unit of work Sequence of operations Dictated by business rules Debit/credit Order header/order detail Why do we care? Data integrity Performance What is a transaction?
A tomicity All or Nothing; everything commits, or everything rolls back C onsistency All constraints and rules are honored and all data structures are intact, even if system fails ACID  Properties
ACID Properties continued I solation Concurrent transactions are kept separate, aka “serialized” Separate transactions never see data in an intermediate state Managed with locking D urability After commit, effects of transaction persist even if system fails
Default mode for SQL Server Every T-SQL command that is successfully completed commits If command encounters an error, transaction is rolled back Over-ridden with explicit transaction BEGIN TRAN Auto-Commit
Defined by the user Automatically abort only in case of  fatal  error TSQL Begin Tran Commit Tran/Commit Work Rollback Tran/Rollback Work OLEDB  ITransactionLocal::StartTransaction  ITransaction::Commit/ITransaction::Abort  ADO.NET SqlConnection object  BeginTransaction Commit()/Rollback()  ADO Connection object BeginTrans CommitTrans/Rollbacktrans Explicit Transactions
TSQL Transaction DEMO
Crucial to managing transactions properly In TSQL Check @@ERROR System error message True for SQL command immediately proceeding Pass back to calling program and take action Take action in SQL code Return user-defined error message via RAISERROR Store in sysmessages Build dynamically Can be logged Can take parameters TRY…CATCH SET XACT_ABORT ON Provides protection, but silently Errors During Transactions
Error Handling DEMO
Possible to nest transaction blocks BUT! Committing inner transactions  is ignored Only outermost COMMIT will have effect ROLLBACK will rollback all levels @@TRANCOUNT Returns nesting level of current transaction block Each BEGIN TRAN increments by 1 COMMIT decrements by 1 ROLLBACK decrements to 0 Nested Transactions
Nested Transaction DEMO
Requires planning Keep as short as possible Access the least amount of data possible Do not wait for user input during a transaction Make intelligent use of isolation levels Coding Efficient Transactions
Isolation Levels Read Uncommitted aka (NOLOCK) Does not issue shared lock, does not honor exclusive lock Rows can be updated/inserted/deleted before transaction ends Least restrictive Read Committed SQL Server default Holds shared lock Cannot read uncommitted data, but data can be changed before end of transaction, resulting in nonrepeatable read or phantom rows
Isolation Levels continued Repeatable Read Locks data being read, prevents updates/deletes New rows can be inserted during transaction, will be included in later reads Serializable aka HOLDLOCK on all tables in SELECT Locks  range  of data being read, no modifications are possible  Prevents updates/deletes/inserts Most restrictive
Isolation Level DEMO
Isolation Levels Summary From Books Online “Managing Concurrent Data Access” No No No Serializable Yes No No Repeatable Read Yes Yes No Read committed Yes Yes Yes Read Uncommitted Phantom Rows Non-Repeatable Read Dirty Read Isolation Level
Isolation Levels Added in SS2005 READ_COMMITTED_SNAPSHOT New implementation of READ COMMITTED Uses row versioning instead of locking ALTER DATABASE option When turned ON, transactions setting the read committed isolation level use row versioning SNAPSHOT Uses row versioning instead of locking Only recognize data modifications that were committed before the start of the transaction Data modifications made by others after start of transaction are ignored Both Use TEMPDB heavily Minimize contention Provide read consistency
Snapshot Isolation DEMO
Snapshot Isolation Summary From Books Online “Row Versioning-based Isolation Levels in the Database Engine” Uses row versions to select rows to update. Tries to acquire an exclusive lock on the actual data row to be modified, and if the data has been modified by another transaction, an update conflict occurs and the snapshot transaction is terminated. Reverts from row versions to actual data to select rows to update and uses update locks on the data rows selected. Acquires exclusive locks on actual data rows to be modified. No update conflict detection. How updates are handled. Integrated support. Cannot be disabled. None. Update conflict detection. All data that was committed before the start of each transaction. All data that was committed before the start of each statement. The version of data read by statements. Requires the execution of SET TRANSACTION ISOLATION LEVEL to specify the SNAPSHOT isolation level before the start of the transaction. Use the default read-committed isolation level, or run the SET TRANSACTION ISOLATION LEVEL statement to specify the READ COMMITTED isolation level. This can be done after the transaction starts. How a session requests the specific type of row versioning. ALLOW_SNAPSHOT_ISOLATION READ_COMMITTED_SNAPSHOT The database option that must be set to ON to enable the required support. Snapshot isolation level  Read-committed snapshot isolation level  Property
Conclusion Transaction management crucial  Guaranteeing data integrity Performance Understand how transactions work Understand what’s acceptable for your system Choose appropriate isolation level Assume nothing! DBA & developer collaboration key Email: denise.mcinerney@sqlpass.org

SQL Server Transaction Management

  • 1.
    SQL Server TransactionManagement Denise McInerney San Francisco SQL Server User Group April 9, 2008
  • 2.
    Introduction What isa transaction Auto-commit Explicit transactions Nested transactions Catching errors Coding efficient transactions Isolation levels Conclusion Agenda
  • 3.
    Introduction 10 yearsSQL Server DBA MCDBA/MCTS Web-based OLTP applications Focus on performance tuning Development DBA www.intuitmarket.com PASS volunteer Women in Technology SIG Chairperson
  • 4.
    Single, logical unitof work Sequence of operations Dictated by business rules Debit/credit Order header/order detail Why do we care? Data integrity Performance What is a transaction?
  • 5.
    A tomicity Allor Nothing; everything commits, or everything rolls back C onsistency All constraints and rules are honored and all data structures are intact, even if system fails ACID Properties
  • 6.
    ACID Properties continuedI solation Concurrent transactions are kept separate, aka “serialized” Separate transactions never see data in an intermediate state Managed with locking D urability After commit, effects of transaction persist even if system fails
  • 7.
    Default mode forSQL Server Every T-SQL command that is successfully completed commits If command encounters an error, transaction is rolled back Over-ridden with explicit transaction BEGIN TRAN Auto-Commit
  • 8.
    Defined by theuser Automatically abort only in case of fatal error TSQL Begin Tran Commit Tran/Commit Work Rollback Tran/Rollback Work OLEDB ITransactionLocal::StartTransaction ITransaction::Commit/ITransaction::Abort ADO.NET SqlConnection object BeginTransaction Commit()/Rollback() ADO Connection object BeginTrans CommitTrans/Rollbacktrans Explicit Transactions
  • 9.
  • 10.
    Crucial to managingtransactions properly In TSQL Check @@ERROR System error message True for SQL command immediately proceeding Pass back to calling program and take action Take action in SQL code Return user-defined error message via RAISERROR Store in sysmessages Build dynamically Can be logged Can take parameters TRY…CATCH SET XACT_ABORT ON Provides protection, but silently Errors During Transactions
  • 11.
  • 12.
    Possible to nesttransaction blocks BUT! Committing inner transactions is ignored Only outermost COMMIT will have effect ROLLBACK will rollback all levels @@TRANCOUNT Returns nesting level of current transaction block Each BEGIN TRAN increments by 1 COMMIT decrements by 1 ROLLBACK decrements to 0 Nested Transactions
  • 13.
  • 14.
    Requires planning Keepas short as possible Access the least amount of data possible Do not wait for user input during a transaction Make intelligent use of isolation levels Coding Efficient Transactions
  • 15.
    Isolation Levels ReadUncommitted aka (NOLOCK) Does not issue shared lock, does not honor exclusive lock Rows can be updated/inserted/deleted before transaction ends Least restrictive Read Committed SQL Server default Holds shared lock Cannot read uncommitted data, but data can be changed before end of transaction, resulting in nonrepeatable read or phantom rows
  • 16.
    Isolation Levels continuedRepeatable Read Locks data being read, prevents updates/deletes New rows can be inserted during transaction, will be included in later reads Serializable aka HOLDLOCK on all tables in SELECT Locks range of data being read, no modifications are possible Prevents updates/deletes/inserts Most restrictive
  • 17.
  • 18.
    Isolation Levels SummaryFrom Books Online “Managing Concurrent Data Access” No No No Serializable Yes No No Repeatable Read Yes Yes No Read committed Yes Yes Yes Read Uncommitted Phantom Rows Non-Repeatable Read Dirty Read Isolation Level
  • 19.
    Isolation Levels Addedin SS2005 READ_COMMITTED_SNAPSHOT New implementation of READ COMMITTED Uses row versioning instead of locking ALTER DATABASE option When turned ON, transactions setting the read committed isolation level use row versioning SNAPSHOT Uses row versioning instead of locking Only recognize data modifications that were committed before the start of the transaction Data modifications made by others after start of transaction are ignored Both Use TEMPDB heavily Minimize contention Provide read consistency
  • 20.
  • 21.
    Snapshot Isolation SummaryFrom Books Online “Row Versioning-based Isolation Levels in the Database Engine” Uses row versions to select rows to update. Tries to acquire an exclusive lock on the actual data row to be modified, and if the data has been modified by another transaction, an update conflict occurs and the snapshot transaction is terminated. Reverts from row versions to actual data to select rows to update and uses update locks on the data rows selected. Acquires exclusive locks on actual data rows to be modified. No update conflict detection. How updates are handled. Integrated support. Cannot be disabled. None. Update conflict detection. All data that was committed before the start of each transaction. All data that was committed before the start of each statement. The version of data read by statements. Requires the execution of SET TRANSACTION ISOLATION LEVEL to specify the SNAPSHOT isolation level before the start of the transaction. Use the default read-committed isolation level, or run the SET TRANSACTION ISOLATION LEVEL statement to specify the READ COMMITTED isolation level. This can be done after the transaction starts. How a session requests the specific type of row versioning. ALLOW_SNAPSHOT_ISOLATION READ_COMMITTED_SNAPSHOT The database option that must be set to ON to enable the required support. Snapshot isolation level Read-committed snapshot isolation level Property
  • 22.
    Conclusion Transaction managementcrucial Guaranteeing data integrity Performance Understand how transactions work Understand what’s acceptable for your system Choose appropriate isolation level Assume nothing! DBA & developer collaboration key Email: denise.mcinerney@sqlpass.org