Chapter 13. Concurrency Control. In This Chapter. c Concurrency Models c Transactions c Locking c Isolation Levels c Row Versioning

Size: px
Start display at page:

Download "Chapter 13. Concurrency Control. In This Chapter. c Concurrency Models c Transactions c Locking c Isolation Levels c Row Versioning"

Transcription

1 Chapter 13 Concurrency Control In This Chapter c Concurrency Models c Transactions c Locking c Isolation Levels c Row Versioning

2 360 Microsoft SQL Server 2012: A Beginner s Guide As you already know, data in a database is generally shared between many user application programs. The situation in which several user application programs read and write the same data at the same time is called concurrency. Thus, each DBMS must have some kind of control mechanism to solve concurrency problems. A high level of concurrency is possible in a database system that can manage many active user applications without them interfering with each other. Conversely, a database system in which different active applications interfere with each other supports a low level of concurrency. This chapter begins by describing the two concurrency control models that the Database Engine supports. The next section explains how concurrency problems can be solved using transactions. This discussion includes an introduction to the four properties of transactions, known as ACID properties, an overview of the Transact-SQL statements related to transactions, and an introduction to transaction logs. The third major section addresses locking and the three general lock properties: lock modes, lock resources, and lock duration. Deadlock, an important problem that can arise as a consequence of locking, is also introduced. The behavior of transactions depends on the selected isolation level. The five isolation levels are introduced, including whether each belongs to the pessimistic or the optimistic concurrency model. The differences between existing isolation levels and their practical meaning will be explained too. The end of the chapter introduces row versioning, which is how the Database Engine implements the optimistic concurrency model. The two isolation levels related to this model SNAPSHOT and READ COMMITTED SNAPSHOT are discussed, as well as use of the tempdb system database as a version store. Concurrency Models The Database Engine supports two different concurrency models: Pessimistic concurrency Optimistic concurrency Pessimistic concurrency uses locks to block access to data that is used by another process at the same time. In other words, a database system that uses pessimistic concurrency assumes that a conflict between two or more processes can occur at any time and therefore locks resources (row, page, table), as they are required, for the duration of a transaction. As you will see in the section Locking, pessimistic concurrency issues shared locks on data being read so that no other process can modify that data. Also, pessimistic concurrency

3 Chapter 13: Concurrency Control 361 issues exclusive locks for data being modified so that no other processes can read or modify that data. Optimistic concurrency works on the assumption that a transaction is unlikely to modify data that another transaction is modifying at the same time. The Database Engine supports optimistic concurrency so that older versions of data rows are saved, and any process that reads the same data uses the row version that was active when it started reading data. For that reason, a process that modifies the data can do so without any limitation, because all other processes that read the same data access the saved versions of the data. The only conflict scenario occurs when two or more write operations use the same data. In that case, the system displays an error so that the client application can handle it. The notion of optimistic concurrency is generally defined in a broader sense. Optimistic concurrency control works on the assumption that resource conflicts between multiple users are unlikely, and allows transactions to execute without using locks. Only when a user is attempting to change data are resources checked to determine if any conflicts have occurred. If a conflict occurs, the application must be restarted. Transactions A transaction specifies a sequence of Transact-SQL statements that is used by database programmers to package together read and write operations, so that the database system can guarantee the consistency of data. There are two forms of transactions: C C Implicit Specifies any single INSERT, UPDATE, or DELETE statement as a transaction unit C C Explicit Generally, a group of Transact-SQL statements, where the beginning and the end of the group are marked using statements such as BEGIN TRANSACTION, COMMIT, and ROLLBACK The notion of a transaction is best explained through an example. In the sample database, the employee Ann Jones should be assigned a new employee number. The employee number must be modified in two different tables at the same time. The row in the employee table and all corresponding rows in the works_on table must be modified at the same time. (If only one of these tables is modified, data in the sample database would be inconsistent, because the values of the primary key in the employee table and the corresponding values of the foreign key in the works_on table for Ann Jones would not match.) Example 13.1 shows the implementation of this transaction using Transact-SQL statements.

4 362 Microsoft SQL Server 2012: A Beginner s Guide Example 13.1 USE sample; BEGIN TRANSACTION /* The beginning of the transaction */ UPDATE employee SET emp_no = WHERE emp_no = IF (@@error <> 0) ROLLBACK /* Rollback of the transaction */ UPDATE works_on SET emp_no = WHERE emp_no = IF (@@error <> 0) ROLLBACK COMMIT /*The end of the transaction */ The consistent state of data used in Example 13.1 can be obtained only if both UPDATE statements are executed or neither of them is executed. The global is used to test the execution of each Transact-SQL statement. If an error is set to a negative value and the execution of all statements is rolled back. (The Transact-SQL statements BEGIN TRANSACTION, COMMIT, and ROLLBACK are defined in the upcoming section Transact-SQL Statements and Transactions. ) The Transact-SQL language supports exception handling. Instead of using the global used in Example 13.1, you can use TRY and CATCH statements to implement exception handling in a transaction. The use of these statements is discussed in Chapter 8. The next section explains the ACID properties of transactions. These properties guarantee that the data used by application programs will be consistent. Properties of Transactions Transactions have the following properties, which are known collectively by the acronym ACID: Atomicity Consistency Isolation Durability

5 Chapter 13: Concurrency Control 363 The atomicity property guarantees the indivisibility of a set of statements that modifies data in a database and is part of a transaction. This means that either all data modifications in a transaction are executed or, in the case of any failure, all already executed changes are undone. Consistency guarantees that a transaction will not allow the database to contain inconsistent data. In other words, the transactional transformations on data bring the database from one consistent state to another. The isolation property separates concurrent transactions from each other. In other words, an active transaction can t see data modifications in a concurrent and incomplete transaction. This means that some transactions might be rolled back to guarantee isolation. Durability guarantees one of the most important database concepts: persistence of data. This property ensures that the effects of the particular transaction persist even if a system error occurs. For this reason, if a system error occurs while a transaction is active, all statements of that transaction will be undone. Transact-SQL Statements and Transactions There are six Transact-SQL statements related to transactions: BEGIN TRANSACTION BEGIN DISTRIBUTED TRANSACTION COMMIT [WORK] ROLLBACK [WORK] SAVE TRANSACTION SET IMPLICIT_TRANSACTIONS The BEGIN TRANSACTION statement starts the transaction. It has the following syntax: BEGIN TRANSACTION [ } [WITH MARK ['description']]] transaction_name is the name assigned to the transaction, which can be used only on the outermost pair of nested BEGIN TRANSACTION/COMMIT or BEGIN TRANSACTION/ROLLBACK is the name of a user-defined variable containing a valid transaction name. The WITH MARK option specifies that the transaction is to be marked in the log. description is a string that describes the mark. If WITH MARK is used, a transaction name must be specified. (For more information on transaction log marking for recovery, see Chapter 16.)

6 364 Microsoft SQL Server 2012: A Beginner s Guide The BEGIN DISTRIBUTED TRANSACTION statement specifies the start of a distributed transaction managed by the Microsoft Distributed Transaction Coordinator (MS DTC). A distributed transaction is one that involves databases on more than one server. For this reason, there is a need for a coordinator that will coordinate execution of statements on all involved servers. The server executing the BEGIN DISTRIBUTED TRANSACTION statement is the transaction coordinator and therefore controls the completion of the distributed transaction. (See Chapter 18 for a discussion of distributed transactions.) The COMMIT WORK statement successfully ends the transaction started with the BEGIN TRANSACTION statement. This means that all modifications made by the transaction are stored on the disk. The COMMIT WORK statement is a standardized SQL statement. (The WORK clause is optional.) The Transact-SQL language also supports the COMMIT TRANSACTION statement, which is functionally equivalent to COMMIT WORK, with the exception that the former accepts a user-defined transaction name. COMMIT TRANSACTION is an extension of Transact-SQL in relation to the SQL standard. In contrast to the COMMIT statement, the ROLLBACK WORK statement reports an unsuccessful end of the transaction. Programmers use this statement if they assume that the database might be in an inconsistent state. In this case, all executed modification operations within the transaction are rolled back. The ROLLBACK WORK statement is a standardized SQL statement. (The WORK clause is optional.) Transact-SQL also supports the ROLLBACK TRANSACTION statement, which is functionally equivalent to ROLLBACK WORK, with the exception that ROLLBACK TRANSACTION accepts a user-defined transaction name. The SAVE TRANSACTION statement sets a savepoint within a transaction. A savepoint marks a specified point within the transaction so that all updates that follow can be canceled without canceling the entire transaction. (To cancel an entire transaction, use the ROLLBACK statement.) The SAVE TRANSACTION statement actually does not commit any modification operation; it only creates a target for the subsequent ROLLBACK statement with the label with the same name as the SAVE TRANSACTION statement. Example 13.2 shows the use of the SAVE TRANSACTION statement.

7 Chapter 13: Concurrency Control 365 Example 13.2 BEGIN TRANSACTION; INSERT INTO department (dept_no, dept_name) VALUES ('d4', 'Sales'); SAVE TRANSACTION a; INSERT INTO department (dept_no, dept_name) VALUES ('d5', 'Research'); SAVE TRANSACTION b; INSERT INTO department (dept_no, dept_name) VALUES ('d6', 'Management'); ROLLBACK TRANSACTION b; INSERT INTO department (dept_no, dept_name) VALUES ('d7', 'Support'); ROLLBACK TRANSACTION a; COMMIT TRANSACTION; The only statement in Example 13.2 that is executed is the first INSERT statement. The third INSERT statement is rolled back by the ROLLBACK b statement, while the other two INSERT statements are rolled back by the ROLLBACK a statement. The SAVE TRANSACTION statement, in combination with the IF or WHILE statement, is a useful transaction feature for the execution of parts of an entire transaction. On the other hand, the use of this statement is contrary to the principle of operational databases that a transaction should be as short as possible, because long transactions generally reduce data availability. As you already know, each Transact-SQL statement always belongs either implicitly or explicitly to a transaction. The Database Engine provides implicit transactions for compliance with the SQL standard. When a session operates in the implicit transaction mode, selected statements implicitly issue the BEGIN TRANSACTION statement. This means that you do nothing to start an implicit transaction. However, the end of each implicit transaction must be explicitly committed or rolled back using the COMMIT or ROLLBACK statement. (If you do not explicitly commit the transaction, the transaction and all the data changes it contains are rolled back when the user disconnects.) To enable an implicit transaction, you have to enable the IMPLICIT_ TRANSACTIONS clause of the SET statement. This statement sets the implicit transaction mode for the current session. When a connection is in the implicit

8 366 Microsoft SQL Server 2012: A Beginner s Guide transaction mode and the connection is not currently in a transaction, executing any of the following statements starts a transaction: ALTER TABLE FETCH REVOKE CREATE TABLE GRANT SELECT DELETE INSERT TRUNCATE TABLE DROP TABLE OPEN UPDATE In other words, if you have a sequence of statements from the preceding list, each statement will represent a single transaction. The beginning of an explicit transaction is marked with the BEGIN TRANSACTION statement. The end of an explicit transaction is marked with the COMMIT or ROLLBACK statement. Explicit transactions can be nested. In this case, each pair of statements BEGIN TRANSACTION/COMMIT or BEGIN TRANSACTION/ ROLLBACK is used inside one or more such pairs. (The nested transactions are usually used in stored procedures, which themselves contain transactions and are invoked inside another transaction.) The global contains the number of active transactions for the current user. BEGIN TRANSACTION, COMMIT, and ROLLBACK can be specified using a name assigned to the transaction. (The named ROLLBACK statement corresponds either to a named transaction or to the SAVE TRANSACTION statement with the same name.) You can use a named transaction only in the outermost statement pair of nested BEGIN TRANSACTION/COMMIT or BEGIN TRANSACTION/ ROLLBACK statements. Transaction Log Relational database systems keep a record of each change they make to the database during a transaction. This is necessary in case an error occurs during the execution of the transaction. In this situation, all previously executed statements within the transaction have to be rolled back. As soon as the system detects the error, it uses the stored records to return the database to the consistent state that existed before the transaction was started. The Database Engine keeps all stored records, in particular the before and after values, in one or more files called the transaction log. Each database has its own transaction log. Thus, if it is necessary to roll back one or more modification operations executed on the tables of the current database, the Database Engine uses the entries in the transaction log to restore the values of columns that the database had before the transaction was started. The transaction log is used to roll back or restore a transaction. If an error occurs and the transaction does not completely execute, the system uses all existing before values

9 Chapter 13: Concurrency Control 367 from the transaction log (called before images) to roll back all modifications since the start of the transaction. The process in which before images from the transaction log are used to roll back all modifications is called the undo activity. Transaction logs also store after images. After images are modified values, which are used to roll forward all modifications since the start of the transaction. This process is called the redo activity and is applied during recovery of a database. (For further details concerning transaction logs and recovery, see Chapter 16.) Every entry written into the log is uniquely identified using the log sequence number (LSN). All log entries that are part of the particular transaction are linked together, so that all parts of a transaction can be located for undo and redo activities. Locking Concurrency can lead to several negative effects, such as the reading of nonexistent data or loss of modified data. Consider this real-world example illustrating one of these negative effects, called dirty read: User U 1 in the personnel department gets notice of an address change for the employee Jim Smith. U 1 makes the address change, but when viewing the bank account information of Mr. Smith in the consecutive dialog step, he realizes that he modified the address of the wrong person. (The enterprise employs two persons with the name Jim Smith.) Fortunately, the application allows the user to cancel this change by clicking a button. U 1 clicks the button, knowing that he has committed no error. At the same time, user U 2 in the technical department retrieves the data of the latter Mr. Smith to send the newest technical document to his home, because the employee seldom comes to the office. As the employee s address was wrongly changed just before U 2 retrieved the address, U 2 prints out the wrong address label and sends the document to the wrong person. To prevent problems like these in the pessimistic concurrency model, every DBMS must have mechanisms that control the access of data by all users at the same time. The Database Engine, like all relational DBMSs, uses locks to guarantee the consistency of the database in case of multiuser access. Each application program locks the data it needs, guaranteeing that no other program can modify the same data. When another application program requests the modification of the locked data, the system either stops the program with an error or makes a program wait. Locking has several different aspects: Lock duration Lock modes Lock granularity

10 368 Microsoft SQL Server 2012: A Beginner s Guide Lock duration specifies a time period during which a resource holds the particular lock. Duration of a lock depends on, among other things, the mode of the lock and the choice of the isolation level. The next two sections describe lock modes and lock granularity. The following discussion concerns the pessimistic concurrency model. The optimistic concurrency model is handled using row versioning, and will be explained at the end of this chapter. Lock Modes Lock modes specify different kinds of locks. The choice of which lock mode to apply depends on the resource that needs to be locked. The following three lock types are used for row- and page-level locking: Shared (S) Exclusive (X) Update (U) A shared lock reserves a resource (page or row) for reading only. Other processes cannot modify the locked resource while the lock remains. On the other hand, several processes can hold a shared lock for a resource at the same time that is, several processes can read the resource locked with the shared lock. An exclusive lock reserves a page or row for the exclusive use of a single transaction. It is used for DML statements (INSERT, UPDATE, and DELETE) that modify the resource. An exclusive lock cannot be set if some other process holds a shared or exclusive lock on the resource that is, there can be only one exclusive lock for a resource. Once an exclusive lock is set for the page (or row), no other lock can be placed on the same resource. The database system automatically chooses the appropriate lock mode according to the operation type (read or write). An update lock can be placed only if no other update or exclusive lock exists. On the other hand, it can be placed on objects that already have shared locks. (In this case, the update lock acquires another shared lock on the same object.) If a transaction that

11 Chapter 13: Concurrency Control 369 modifies the object is committed, the update lock is changed to an exclusive lock if there are no other locks on the object. There can be only one update lock for an object. Update locks prevent certain common types of deadlocks. (Deadlocks are described at the end of this section.) Table 13-1 shows the compatibility matrix for shared, exclusive, and update locks. The matrix is interpreted as follows: suppose transaction T 1 holds a lock as specified in the first column of the matrix, and suppose some other transaction, T 2, requests a lock as specified in the corresponding column heading. In this case, yes indicates that a lock of T 2 is possible, whereas no indicates a conflict with the existing lock. The Database Engine also supports other lock forms, such as latches and spinlocks. The description of these lock forms can be found in Books Online. At the table level, there are five different types of locks: Shared (S) Exclusive (X) Intent shared (IS) Intent exclusive (IX) Shared with intent exclusive (SIX) Shared and exclusive locks correspond to the row-level (or page-level) locks with the same names. Generally, an intent lock shows an intention to lock the next-lower resource in the hierarchy of the database objects. Therefore, intent locks are placed at Shared Update Exclusive Shared Yes Yes No Update Yes No No Exclusive No No No Table 13-1 Compatibility Matrix for Shared, Exclusive, and Update Locks

12 370 Microsoft SQL Server 2012: A Beginner s Guide S X IS SIX IX S Yes No Yes No No X No No No No No IS Yes No Yes Yes Yes SIX No No Yes No No IX No No Yes No Yes Table 13-2 Compatibility Matrix for All Kinds of Table Locks a level in the object hierarchy above that which the process intends to lock. This is an efficient way to tell whether such locks will be possible, and it prevents other processes from locking the higher level before the desired locks can be attained. Table 13-2 shows the compatibility matrix for all kinds of table locks. The matrix is interpreted exactly as the matrix in Table Lock Granularity Lock granularity specifies which resource is locked by a single lock attempt. The Database Engine can lock the following resources: Row Page Index key or range of index keys Table Extent Database itself The system automatically chooses the appropriate lock granularity. A row is the smallest resource that can be locked. The support of row-level locking includes both data rows and index entries. Row-level locking means that only the row that is accessed by an application will be locked. Hence, all other rows that belong to the same page are free and can be used by other applications. The Database Engine can also lock the page on which the row that has to be locked is stored.

13 Chapter 13: Concurrency Control 371 For clustered tables, the data pages are stored at the leaf level of the (clustered) index structure and are therefore locked with index key locks instead of row locks. Locking is also done on disk units, called extents, that are 64K in size (see Chapter 15). Extent locks are set automatically when a table (or index) grows and the additional disk space is needed. Lock granularity affects concurrency. In general, the more granular the lock, the more concurrency is reduced. This means that row-level locking maximizes concurrency because it leaves all but one row on the page unlocked. On the other hand, system overhead is increased because each locked row requires one lock. Page-level locking (and table-level locking) restricts the availability of data but decreases the system overhead. Lock Escalation If many locks of the same granularity are held during a transaction, the Database Engine automatically upgrades these locks into a table lock. This process of converting many page-, row-, or index-level locks into one table lock is called lock escalation. The escalation threshold is the boundary at which the database system applies the lock escalation. Escalation thresholds are determined dynamically by the system and require no configuration. (Currently, the threshold boundary is 5000 locks.) The general problem with lock escalation is that the database server decides when to escalate a particular lock, and this decision might be suboptimal for applications with different requirements. You can use the ALTER TABLE statement to change the lock escalation mechanism. This statement supports the TABLE option with the following syntax: SET ( LOCK_ESCALATION = { TABLE AUTO DISABLE } ) The TABLE option is the default value and specifies that lock escalation will be done at table-level granularity. The AUTO option allows the Database Engine to select the lock escalation granularity that is appropriate for the table schema. Finally, the DISABLE option allows you to disable lock escalation in most cases. (There are some cases in which the Database Engine must take a table lock to protect data integrity.) Example 13.3 disables the lock escalation for the employee table. Example 13.3 USE sample; ALTER TABLE employee SET (LOCK_ESCALATION = DISABLE);

14 372 Microsoft SQL Server 2012: A Beginner s Guide Affecting Locks You can use either locking hints or the LOCK_TIMEOUT option of the SET statement to affect locks. The following subsections describe these features. Locking Hints Locking hints specify the type of locking used by the Database Engine to lock table data. Table-level locking hints can be used when finer control of the types of locks acquired on a resource is required. (Locking hints override the current transaction isolation level for the session.) All locking hints are written as a part of the FROM clause in the SELECT statement. You can use the following locking hints: C C UPDLOCK Places update locks for each row of the table during the read operation. All update locks are held until the end of the transaction. C C TABLOCK (TABLOCKX) Places a shared (or exclusive) table lock on the table. All locks are held until the end of the transaction. C C ROWLOCK Replaces the existing shared table lock with shared row locks for each qualifying row of the table. C C PAGLOCK Replaces a shared table lock with shared page locks for each page containing qualifying rows. C C NOLOCK Synonym for READUNCOMMITTED (see the description of isolation-level hints later in this chapter). C C HOLDLOCK Synonym for REPEATABLEREAD (see the description of isolation-level hints later in this chapter). C C XLOCK Specifies that exclusive locks are to be taken and held until the transaction completes. If XLOCK is specified with ROWLOCK, PAGLOCK, or TABLOCK, the exclusive locks apply to the appropriate level of granularity. C C READPAST Specifies that the Database Engine does not read rows that are locked by other transactions. All these options can be combined in any order if the combination makes sense. (For example, the combination of TABLOCK and PAGLOCK does not make sense, because both options are applied to different resources.)

15 Chapter 13: Concurrency Control 373 LOCK_TIMEOUT Option If you don t want your process to wait without any time limitations, you can use the LOCK_TIMEOUT option of the SET statement. This option specifies the number of milliseconds a transaction will wait for a lock to be released. For instance, if you want your processes to wait eight seconds, you write the following statement: SET LOCK_TIMEOUT 8000 If the particular resource cannot be granted to your process within this time period, the statement will be aborted with the corresponding error message. The value of 1 (the default value) indicates no time-out; in other words, the transaction won t wait at all. (The READPAST locking hint provides an alternative to the LOCK_TIMEOUT option.) Displaying Lock Information The most important utility to display lock information is a dynamic management view called sys.dm_tran_locks. This view returns information about currently active lock manager resources. Each row represents a currently active request for a lock that has been granted or is waiting to be granted. The columns of this view relate to two groups: resource and request. The resource group describes the resource on which the lock request is being made, and the request group describes the lock request. The most important columns of this view are as follows: C C resource_type Represents the resource type C C resource_database_id resource is scoped C C request_mode Specifies the mode of the request C C request_status Example 13.4 displays all the locks that are in a wait state. Example 13.4 USE AdventureWorks; SELECT resource_type, DB_NAME(resource_database_id) as db_name, request_session_id, request_mode, request_status FROM sys.dm_tran_locks WHERE request_status = 'WAIT;'

16 374 Microsoft SQL Server 2012: A Beginner s Guide Deadlock A deadlock is a special concurrency problem in which two transactions block the progress of each other. The first transaction has a lock on some database object that the other transaction wants to access, and vice versa. (In general, several transactions can cause a deadlock by building a circle of dependencies.) Example 13.5 shows the deadlock situation between two transactions. The parallelism of processes cannot be achieved naturally using the small sample database, because every transaction in it is executed very quickly. Therefore, Example 13.5 uses the WAITFOR statement to pause both transactions for ten seconds to simulate the deadlock. Example 13.5 USE sample; BEGIN TRANSACTION UPDATE works_on SET job = 'Manager' WHERE emp_no = AND project_no = 'p2' WAITFOR DELAY '00:00:10' UPDATE employee SET emp_lname = 'Green' WHERE emp_no = 9031 COMMIT BEGIN TRANSACTION UPDATE employee SET dept_no = 'd2' WHERE emp_no = 9031 WAITFOR DELAY '00:00:10' DELETE FROM works_on WHERE emp_no = AND project_no = 'p2' COMMIT If both transactions in Example 13.5 are executed at the same time, the deadlock appears and the system returns the following output: Server: Msg 1205, Level 13, State 45 Transaction (Process id 56) was deadlocked with another process and has been chosen as deadlock victim. Rerun your command. As the output of Example 13.5 shows, the database system handles a deadlock by choosing one of the transactions as a victim (actually, the one that closed the loop in lock requests) and rolling it back. (The other transaction is executed after that.) A programmer can handle a deadlock by implementing the conditional statement that tests for the returned error number (1205) and then executes the rolled-back transaction again. You can affect which transaction the system chooses as the victim by using the DEADLOCK_PRIORITY option of the SET statement. There are 21 different

17 Chapter 13: Concurrency Control 375 priority levels, from 10 to 10. The value LOW corresponds to 5, NORMAL (the default value) corresponds to 0, and HIGH corresponds to 5. The victim session is chosen according to the session s deadlock priority. Isolation Levels In theory, each transaction should be fully isolated from other transactions. But, in such a case, data availability is significantly reduced, because read operations in a transaction block write operations in other transactions, and vice versa. If data availability is an important issue, this property can be loosened using isolation levels. Isolation levels specify the degree to which data being retrieved in a transaction is protected from changes to the same data by other transactions. Before you are introduced to the existing isolation levels, the following section takes a look at scenarios that can arise if locking isn t used and, hence, there is no isolation between transactions. Concurrency Problems If locking isn t used, and thus no isolation exists between transactions, the following four problems may appear: Lost update Dirty reads (discussed earlier, in the Locking section) Nonrepeatable reads Phantoms The lost update concurrency problem occurs when no isolation is provided to a transaction from other transactions. This means that several transactions can read the same data and modify it. The changes to the data by all transactions, except those by the last transaction, are lost. The nonrepeatable read concurrency problem occurs when one process reads data several times, and another process changes the same data between two read operations of the first process. Therefore, the values read by both read operations of the first process are different. The phantom concurrency problem is similar to the nonrepeatable read concurrency problem, because two subsequent read operations can display different values, but in this case, the reason for this behavior lies in the different number of rows being read the first time and the second time. (Additional rows, called phantoms, are inserted by other transactions.)

18 376 Microsoft SQL Server 2012: A Beginner s Guide The Database Engine and Isolation Levels Using isolation levels, you can specify which of the concurrency problems discussed in the preceding section may occur and which you want to avoid. The Database Engine supports the following five isolation levels, which control how your read operations are executed: READ UNCOMMITTED READ COMMITTED REPEATABLE READ SERIALIZABLE SNAPSHOT READ UNCOMMITTED, REPEATABLE READ, and SERIALIZABLE are available only in the pessimistic concurrency model, whereas SNAPSHOT is available only in the optimistic concurrency model. READ COMMITTED is available in both models. The four isolation levels available in the pessimistic concurrency model are described next. SNAPSHOT is described in the next section, Row Versioning. READ UNCOMMITTED READ UNCOMMITTED provides the simplest form of isolation between transactions, because it does not isolate the read operations from other transactions at all. When a transaction retrieves a row at this isolation level, it acquires no locks and respects none of the existing locks. The data that is read by such a transaction may be inconsistent. In this case, a transaction reads data that is updated from some other active transaction. If the latter transaction rolls back later, the former transaction reads data that never really existed. Of the four concurrency problems described in the preceding section, READ UNCOMMITTED allows dirty reads, nonrepeatable reads, and phantoms. The READ UNCOMMITTED isolation level is usually very undesirable and should be used only when the accuracy of the data read is not important or the data is seldom modified. READ COMMITTED As you already know, the READ COMMITTED isolation level has two forms. The first form applies to the pessimistic concurrency model, while the second form applies

19 Chapter 13: Concurrency Control 377 to the optimistic concurrency model. This section discusses the former. The second form, READ COMMITTED SNAPSHOT, is discussed in the following section, Row Versioning. A transaction that reads a row and uses the READ COMMITTED isolation level tests only whether an exclusive lock is placed on the row. If no such lock exists, the transaction fetches the row. (This is done using a shared lock.) This action prevents the transaction from reading data that is not committed and that can be subsequently rolled back. After reading the data values, the data can be changed by some other transaction. Shared locks used by this isolation level are released immediately after the data is processed. (Generally, all locks are released at the end of the transaction.) For this reason, the access to the concurrent data is improved, but nonrepeatable reads and phantoms can still happen. The READ COMMITTED isolation level is the default isolation level of the Database Engine. REPEATABLE READ In contrast to the READ COMMITTED isolation level, REPEATABLE READ places shared locks on all data that is read and holds these locks until the transaction is committed or rolled back. Therefore, in this case, the execution of a query several times inside a transaction will always display the same result. The disadvantage of this isolation level is that concurrency is further reduced, because the time interval during which other transactions cannot update the same data is significantly longer than in the case of READ COMMITTED. This isolation level does not prevent another transaction from inserting new rows, which are included in subsequent reads, so phantoms can appear. SERIALIZABLE SERIALIZABLE is the strongest isolation level, because it prevents all four concurrency problems already discussed. It acquires a range lock on all data that is read by the corresponding transaction. Therefore, this isolation level also prevents the insertion of new rows by another transaction until the former transaction is committed or rolled back. The SERIALIZABLE isolation level is implemented using a key-range locking method. This method locks individual rows and the ranges between them. A key-range lock acquires locks for index entries rather than locks for the particular pages or the entire table. In this case, any modification operation of another transaction cannot be executed, because the necessary changes of index entries are not possible.

20 378 Microsoft SQL Server 2012: A Beginner s Guide As a conclusion to the discussion of all four isolation levels above, you have to know that each isolation level in the preceding description reduces the concurrency more than the previous one. Thus, the isolation level READ UNCOMMITTED reduces concurrency the least. On the other hand, it also has the smallest isolation from concurrent transactions. SERIALIZABLE reduces concurrency the most, but guarantees full isolation between concurrent transactions. Setting and Editing Isolation Levels You can set an isolation level by using the following: The TRANSACTION ISOLATION LEVEL clause of the SET statement Isolation-level hints The TRANSACTION ISOLATION LEVEL option of the SET statement provides five constant values, which have the same names and meanings as the standard isolation levels just described. The FROM clause of the SELECT statement supports several hints for isolation levels: READUNCOMMITTED READCOMMITTED REPEATABLEREAD SERIALIZABLE These hints correspond to the isolation levels with the same name (but with a space in the name). The specification of isolation levels in the FROM clause of the SELECT statement overrides the current value set by the SET TRANSACTION ISOLATION LEVEL statement. The DB USEROPTIONS statement returns, among other things, information about the isolation level. Look at the value of the ISOLATION LEVEL option of this statement to find out the isolation level of your process. Row Versioning The Database Engine supports an optimistic concurrency control mechanism based on row versioning. When data is modified using row versioning, logical copies of the data are maintained for all data modifications performed in the database. Every time a row is modified, the database system stores a before image of the previously committed

21 Chapter 13: Concurrency Control 379 row in the tempdb system database. Each version is marked with the transaction sequence number (XSN) of the transaction that made the change. (The XSN is used to identify all operations to be managed under the corresponding transaction.) The newest version of a row is always stored in the database and chained in the linked list to the corresponding version stored in tempdb. An old row version in the tempdb database might contain pointers to other, even older versions. Each row version is kept in the tempdb database as long as there are operations that might require it. Row versioning isolates transactions from the effects of modifications made by other transactions without the need for requesting shared locks on rows that have been read. This significant reduction in the total number of locks acquired by this isolation level significantly increases availability of data. However, exclusive locks are still needed: transactions using the optimistic isolation level called SNAPSHOT request exclusive locks when they modify rows. Row versioning is used, among other things, to Support the READ COMMITTED SNAPSHOT isolation level Support the SNAPSHOT isolation level Build the inserted and deleted tables in triggers The following subsections describe the SNAPSHOT and READ COMMITTED SNAPSHOT isolation levels, while Chapter 14 discusses in detail the inserted and deleted tables. READ COMMITTED SNAPSHOT Isolation Level READ COMMITTED SNAPSHOT is a slight variation of the READ COMMITTED isolation level discussed in the previous section. It is a statement-level isolation, which means that any other transaction will read the committed values as they exist at the beginning of the statement. In the case of updates, this isolation level reverts from row versions to actual data to select rows to update and uses update locks on the data rows selected. Actual data rows that have to be modified acquire exclusive locks. The main advantage of READ COMMITTED SNAPSHOT is that read operations do not block updates, and updates do not block read operations. On the other hand, updates block other updates, because exclusive locks are set before an update operation is executed. You use the SET clause of the ALTER DATABASE statement to enable the READ COMMITTED SNAPSHOT isolation level. After activation, no further changes are necessary. Any transaction specified with the READ COMMITTED isolation level will now run under READ COMMITTED SNAPSHOT.

22 380 Microsoft SQL Server 2012: A Beginner s Guide SNAPSHOT Isolation Level The SNAPSHOT isolation level is a transaction-level isolation, which means that any other transaction will read the committed values as they exist just before the snapshot transaction starts. Also, the snapshot transaction will return the initial value until it completes, even if another transaction changed it in the meantime. Therefore, only after the snapshot transaction ends will the other transaction read a modified value. Transactions running under the SNAPSHOT isolation level acquire exclusive locks on data before performing the modification only to enforce constraints. Otherwise, locks are not acquired on data until the data is to be modified. When a data row meets the update criteria, the snapshot transaction verifies that the data row has not been modified by a concurrent transaction that committed after the transaction began. If the data row has been modified in a concurrent transaction, an update conflict occurs and the snapshot transaction is terminated. The update conflict is handled by the database system, and no way exists to disable the update conflict detection. Enabling the SNAPSHOT isolation level is a two-step process. First, on the database level, enable the ALLOW_SNAPSHOT_ISOLATION database option (using SQL Server Management Studio, for instance). Second, for each session that will use this isolation level, set the SET TRANSACTION ISOLATION LEVEL statement to SNAPSHOT. When these options are set, versions are built for all rows that are modified in the database. READ COMMITTED SNAPSHOT vs. SNAPSHOT The most important difference between the two optimistic isolation levels is that SNAPSHOT can result in update conflicts when a process sees the same data for the duration of its transaction and is not blocked. By contrast, the READ COMMITTED SNAPSHOT isolation level does not use its own XSN when choosing row versions. Each time a statement is started, such a transaction reads the latest XSN issued for that instance of the database system and selects the row based on that number. Another difference is that the READ COMMITTED SNAPSHOT isolation level allows other transactions to modify the data before the row versioning transaction completes. This can lead to a conflict if another transaction modified the data between the time the row versioning transaction performs a read and subsequently tries to execute the corresponding write operation. (For an application based on the SNAPSHOT isolation level, the system detects the possible conflicts and sends the corresponding error message.)

23 Chapter 13: Concurrency Control 381 Summary Concurrency in multiuser database systems can lead to several negative effects, such as the reading of nonexistent data or loss of modified data. The Database Engine, like all other DBMSs, solves this problem by using transactions. A transaction is a sequence of Transact-SQL statements that logically belong together. All statements inside a transaction build an atomic unit. This means that either all statements are executed or, in the case of failure, all statements are canceled. The locking mechanism is used to implement transactions. The effect of the lock is to prevent other transactions from changing the locked object. Locking has the following aspects: lock modes, lock granularity, and lock duration. Lock mode specifies different kinds of locks, the choice of which depends on the resource that needs to be locked. Lock duration specifies a time period during which a resource holds the particular lock. The Database Engine provides a mechanism called a trigger that enforces, among other things, general integrity constraints. This mechanism is discussed in detail in the next chapter. Exercises E.13.1 What is a purpose of transactions? E.13.2 What is the difference between a local and a distributed transaction? E.13.3 What is the difference between implicit and explicit transaction mode? E.13.4 What kinds of locks are compatible with an exclusive lock? E.13.5 How can you test the successful execution of each T-SQL statement?

24 382 Microsoft SQL Server 2012: A Beginner s Guide E.13.6 When should you use the SAVE TRANSACTION statement? E.13.7 Discuss the difference between row-level and page-level locking. E.13.8 Can a user explicitly influence the locking behavior of the system? E.13.9 What is a difference between basic lock types (shared and exclusive) and an intent lock? E What does lock escalation mean? E Discuss the difference between the READ UNCOMMITTED and SERIALIZABLE isolation levels. E What is deadlock? E Which process is used as a victim in a deadlock situation? Can a user influence the decision of the system?

Seminar 3. Transactions. Concurrency Management in MS SQL Server

Seminar 3. Transactions. Concurrency Management in MS SQL Server Seminar 3 Transactions Concurrency Management in MS SQL Server Transactions in SQL Server SQL Server uses transactions to compose multiple operations in a single unit of work. Each user's work is processed

More information

Module 15: Managing Transactions and Locks

Module 15: Managing Transactions and Locks Module 15: Managing Transactions and Locks Overview Introduction to Transactions and Locks Managing Transactions SQL Server Locking Managing Locks Introduction to Transactions and Locks Transactions Ensure

More information

Database Administration and Tuning

Database Administration and Tuning Department of Computer Science and Engineering 2012/2013 Database Administration and Tuning Lab 5 2nd semester In this lab class we will approach the following topics: 1. Important Concepts 1. Transaction

More information

Locking & Blocking Made Simple

Locking & Blocking Made Simple Locking & Blocking Made Simple Joe Webb Microsoft SQL Server MVP WebbTech Solutions, LLC joew@webbtechsolutions.com Our Agenda The Nature of Multi-User Databases The Basics of Locking and Blocking Techniques

More information

A can be implemented as a separate process to which transactions send lock and unlock requests The lock manager replies to a lock request by sending a lock grant messages (or a message asking the transaction

More information

bobpusateri.com heraflux.com linkedin.com/in/bobpusateri. Solutions Architect

bobpusateri.com heraflux.com linkedin.com/in/bobpusateri. Solutions Architect 1 @sqlbob bobpusateri.com heraflux.com linkedin.com/in/bobpusateri Specialties / Focus Areas / Passions: Performance Tuning & Troubleshooting Very Large Databases SQL Server Storage Engine High Availability

More information

Chapter 7 (Cont.) Transaction Management and Concurrency Control

Chapter 7 (Cont.) Transaction Management and Concurrency Control Chapter 7 (Cont.) Transaction Management and Concurrency Control In this chapter, you will learn: What a database transaction is and what its properties are What concurrency control is and what role it

More information

CHAPTER 3 RECOVERY & CONCURRENCY ADVANCED DATABASE SYSTEMS. Assist. Prof. Dr. Volkan TUNALI

CHAPTER 3 RECOVERY & CONCURRENCY ADVANCED DATABASE SYSTEMS. Assist. Prof. Dr. Volkan TUNALI CHAPTER 3 RECOVERY & CONCURRENCY ADVANCED DATABASE SYSTEMS Assist. Prof. Dr. Volkan TUNALI PART 1 2 RECOVERY Topics 3 Introduction Transactions Transaction Log System Recovery Media Recovery Introduction

More information

A transaction is a sequence of one or more processing steps. It refers to database objects such as tables, views, joins and so forth.

A transaction is a sequence of one or more processing steps. It refers to database objects such as tables, views, joins and so forth. 1 2 A transaction is a sequence of one or more processing steps. It refers to database objects such as tables, views, joins and so forth. Here, the following properties must be fulfilled: Indivisibility

More information

Database Principles: Fundamentals of Design, Implementation, and Management Tenth Edition. Chapter 13 Managing Transactions and Concurrency

Database Principles: Fundamentals of Design, Implementation, and Management Tenth Edition. Chapter 13 Managing Transactions and Concurrency Database Principles: Fundamentals of Design, Implementation, and Management Tenth Edition Chapter 13 Managing Transactions and Concurrency Objectives In this chapter, you will learn: What a database transaction

More information

Chapter 22. Transaction Management

Chapter 22. Transaction Management Chapter 22 Transaction Management 1 Transaction Support Transaction Action, or series of actions, carried out by user or application, which reads or updates contents of database. Logical unit of work on

More information

Concurrency Control. Transaction Management. Lost Update Problem. Need for Concurrency Control. Concurrency control

Concurrency Control. Transaction Management. Lost Update Problem. Need for Concurrency Control. Concurrency control Concurrency Control Process of managing simultaneous operations on the database without having them interfere with one another. Transaction Management Concurrency control Connolly & Begg. Chapter 19. Third

More information

What are Transactions? Transaction Management: Introduction (Chap. 16) Major Example: the web app. Concurrent Execution. Web app in execution (CS636)

What are Transactions? Transaction Management: Introduction (Chap. 16) Major Example: the web app. Concurrent Execution. Web app in execution (CS636) What are Transactions? Transaction Management: Introduction (Chap. 16) CS634 Class 14, Mar. 23, 2016 So far, we looked at individual queries; in practice, a task consists of a sequence of actions E.g.,

More information

Databases - Transactions

Databases - Transactions Databases - Transactions Gordon Royle School of Mathematics & Statistics University of Western Australia Gordon Royle (UWA) Transactions 1 / 34 ACID ACID is the one acronym universally associated with

More information

Problems Caused by Failures

Problems Caused by Failures Problems Caused by Failures Update all account balances at a bank branch. Accounts(Anum, CId, BranchId, Balance) Update Accounts Set Balance = Balance * 1.05 Where BranchId = 12345 Partial Updates - Lack

More information

Transaction Management: Introduction (Chap. 16)

Transaction Management: Introduction (Chap. 16) Transaction Management: Introduction (Chap. 16) CS634 Class 14 Slides based on Database Management Systems 3 rd ed, Ramakrishnan and Gehrke What are Transactions? So far, we looked at individual queries;

More information

Introduction to Databases, Fall 2005 IT University of Copenhagen. Lecture 10: Transaction processing. November 14, Lecturer: Rasmus Pagh

Introduction to Databases, Fall 2005 IT University of Copenhagen. Lecture 10: Transaction processing. November 14, Lecturer: Rasmus Pagh Introduction to Databases, Fall 2005 IT University of Copenhagen Lecture 10: Transaction processing November 14, 2005 Lecturer: Rasmus Pagh Today s lecture Part I: Transaction processing Serializability

More information

CSE 530A ACID. Washington University Fall 2013

CSE 530A ACID. Washington University Fall 2013 CSE 530A ACID Washington University Fall 2013 Concurrency Enterprise-scale DBMSs are designed to host multiple databases and handle multiple concurrent connections Transactions are designed to enable Data

More information

Transactions. Kathleen Durant PhD Northeastern University CS3200 Lesson 9

Transactions. Kathleen Durant PhD Northeastern University CS3200 Lesson 9 Transactions Kathleen Durant PhD Northeastern University CS3200 Lesson 9 1 Outline for the day The definition of a transaction Benefits provided What they look like in SQL Scheduling Transactions Serializability

More information

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe CHAPTER 20 Introduction to Transaction Processing Concepts and Theory Introduction Transaction Describes local unit of database processing Transaction processing systems Systems with large databases and

More information

Part VII Data Protection

Part VII Data Protection Part VII Data Protection Part VII describes how Oracle protects the data in a database and explains what the database administrator can do to provide additional protection for data. Part VII contains the

More information

DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI

DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI Department of Computer Science and Engineering CS6302- DATABASE MANAGEMENT SYSTEMS Anna University 2 & 16 Mark Questions & Answers Year / Semester: II / III

More information

Database Systems CSE 414

Database Systems CSE 414 Database Systems CSE 414 Lecture 27: Transaction Implementations 1 Announcements Final exam will be on Dec. 14 (next Thursday) 14:30-16:20 in class Note the time difference, the exam will last ~2 hours

More information

Transaction Management

Transaction Management Transaction Management Imran Khan FCS, IBA In this chapter, you will learn: What a database transaction is and what its properties are How database transactions are managed What concurrency control is

More information

Transaction Management. Pearson Education Limited 1995, 2005

Transaction Management. Pearson Education Limited 1995, 2005 Chapter 20 Transaction Management 1 Chapter 20 - Objectives Function and importance of transactions. Properties of transactions. Concurrency Control Deadlock and how it can be resolved. Granularity of

More information

Introduction to Transaction Processing Concepts and Theory

Introduction to Transaction Processing Concepts and Theory Chapter 4 Introduction to Transaction Processing Concepts and Theory Adapted from the slides of Fundamentals of Database Systems (Elmasri et al., 2006) 1 Chapter Outline Introduction to Transaction Processing

More information

Transaction Management Chapter 11. Class 9: Transaction Management 1

Transaction Management Chapter 11. Class 9: Transaction Management 1 Transaction Management Chapter 11 Class 9: Transaction Management 1 The Concurrent Update Problem To prevent errors from being introduced when concurrent updates are attempted, the application logic must

More information

Transaction Management

Transaction Management Transaction Management 1) Explain properties of a transaction? (JUN/JULY 2015) Transactions should posses the following (ACID) properties: Transactions should possess several properties. These are often

More information

Transactions. ACID Properties of Transactions. Atomicity - all or nothing property - Fully performed or not at all

Transactions. ACID Properties of Transactions. Atomicity - all or nothing property - Fully performed or not at all Transactions - An action, or series of actions, carried out by a single user or application program, which reads or updates the contents of the database - Logical unit of work on the database - Usually

More information

Intro to Transactions

Intro to Transactions Reading Material CompSci 516 Database Systems Lecture 14 Intro to Transactions [RG] Chapter 16.1-16.3, 16.4.1 17.1-17.4 17.5.1, 17.5.3 Instructor: Sudeepa Roy Acknowledgement: The following slides have

More information

Weak Levels of Consistency

Weak Levels of Consistency Weak Levels of Consistency - Some applications are willing to live with weak levels of consistency, allowing schedules that are not serialisable E.g. a read-only transaction that wants to get an approximate

More information

Multi-User-Synchronization

Multi-User-Synchronization Chapter 10 Multi-User-Synchronization Database Systems p. 415/569 Why Run TAs Concurrently? We could run all TAs serially (one after the other) This would prevent all unwanted side effects However, this

More information

Chapter 20 Introduction to Transaction Processing Concepts and Theory

Chapter 20 Introduction to Transaction Processing Concepts and Theory Chapter 20 Introduction to Transaction Processing Concepts and Theory - Logical units of DB processing - Large database and hundreds of transactions - Ex. Stock market, super market, banking, etc - High

More information

CSE 344 MARCH 25 TH ISOLATION

CSE 344 MARCH 25 TH ISOLATION CSE 344 MARCH 25 TH ISOLATION ADMINISTRIVIA HW8 Due Friday, June 1 OQ7 Due Wednesday, May 30 Course Evaluations Out tomorrow TRANSACTIONS We use database transactions everyday Bank $$$ transfers Online

More information

DATABASE TRANSACTIONS. CS121: Relational Databases Fall 2017 Lecture 25

DATABASE TRANSACTIONS. CS121: Relational Databases Fall 2017 Lecture 25 DATABASE TRANSACTIONS CS121: Relational Databases Fall 2017 Lecture 25 Database Transactions 2 Many situations where a sequence of database operations must be treated as a single unit A combination of

More information

Graph-based protocols are an alternative to two-phase locking Impose a partial ordering on the set D = {d 1, d 2,..., d h } of all data items.

Graph-based protocols are an alternative to two-phase locking Impose a partial ordering on the set D = {d 1, d 2,..., d h } of all data items. Graph-based protocols are an alternative to two-phase locking Impose a partial ordering on the set D = {d 1, d 2,..., d h } of all data items. If d i d j then any transaction accessing both d i and d j

More information

Database Systems CSE 414

Database Systems CSE 414 Database Systems CSE 414 Lecture 22: Transaction Implementations CSE 414 - Spring 2017 1 Announcements WQ7 (last!) due on Sunday HW7: due on Wed, May 24 using JDBC to execute SQL from Java using SQL Server

More information

Security Mechanisms I. Key Slide. Key Slide. Security Mechanisms III. Security Mechanisms II

Security Mechanisms I. Key Slide. Key Slide. Security Mechanisms III. Security Mechanisms II Database Facilities One of the main benefits from centralising the implementation data model of a DBMS is that a number of critical facilities can be programmed once against this model and thus be available

More information

CS352 Lecture - The Transaction Concept

CS352 Lecture - The Transaction Concept CS352 Lecture - The Transaction Concept Last Revised 11/7/06 Objectives: 1. To introduce the notion of a transaction and the ACID properties of a transaction 2. To introduce the notion of the state of

More information

Transaction Processing Concepts and Theory. Truong Tuan Anh CSE-HCMUT

Transaction Processing Concepts and Theory. Truong Tuan Anh CSE-HCMUT 1 Transaction Processing Concepts and Theory Truong Tuan Anh CSE-HCMUT 2 Outline Introduction to Transaction Processing Transaction and System Concepts Desirable Properties of Transactions Characterizing

More information

Lecture 21 Concurrency Control Part 1

Lecture 21 Concurrency Control Part 1 CMSC 461, Database Management Systems Spring 2018 Lecture 21 Concurrency Control Part 1 These slides are based on Database System Concepts 6 th edition book (whereas some quotes and figures are used from

More information

Into into Locking and Blocking. Dmitri Korotkevitch (http://aboutsqlserver.com) 1

Into into Locking and Blocking. Dmitri Korotkevitch (http://aboutsqlserver.com) 1 Into into Locking and Blocking Dmitri Korotkevitch (http://aboutsqlserver.com) 1 About me 20 years of experience in IT 14+ years of experience working with Microsoft SQL Server Microsoft SQL Server MVP

More information

Copyright 2007 Ramez Elmasri and Shamkant B. Navathe. Slide 17-1

Copyright 2007 Ramez Elmasri and Shamkant B. Navathe. Slide 17-1 Slide 17-1 Chapter 17 Introduction to Transaction Processing Concepts and Theory Chapter Outline 1 Introduction to Transaction Processing 2 Transaction and System Concepts 3 Desirable Properties of Transactions

More information

Chapter 15 : Concurrency Control

Chapter 15 : Concurrency Control Chapter 15 : Concurrency Control What is concurrency? Multiple 'pieces of code' accessing the same data at the same time Key issue in multi-processor systems (i.e. most computers today) Key issue for parallel

More information

Transactions and Concurrency Control. Dr. Philip Cannata

Transactions and Concurrency Control. Dr. Philip Cannata Transactions and Concurrency Control Dr. Philip Cannata 1 To open two SQLDevelopers: On the Mac do the following: click on the SQLDeveloper icon to start one instance from the command line run the following

More information

Advances in Data Management Transaction Management A.Poulovassilis

Advances in Data Management Transaction Management A.Poulovassilis 1 Advances in Data Management Transaction Management A.Poulovassilis 1 The Transaction Manager Two important measures of DBMS performance are throughput the number of tasks that can be performed within

More information

CSE 344 MARCH 9 TH TRANSACTIONS

CSE 344 MARCH 9 TH TRANSACTIONS CSE 344 MARCH 9 TH TRANSACTIONS ADMINISTRIVIA HW8 Due Monday Max Two Late days Exam Review Sunday: 5pm EEB 045 CASE STUDY: SQLITE SQLite is very simple More info: http://www.sqlite.org/atomiccommit.html

More information

CPS352 Lecture - The Transaction Concept

CPS352 Lecture - The Transaction Concept Objectives: CPS352 Lecture - The Transaction Concept Last Revised March 3, 2017 1. To introduce the notion of a transaction and the ACID properties of a transaction 2. To introduce the notion of the state

More information

Database Management System Prof. D. Janakiram Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No.

Database Management System Prof. D. Janakiram Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No. Database Management System Prof. D. Janakiram Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No. # 20 Concurrency Control Part -1 Foundations for concurrency

More information

L i (A) = transaction T i acquires lock for element A. U i (A) = transaction T i releases lock for element A

L i (A) = transaction T i acquires lock for element A. U i (A) = transaction T i releases lock for element A Lock-Based Scheduler Introduction to Data Management CSE 344 Lecture 20: Transactions Simple idea: Each element has a unique lock Each transaction must first acquire the lock before reading/writing that

More information

Chapter 13 : Concurrency Control

Chapter 13 : Concurrency Control Chapter 13 : Concurrency Control Chapter 13: Concurrency Control Lock-Based Protocols Timestamp-Based Protocols Validation-Based Protocols Multiple Granularity Multiversion Schemes Insert and Delete Operations

More information

PROCEDURAL DATABASE PROGRAMMING ( PL/SQL AND T-SQL)

PROCEDURAL DATABASE PROGRAMMING ( PL/SQL AND T-SQL) Technology & Information Management Instructor: Michael Kremer, Ph.D. Class 10 Database Programming PROCEDURAL DATABASE PROGRAMMING ( PL/SQL AND T-SQL) AGENDA 14. Advanced Topics 14.1 Optimistic/Pessimistic

More information

SQL: Transactions. Introduction to Databases CompSci 316 Fall 2017

SQL: Transactions. Introduction to Databases CompSci 316 Fall 2017 SQL: Transactions Introduction to Databases CompSci 316 Fall 2017 2 Announcements (Tue., Oct. 17) Midterm graded Sample solution already posted on Sakai Project Milestone #1 feedback by email this weekend

More information

CSE 190D Database System Implementation

CSE 190D Database System Implementation CSE 190D Database System Implementation Arun Kumar Topic 6: Transaction Management Chapter 16 of Cow Book Slide ACKs: Jignesh Patel 1 Transaction Management Motivation and Basics The ACID Properties Transaction

More information

Transactions and Isolation

Transactions and Isolation Transactions and Isolation Tom Kelliher, CS 318 Apr. 29, 2002 1 Administrivia Announcements Normal form analyses due Wednesday. Toolboxes and projects due Friday. Review for final on Friday. Course evaluation

More information

TRANSACTION PROCESSING PROPERTIES OF A TRANSACTION TRANSACTION PROCESSING PROPERTIES OF A TRANSACTION 4/3/2014

TRANSACTION PROCESSING PROPERTIES OF A TRANSACTION TRANSACTION PROCESSING PROPERTIES OF A TRANSACTION 4/3/2014 TRANSACTION PROCESSING SYSTEMS IMPLEMENTATION TECHNIQUES TRANSACTION PROCESSING DATABASE RECOVERY DATABASE SECURITY CONCURRENCY CONTROL Def: A Transaction is a program unit ( deletion, creation, updating

More information

T ransaction Management 4/23/2018 1

T ransaction Management 4/23/2018 1 T ransaction Management 4/23/2018 1 Air-line Reservation 10 available seats vs 15 travel agents. How do you design a robust and fair reservation system? Do not enough resources Fair policy to every body

More information

Transactions and Locking. Rose-Hulman Institute of Technology Curt Clifton

Transactions and Locking. Rose-Hulman Institute of Technology Curt Clifton Transactions and Locking Rose-Hulman Institute of Technology Curt Clifton Outline ACID Transactions COMMIT and ROLLBACK Managing Transactions Locks The Setting Database systems are normally being accessed

More information

Introduction to Data Management CSE 344

Introduction to Data Management CSE 344 Introduction to Data Management CSE 344 Unit 7: Transactions Schedules Implementation Two-phase Locking (3 lectures) 1 Class Overview Unit 1: Intro Unit 2: Relational Data Models and Query Languages Unit

More information

Database Tuning and Physical Design: Execution of Transactions

Database Tuning and Physical Design: Execution of Transactions Database Tuning and Physical Design: Execution of Transactions Spring 2018 School of Computer Science University of Waterloo Databases CS348 (University of Waterloo) Transaction Execution 1 / 20 Basics

More information

CSE 444: Database Internals. Lectures Transactions

CSE 444: Database Internals. Lectures Transactions CSE 444: Database Internals Lectures 13-14 Transactions CSE 444 - Spring 2014 1 Announcements Lab 2 is due TODAY Lab 3 will be released today, part 1 due next Monday HW4 is due on Wednesday HW3 will be

More information

Concurrency Control. R &G - Chapter 19

Concurrency Control. R &G - Chapter 19 Concurrency Control R &G - Chapter 19 Smile, it is the key that fits the lock of everybody's heart. Anthony J. D'Angelo, The College Blue Book Review DBMSs support concurrency, crash recovery with: ACID

More information

Intro to Transaction Management

Intro to Transaction Management Intro to Transaction Management CMPSCI 645 May 3, 2006 Gerome Miklau Slide content adapted from Ramakrishnan & Gehrke, Zack Ives 1 Concurrency Control Concurrent execution of user programs is essential

More information

DATABASE DESIGN I - 1DL300

DATABASE DESIGN I - 1DL300 DATABASE DESIGN I - 1DL300 Spring 2011 An introductory course on database systems http://www.it.uu.se/edu/course/homepage/dbastekn/vt11/ Manivasakan Sabesan Uppsala Database Laboratory Department of Information

More information

TRANSACTION PROPERTIES

TRANSACTION PROPERTIES Transaction Is any action that reads from and/or writes to a database. A transaction may consist of a simple SELECT statement to generate a list of table contents; it may consist of series of INSERT statements

More information

Transaction Management: Concurrency Control, part 2

Transaction Management: Concurrency Control, part 2 Transaction Management: Concurrency Control, part 2 CS634 Class 16 Slides based on Database Management Systems 3 rd ed, Ramakrishnan and Gehrke Locking for B+ Trees Naïve solution Ignore tree structure,

More information

Locking for B+ Trees. Transaction Management: Concurrency Control, part 2. Locking for B+ Trees (contd.) Locking vs. Latching

Locking for B+ Trees. Transaction Management: Concurrency Control, part 2. Locking for B+ Trees (contd.) Locking vs. Latching Locking for B+ Trees Transaction Management: Concurrency Control, part 2 Slides based on Database Management Systems 3 rd ed, Ramakrishnan and Gehrke CS634 Class 16 Naïve solution Ignore tree structure,

More information

SQL: Transactions. Announcements (October 2) Transactions. CPS 116 Introduction to Database Systems. Project milestone #1 due in 1½ weeks

SQL: Transactions. Announcements (October 2) Transactions. CPS 116 Introduction to Database Systems. Project milestone #1 due in 1½ weeks SQL: Transactions CPS 116 Introduction to Database Systems Announcements (October 2) 2 Project milestone #1 due in 1½ weeks Come to my office hours if you want to chat about project ideas Midterm in class

More information

Concurrency Control & Recovery

Concurrency Control & Recovery Transaction Management Overview CS 186, Fall 2002, Lecture 23 R & G Chapter 18 There are three side effects of acid. Enhanced long term memory, decreased short term memory, and I forget the third. - Timothy

More information

Introduction. Storage Failure Recovery Logging Undo Logging Redo Logging ARIES

Introduction. Storage Failure Recovery Logging Undo Logging Redo Logging ARIES Introduction Storage Failure Recovery Logging Undo Logging Redo Logging ARIES Volatile storage Main memory Cache memory Nonvolatile storage Stable storage Online (e.g. hard disk, solid state disk) Transaction

More information

Introduction to Data Management CSE 344

Introduction to Data Management CSE 344 Introduction to Data Management CSE 344 Lecture 22: More Transaction Implementations 1 Review: Schedules, schedules, schedules The DBMS scheduler determines the order of operations from txns are executed

More information

UNIT-IV TRANSACTION PROCESSING CONCEPTS

UNIT-IV TRANSACTION PROCESSING CONCEPTS 1 Transaction UNIT-IV TRANSACTION PROCESSING CONCEPTS A Transaction refers to a logical unit of work in DBMS, which comprises a set of DML statements that are to be executed atomically (indivisibly). Commit

More information

How Oracle Does It. No Read Locks

How Oracle Does It. No Read Locks How Oracle Does It Oracle Locking Policy No Read Locks Normal operation: no read locks Readers do not inhibit writers Writers do not inhibit readers Only contention is Write-Write Method: multiversion

More information

Foundation of Database Transaction Processing. Copyright 2012 Pearson Education, Inc.

Foundation of Database Transaction Processing. Copyright 2012 Pearson Education, Inc. Foundation of Database Transaction Processing Copyright 2012 Pearson Education, Inc. Chapter Outline - 17.1 Introduction to Transaction Processing - 17.2 Transaction and System Concepts - 17.3 Desirable

More information

Phantom Problem. Phantom Problem. Phantom Problem. Phantom Problem R1(X1),R1(X2),W2(X3),R1(X1),R1(X2),R1(X3) R1(X1),R1(X2),W2(X3),R1(X1),R1(X2),R1(X3)

Phantom Problem. Phantom Problem. Phantom Problem. Phantom Problem R1(X1),R1(X2),W2(X3),R1(X1),R1(X2),R1(X3) R1(X1),R1(X2),W2(X3),R1(X1),R1(X2),R1(X3) 57 Phantom Problem So far we have assumed the database to be a static collection of elements (=tuples) If tuples are inserted/deleted then the phantom problem appears 58 Phantom Problem INSERT INTO Product(name,

More information

Information Systems (Informationssysteme)

Information Systems (Informationssysteme) Information Systems (Informationssysteme) Jens Teubner, TU Dortmund jens.teubner@cs.tu-dortmund.de Summer 2016 c Jens Teubner Information Systems Summer 2016 1 Part VIII Transaction Management c Jens Teubner

More information

Locking, concurrency, and isolation

Locking, concurrency, and isolation Holdable result sets and autocommit When autocommit is on, a positioned update or delete statement will automatically cause the transaction to commit. If the result set has holdability ResultSet.CLOSE_CURSORS_AT_COMMIT,

More information

Overview of Transaction Management

Overview of Transaction Management Overview of Transaction Management Chapter 16 Comp 521 Files and Databases Fall 2010 1 Database Transactions A transaction is the DBMS s abstract view of a user program: a sequence of database commands;

More information

Advanced Databases. Lecture 9- Concurrency Control (continued) Masood Niazi Torshiz Islamic Azad University- Mashhad Branch

Advanced Databases. Lecture 9- Concurrency Control (continued) Masood Niazi Torshiz Islamic Azad University- Mashhad Branch Advanced Databases Lecture 9- Concurrency Control (continued) Masood Niazi Torshiz Islamic Azad University- Mashhad Branch www.mniazi.ir Multiple Granularity Allow data items to be of various sizes and

More information

RNDr. Michal Kopecký, Ph.D. Department of Software Engineering, Faculty of Mathematics and Physics, Charles University in Prague

RNDr. Michal Kopecký, Ph.D. Department of Software Engineering, Faculty of Mathematics and Physics, Charles University in Prague course: Database Applications (NDBI026) WS2015/16 RNDr. Michal Kopecký, Ph.D. Department of Software Engineering, Faculty of Mathematics and Physics, Charles University in Prague Transactions Transactional

More information

Understanding Isolation Levels and Locking

Understanding Isolation Levels and Locking Platform: DB2 UDB for Linux, UNIX, and Windows Understanding Isolation Levels and Locking Roger E. Sanders Network Appliance, Inc. Global Systems Engineer Session: G10 Wednesday, 26 October 2005 11:00

More information

TRANSACTION PROCESSING CONCEPTS

TRANSACTION PROCESSING CONCEPTS 1 Transaction CHAPTER 9 TRANSACTION PROCESSING CONCEPTS A Transaction refers to a logical unit of work in DBMS, which comprises a set of DML statements that are to be executed atomically (indivisibly).

More information

CS 5614: Transaction Processing 121. Transaction = Unit of Work Recall ACID Properties (from Module 1)

CS 5614: Transaction Processing 121. Transaction = Unit of Work Recall ACID Properties (from Module 1) CS 5614: Transaction Processing 121 Module 3: Transaction Processing Transaction = Unit of Work Recall ACID Properties (from Module 1) Requirements of Transactions in a DBMS 7-by-24 access Concurrency

More information

CMP-3440 Database Systems

CMP-3440 Database Systems CMP-3440 Database Systems Concurrency Control with Locking, Serializability, Deadlocks, Database Recovery Management Lecture 10 zain 1 Basic Recovery Facilities Backup Facilities: provides periodic backup

More information

Transaction Management & Concurrency Control. CS 377: Database Systems

Transaction Management & Concurrency Control. CS 377: Database Systems Transaction Management & Concurrency Control CS 377: Database Systems Review: Database Properties Scalability Concurrency Data storage, indexing & query optimization Today & next class Persistency Security

More information

Overview. Introduction to Transaction Management ACID. Transactions

Overview. Introduction to Transaction Management ACID. Transactions Introduction to Transaction Management UVic C SC 370 Dr. Daniel M. German Department of Computer Science Overview What is a transaction? What properties transactions have? Why do we want to interleave

More information

Mark Broadbent Principal Consultant SQLCloud SQLCLOUD.CO.UK

Mark Broadbent Principal Consultant SQLCloud SQLCLOUD.CO.UK lock, block & two smoking barrels Mark Broadbent Principal Consultant SQLCloud SQLCLOUD.CO.UK About Mark Broadbent. 30 billion times more intelligent than a live mattress Microsoft Certified Master/ Certified

More information

Concurrency. Consider two ATMs running in parallel. We need a concurrency manager. r1[x] x:=x-250 r2[x] x:=x-250 w[x] commit w[x] commit

Concurrency. Consider two ATMs running in parallel. We need a concurrency manager. r1[x] x:=x-250 r2[x] x:=x-250 w[x] commit w[x] commit DBMS ARCHITECTURE Concurrency Consider two ATMs running in parallel T1 T2 r1[x] x:=x-250 r2[x] x:=x-250 w[x] commit w[x] commit We need a concurrency manager Examples of interference T1: r[x=100] w[x:=600]

More information

Chapter 12 : Concurrency Control

Chapter 12 : Concurrency Control Chapter 12 : Concurrency Control Chapter 12: Concurrency Control Lock-Based Protocols Timestamp-Based Protocols Validation-Based Protocols Multiple Granularity Multiversion Schemes Insert and Delete Operations

More information

Goal of Concurrency Control. Concurrency Control. Example. Solution 1. Solution 2. Solution 3

Goal of Concurrency Control. Concurrency Control. Example. Solution 1. Solution 2. Solution 3 Goal of Concurrency Control Concurrency Control Transactions should be executed so that it is as though they executed in some serial order Also called Isolation or Serializability Weaker variants also

More information

2 Copyright 2015 M. E. Kabay. All rights reserved. 4 Copyright 2015 M. E. Kabay. All rights reserved.

2 Copyright 2015 M. E. Kabay. All rights reserved. 4 Copyright 2015 M. E. Kabay. All rights reserved. Application Controls CSH6 Chapter 52 Application Controls Myles Walsh Topics Protection in Development Protecting Databases Protecting Batch Files Ensuring that Information in the System is Valid 1 Copyright

More information

Database Systems. Announcement

Database Systems. Announcement Database Systems ( 料 ) December 27/28, 2006 Lecture 13 Merry Christmas & New Year 1 Announcement Assignment #5 is finally out on the course homepage. It is due next Thur. 2 1 Overview of Transaction Management

More information

) Intel)(TX)memory):) Transac'onal) Synchroniza'on) Extensions)(TSX))) Transac'ons)

) Intel)(TX)memory):) Transac'onal) Synchroniza'on) Extensions)(TSX))) Transac'ons) ) Intel)(TX)memory):) Transac'onal) Synchroniza'on) Extensions)(TSX))) Transac'ons) Goal A Distributed Transaction We want a transaction that involves multiple nodes Review of transactions and their properties

More information

Distributed Data Analytics Transactions

Distributed Data Analytics Transactions Distributed Data Analytics G-3.1.09, Campus III Hasso Plattner Institut must ensure that interactions succeed consistently An OLTP Topic Motivation Most database interactions consist of multiple, coherent

More information

) Intel)(TX)memory):) Transac'onal) Synchroniza'on) Extensions)(TSX))) Transac'ons)

) Intel)(TX)memory):) Transac'onal) Synchroniza'on) Extensions)(TSX))) Transac'ons) ) Intel)(TX)memory):) Transac'onal) Synchroniza'on) Extensions)(TSX))) Transac'ons) Goal A Distributed Transaction We want a transaction that involves multiple nodes Review of transactions and their properties

More information

Introduction to Data Management CSE 414

Introduction to Data Management CSE 414 Introduction to Data Management CSE 414 Lecture 23: Transactions CSE 414 - Winter 2014 1 Announcements Webquiz due Monday night, 11 pm Homework 7 due Wednesday night, 11 pm CSE 414 - Winter 2014 2 Where

More information

Does the Optimistic Concurrency resolve your blocking problems? Margarita Naumova, SQL Master Academy

Does the Optimistic Concurrency resolve your blocking problems? Margarita Naumova, SQL Master Academy Does the Optimistic Concurrency resolve your blocking problems? Margarita Naumova, SQL Master Academy MAGI NAUMOVA Working with SQL Server from v6.5 SQL Server Trainer and Consultant with over 60 projects

More information

Transaction Processing: Concurrency Control. Announcements (April 26) Transactions. CPS 216 Advanced Database Systems

Transaction Processing: Concurrency Control. Announcements (April 26) Transactions. CPS 216 Advanced Database Systems Transaction Processing: Concurrency Control CPS 216 Advanced Database Systems Announcements (April 26) 2 Homework #4 due this Thursday (April 28) Sample solution will be available on Thursday Project demo

More information

CSC 261/461 Database Systems Lecture 21 and 22. Spring 2017 MW 3:25 pm 4:40 pm January 18 May 3 Dewey 1101

CSC 261/461 Database Systems Lecture 21 and 22. Spring 2017 MW 3:25 pm 4:40 pm January 18 May 3 Dewey 1101 CSC 261/461 Database Systems Lecture 21 and 22 Spring 2017 MW 3:25 pm 4:40 pm January 18 May 3 Dewey 1101 Announcements Project 3 (MongoDB): Due on: 04/12 Work on Term Project and Project 1 The last (mini)

More information

Implementing Isolation

Implementing Isolation CMPUT 391 Database Management Systems Implementing Isolation Textbook: 20 & 21.1 (first edition: 23 & 24.1) University of Alberta 1 Isolation Serial execution: Since each transaction is consistent and

More information