How transactions work A transaction groups a set of Transact-SQL statements so that they are treated as a unit. Either all statements in the group are.

Slides:



Advertisements
Similar presentations
Applied Database II Transactions In Database The ACID Test Atomicity The whole transaction or none of it Consistency Remains in a consistent state -
Advertisements

Transactions - Concurrent access & System failures - Properties of Transactions - Isolation Levels 4/13/2015Databases21.
Chapter 16 Concurrency. Topics in this Chapter Three Concurrency Problems Locking Deadlock Serializability Isolation Levels Intent Locking Dropping ACID.
1 Lecture 11: Transactions: Concurrency. 2 Overview Transactions Concurrency Control Locking Transactions in SQL.
What is a Transaction? A transaction is a logical logic of work A transaction may have one of two outcomes –When a transaction completes successfully,
Transactions and Locking Rose-Hulman Institute of Technology Curt Clifton.
Module 15: Managing Transactions and Locks. Overview Introduction to Transactions and Locks Managing Transactions SQL Server Locking Managing Locks.
Database Administration Chapter Six DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Transaction Management and Concurrency Control
Distributed DBMSPage © 1998 M. Tamer Özsu & Patrick Valduriez Outline Introduction Background Distributed DBMS Architecture Distributed Database.
Transaction Management and Concurrency Control
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 10 Transaction Management and Concurrency Control.
Database Administration Part 1 Chapter Six CSCI260 Database Applications.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 10 Transaction Management and Concurrency Control.
Chapter 5 Data Manipulation and Transaction Control Oracle 10g: SQL
Managing Concurrency in Web Applications. DBI 2007 HUJI-CS 2 Intersection of Concurrent Accesses A fundamental property of Web sites: Concurrent accesses.
Transaction Management and Concurrency Control
Transactions and Locks Lesson 22. Skills Matrix Transaction A transaction is a series of steps that perform a logical unit of work. Transactions must.
Managing Transaction and Lock Vu Tuyet Trinh Hanoi University of Technology 1.
1 Transactions BUAD/American University Transactions.
Stored Procedures, Transactions, and Error-Handling
Transactions Sylvia Huang CS 157B. Transaction A transaction is a unit of program execution that accesses and possibly updates various data items. A transaction.
BIS Database Systems School of Management, Business Information Systems, Assumption University A.Thanop Somprasong Chapter # 10 Transaction Management.
1cs Intersection of Concurrent Accesses A fundamental property of Web sites: Concurrent accesses by multiple users Concurrent accesses intersect.
Transaction processing Book, chapter 6.6. Problem: With a single user…. you run a query, you get the results, you run the next, etc. But database life.
Concurrency and Transaction Processing. Concurrency models 1. Pessimistic –avoids conflicts by acquiring locks on data that is being read, so no other.
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 136 Database Systems I SQL Modifications and Transactions.
Module 11 Creating Highly Concurrent SQL Server® 2008 R2 Applications.
Transactions and Locks A Quick Reference and Summary BIT 275.
© 2002 by Prentice Hall 1 Database Administration David M. Kroenke Database Concepts 1e Chapter 6 6.
Giovanni Chierico | May 2012 | Дубна Data Concurrency, Consistency and Integrity.
CSC271 Database Systems Lecture # 17. Summary: Previous Lecture  View updatability  Advantages and disadvantages of views  View materialization.
SQLintersection Understanding Transaction Isolation Levels Randy Knight Wednesday, 3:45-5:00.
CSC 411/511: DBMS Design Dr. Nan WangCSC411_L12_JDBC_MySQL 1 Transations.
1 Intro stored procedures Declaring parameters Using in a sproc Intro to transactions Concurrency control & recovery States of transactions Desirable.
A Guide to SQL, Eighth Edition Chapter Six Updating Data.
1 Advanced Database Concepts Transaction Management and Concurrency Control.
Module 11: Managing Transactions and Locks
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 10 Transaction Management and Concurrency Control.
10 Transaction Management and Concurrency Control MIS 304 Winter 2005.
©Bob Godfrey, 2002, 2005 Lecture 17: Transaction Integrity and Concurrency BSA206 Database Management Systems.
10 1 Chapter 10 - A Transaction Management Database Systems: Design, Implementation, and Management, Rob and Coronel.
IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server.
Copyright © 2003 – 2013 by Curt Hill Transaction Management An Overview.
Module 14: Managing Transactions and Locks. Overview Introducing Transactions and Locks Managing Transactions Understanding SQL Server Locking Architecture.
1 Transaction Processing Case Study. 2 Interaksi Proses There is table Sells(shop,beverage,price), and suppose that Joe’s Shop sells only Juice for $2.50.
In this session, you will learn to: Implement triggers Implement transactions Objectives.
Chapter 13 Managing Transactions and Concurrency Database Principles: Fundamentals of Design, Implementation, and Management Tenth Edition.
Locks, Blocks & Isolation Oh My!. About Me Keith Tate Data Professional for over 14 Years MCITP in both DBA and Dev tracks
SQL – Transactions in SQLite
Transaction Management and Concurrency Control
LAB: Web-scale Data Management on a Cloud
CS122 Using Relational Databases and SQL
Isolation Levels Understanding Transaction Temper Tantrums
Transaction & Record Scoping
On transactions, and Atomic Operations
Batches, Transactions, & Errors
Transactions, Locking and Query Optimisation
Chapter 10 Transaction Management and Concurrency Control
Outline Introduction Background Distributed DBMS Architecture
Understanding Transaction Isolation Levels
On transactions, and Atomic Operations
Batches, Transactions, & Errors
Objectives Define and describe transactions
Transactions and Concurrency
Database Administration
Isolation Levels Understanding Transaction Temper Tantrums
-Transactions in SQL -Constraints and Triggers
Transactions-Concurrency Problems
Transactions, Properties of Transactions
Presentation transcript:

How transactions work A transaction groups a set of Transact-SQL statements so that they are treated as a unit. Either all statements in the group are executed or no statements are executed. Server automatically manages all data modification commands, including single-step change requests, as transactions. By default, each insert, update, and delete statement is considered a single transaction.

How transactions work You can use the following commands to create transactions: begin transaction – marks the beginning of the transaction block. The syntax is: begin {transaction | tran} [transaction_name] transaction_name is the name assigned to the transaction. It must conform to the rules for identifiers. Use transaction names only on the outermost pair of nested begin/commit or begin/rollback statements.

Transaction Goals: ACID Atomic Transaction cannot be subdivided All parts must succeed or none may succeed Consistent All applicable constraints that are true before the transaction starts are also true after the transaction completes (example: referential integrity must be preserved) Isolated Changes resulting from the transaction are not visible to other users until the transaction completes Durable Changes resulting from the transaction are permanent and can't be undone (rolled back)

Transaction Processing Issues Problems arise when multiple users attempt to read from and write to the same records simultaneously Problems: Lost updates Dirty reads Nonrepeatable reads Phantom reads

Lost Updates Multiple transactions read a record and then update it. All updates except the last one are "lost". Example: Solution: Don't allow record to be updated with another uncommitted update pending 10:00 PM: Both partners open code file on server and store it on local machines 3:03 AM: Partner 1 finishes coding, uploads file to server, and goes home, satisfied that program is working. Partner 2 is playing video games. 4:17 AM: Partner 2, in a fit of guilt, looks at local program code, changes a few variable names and breaks what little was working, uploads it to server, then goes home. 8:00 AM: Professor looks at non-working code, thinks bad thoughts about team, and assigns low grade.

Dirty Reads "Dirty block": data block that contains uncommitted data "Dirty read": competing transaction reads a record that contains uncommitted data Problem occurs if uncommitted data is rolled back after the read

Dirty Reads Solution: Updates should not be visible to other connections until they are committed 10:00 PM: Partners finish project. Partner 1 wants to try to work a little longer and try to get extra credit points, although he's not sure he can do it. Partner 1 saves a backup copy of the working project but doesn't tell Partner 2 where it is. 3:03 AM: Partner 1 works on extra credit but can't get it working. Goes home in a Mt. Dew-induced haze, planning to turn in original (backup) copy. 7:45 AM: Partner 2 hands in assignment that contains non- working extra-credit code, not knowing it doesn't work. 8:00 AM: Professor grades non-working code, thinks bad thoughts about team, assigns low grade.

Nonrepeatable Read Occurs when a transaction reads the same record multiple times and gets different data each time Caused by other transactions updating the record between the reads

Phantom Reads Occurs when a query in a transaction reads a group of records multiple times and sees different records Caused by other transactions simultaneously inserting, updating, or deleting records so they now satisfy the query search condition.

Auto Commit Transactions By default, each Transact-SQL command is its own transaction. These are known as automatic (or autocommit) transactions. They are begun and committed by the server automatically. You can think of an automatic transaction as a Transact-SQL statement that's ensconced between a BEGIN TRAN and a COMMIT TRAN. If the statement succeeds, it's committed. If not, it's rolled back.

User-Defined Transactions User-defined transactions are the chief means of managing transactions in SQL Server applications. A userdefined transaction is user-defined in that you control when it begins and when it ends. The BEGIN TRAN, COMMIT TRAN, and ROLLBACK TRAN commands are used to control user-defined transactions. Here's an example:

User-Defined Transactions SELECT TOP 5 title_id, stor_id FROM sales ORDER BY title_id, stor_id BEGIN TRAN DELETE sales SELECT TOP 5 title_id, stor_id FROM sales ORDER BY title_id, stor_id GO ROLLBACK TRAN SELECT TOP 5 title_id, stor_id FROM sales ORDER BY title_id, stor_id

User-Defined Transactions title_id stor_id BU BU BU BU (5 row(s) affected) (25 row(s) affected) title_id stor_id (0 row(s) affected) title_id stor_id BU BU BU BU (5 row(s) affected)

Transaction Isolation Levels SQL Server supports four transaction isolation levels. A transaction's isolation level controls how it affects, and is affected by, other transactions. The trade-off is always one of data consistency vs. concurrency. Selecting a more restrictive TIL increases data consistency at the expense of accessibility. Selecting a less restrictive TIL increases concurrency at the expense of data consistency. The trick is to balance these opposing interests so that the needs of your application are met. Use the SET TRANSACTION ISOLATION LEVEL command to set a transaction's isolation level. Valid TILs include READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, and SERIALIZABLE.

Transaction Isolation Levels READ UNCOMMITTED: It is the least restrictive of SQL Server's four TILs. It permits dirty reads (reads of uncommitted changes by other transactions) and nonrepeatable reads (data that changes between reads during a transaction). To see how READ UNCOMMITTED permits dirty and nonrepeatable reads, run the following queries simultaneously:

Transaction Isolation Levels READ UNCOMMITTED: EXAMPLE: -- Query 1 SELECT TOP 5 title_id, qty FROM sales ORDER BY title_id, stor_id BEGIN TRAN UPDATE sales SET qty=0 SELECT TOP 5 title_id, qty FROM sales ORDER BY title_id, stor_id WAITFOR DELAY '00:00:05' ROLLBACK TRAN SELECT TOP 5 title_id, qty FROM sales ORDER BY title_id, stor_id Query 2 SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED PRINT 'Now you see it…' SELECT TOP 5 title_id, qty FROM sales WHERE qty=0 ORDER BY title_id, stor_id IF BEGIN WAITFOR DELAY '00:00:05' PRINT '…now you don''t' SELECT TOP 5 title_id, qty FROM sales WHERE qty=0 ORDER BY title_id, stor_id END

Transaction Isolation Levels READ UNCOMMITTED EXAMPLE: Now you see it… title_id qty BU BU BU (5 row(s) affected) …now you don't title_id qty While the first query is running (you have five seconds), fire off the second one, and you'll see that it's able to access the uncommitted data modifications of the first query. It then waits for the first transaction to finish and attempts to read the same data again. Since the modifications were rolled back, the data has vanished, leaving the second query with a nonrepeatable read.

Transaction Isolation Levels READ COMMITTED: READ COMMITTED is SQL Server's default TIL, so if you don't specify otherwise, you'll get READ COMMITTED. READ COMMITTED avoids dirty reads by initiating share locks on accessed data but permits changes to underlying data during the transaction, possibly resulting in nonrepeatable reads and/or phantom data. To see how this works, run the following queries simultaneously:

Transaction Isolation Levels READ COMMITTED: EXAMPLE: - Query 1 SET TRANSACTION ISOLATION LEVEL READ COMMITTED BEGIN TRAN PRINT 'Now you see it…' SELECT TOP 5 title_id, qty FROM sales ORDER BY title_id, stor_id WAITFOR DELAY '00:00:05' PRINT '…now you don''t' SELECT TOP 5 title_id, qty FROM sales ORDER BY title_id, stor_id GO ROLLBACK TRAN -- Query 2 SET TRANSACTION ISOLATION LEVEL READ COMMITTED UPDATE sales SET qty=6 WHERE qty=5

Transaction Isolation Levels READ COMMITTED EXAMPLE: title_id qty BU BU BU BU BU …now you don't title_id qty BU BU BU BU BU As in the previous example, start the first query, then quickly run the second one simultaneously (you have seconds). In this example, the value of the qty column in the first row of the sales table changes between reads during the first query—a classic no repeatable read.

Transaction Isolation Levels REPEATABLE READ: REPEATABLE READ initiates locks to prevent other users from changing the data a transaction accesses but doesn't prevent new rows from being inserted, possibly resulting in phantom rows appearing between reads during the transaction. Here's an example (as with the other examples, start the first query; then run the second one simultaneously—you have five seconds to start the second query):

Transaction Isolation Levels REPEATABLE READ: EXAMPLE: -- Query 1 SET TRANSACTION ISOLATION LEVEL REPEATABLE READ BEGIN TRAN PRINT 'Nothing up my sleeve…' SELECT TOP 5 title_id, qty FROM sales ORDER BY qty WAITFOR DELAY '00:00:05' PRINT '…except this rabbit' SELECT TOP 5 title_id, qty FROM sales ORDER BY qty GO ROLLBACK TRAN -- Query 2 SET TRANSACTION ISOLATION LEVEL REPEATABLE READ INSERT sales VALUES (6380, ,GETDATE(),2,'USG- Whenever','PS2091')

Transaction Isolation Levels REPEATABLE READ EXAMPLE: Nothing up my sleeve… title_id qty PS BU PS MC BU …except this rabbit title_id qty PS PS BU PS As you can see, a new row appears between the first and second reads of the sales table, even though REPEATABLE READ has been specified. Though REPEATABLE READ prevents changes to data it has already accessed, it doesn't prevent the addition of new data, thus introducing the possibility of phantom rows.

Transaction Isolation Levels SERIALIZABLE: SERIALIZABLE prevents dirty reads and phantom rows by placing a range lock on the data it accesses. It is the most restrictive of SQL Server's four TILs. It's equivalent to using the HOLDLOCK hint with every table a transaction references. Here's an example (delete the row you added in the previous example before running this code):

Transaction Isolation Levels SERIALIZABLE EXAMPLE: SET TRANSACTION ISOLATION LEVEL SERIALIZABLE BEGIN TRAN PRINT 'Nothing up my sleeve…' SELECT TOP 5 title_id, qty FROM sales ORDER BY qty WAITFOR DELAY '00:00:05' PRINT '…or in my hat' SELECT TOP 5 title_id, qty FROM sales ORDER BY qty ROLLBACK TRAN -- Query 2 BEGIN TRAN SET TRANSACTION ISOLATION LEVEL SERIALIZABLE -- This INSERT will be delayed until the first transaction completes INSERT sales VALUES (6380, ,GETDATE(),2,'USG-Whenever','PS2091') ROLLBACK TRAN

Transaction Isolation Levels SERIALIZABLE EXAMPLE: Nothing up my sleeve… title_id qty PS BU PS MC BU …or in my hat title_id qty PS BU PS MC BU In this example, the locks initiated by the SERIALIZABLE isolation level prevent the second query from running until after the first one finishes. While this provides airtight data consistency, it does so at a cost of greatly reduced concurrency.

Nested Transactions Transact-SQL allows you to nest transaction operations by issuing nested BEGIN TRAN commands. The automatic variable can be queried to determine the level of nesting—0 indicates no nesting, 1 indicates nesting one level deep, and so forth. Batches and stored procedures that are nesting sensitive should query when first executed and respond accordingly.

Nested Transactions Here's an example that illustrates some of nested transactions: SELECT 'Before BEGIN BEGIN TRAN SELECT 'After BEGIN DELETE sales BEGIN TRAN nested SELECT 'After BEGIN TRAN DELETE titleauthor COMMIT TRAN nested -- Does nothing except decrement SELECT 'After COMMIT TRAN GO -- When possible, it's a good idea to place ROLLBACK TRAN in a separate batch -- to prevent batch errors from leaving open transactions ROLLBACK TRAN SELECT 'After ROLLBACK SELECT TOP 5 au_id FROM titleauthor

Nested Transactions Before BEGIN TRAN After BEGIN TRAN After BEGIN TRAN nested After COMMIT TRAN nested After ROLLBACK TRAN 0 au_id In this example, we see that despite the nested COMMIT TRAN, the outer ROLLBACK still reverses the effects of the DELETE titleauthor command.

SAVE TRAN and Save Points You can control how much work ROLLBACK reverses via the SAVE TRAN command. SAVE TRAN creates a save point to which you can roll back if you wish. Syntactically, you just pass the name of the save point to the ROLLBACK TRAN command. Here's an example:

SAVE TRAN and Save Points SELECT 'Before BEGIN TRAN BEGIN TRAN main SELECT 'After BEGIN TRAN DELETE sales SAVE TRAN sales -- Mark a save point SELECT 'After SAVE TRAN -- is unchanged BEGIN TRAN nested SELECT 'After BEGIN TRAN DELETE titleauthor SAVE TRAN titleauthor -- Mark a save point SELECT 'After SAVE TRAN -- is unchanged ROLLBACK TRAN sales SELECT 'After ROLLBACK TRAN -- is unchanged SELECT TOP 5 au_id FROM titleauthor IF BEGIN ROLLBACK TRAN SELECT 'After ROLLBACK END SELECT TOP 5 au_id FROM titleauthor

SAVE TRAN and Save Points Before BEGIN TRAN main After BEGIN TRAN main After SAVE TRAN sales After BEGIN TRAN nested After SAVE TRAN titleauthor After ROLLBACK TRAN sales 2 au_id After ROLLBACK TRAN 0 au_id