Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
140 views

SQL Transactions12

This document discusses concurrency control in databases. It defines transactions and concurrency. Transactions are units of work that can commit or rollback changes to the database. The document describes different transaction statements in Transact-SQL like BEGIN TRANSACTION, COMMIT, and ROLLBACK. It also discusses properties of transactions like atomicity, consistency, isolation, and durability (ACID) and how locking and deadlocks are used for concurrency control.

Uploaded by

Gammee Bekele
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
140 views

SQL Transactions12

This document discusses concurrency control in databases. It defines transactions and concurrency. Transactions are units of work that can commit or rollback changes to the database. The document describes different transaction statements in Transact-SQL like BEGIN TRANSACTION, COMMIT, and ROLLBACK. It also discusses properties of transactions like atomicity, consistency, isolation, and durability (ACID) and how locking and deadlocks are used for concurrency control.

Uploaded by

Gammee Bekele
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Table of Content

Table of Content.....................................................................................................................................................................I
CONCURRENCY CONTROL.............................................................................................................................................1
Transact-SQL Statements and Transactions..........................................................................................................................2
Properties of Transactions:....................................................................................................................................................4
Transaction Log.................................................................................................................................................................... 5
Locking................................................................................................................................................................................. 5
Deadlock...............................................................................................................................................................................7
Exercises...............................................................................................................................................................................7

I
II
CONCURRENCY CONTROL

Concurrency:-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.

Database Engine supports two different concurrency control 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 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. 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.
A transaction:- is a unit of work that is performed against a database. Transactions are units or sequences of
work accomplished in a logical order, whether in a manual fashion by a user or automatically by some sort of a
database program.
A transaction is the propagation of one or more changes to the database. For example, if you are Inserting a
record or updating a record or deleting a record from the table, then you are performing transaction on the table.
It is important to control transactions to ensure data integrity and to handle database errors.

1
Practically, you will club many SQL queries into a group and you will execute all of them together as a part of a
transaction.

There are two forms of transactions:

 Implicit Specifies any single INSERT, UPDATE, or DELETE statement as a transaction unit.
 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.

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 [ {transaction_name | @trans_var }

[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 statements. @trans_var
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.
2
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, where is a need for a coordinator, which 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.

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.)

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.)

The SAVE TRANSACTION statement sets a save point 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.)

Note:-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:

Create a database by the name Sample

Create database Sample;


Consider the Customers table having the following records:

3
Create the table Customers under the database sample and insert the records in the customers table

USE SAMPLE;

CREATE TABLE CUSTOMERS

ID INT NOT NULL,

NAME VARCHAR(30),

AGE INT NOT NULL CHEAK(AGE>=18 AND AGE<=100),

ADDRESS VARCHAR(30),

SALARY DECIMAL(18, 2)

);

Insert all records given above in the customers table

See the content of the table using Select Statement

Select * from Customers;

Example below shows the use of the SAVE TRANSACTION statement.

BEGIN TRANSACTION;

INSERT INTO Customers (ID, NAME, AGE, ADDRESS, SALARY)

VALUES ('4', ' Chaitali' , '25', ' Mumbai', ' 6500.00');

SAVE TRANSACTION SP1;

INSERT INTO Customers (ID, NAME, AGE, ADDRESS, SALARY)

4
VALUES ('5', ' Hardik ', '27', ' Bhopal',' 8500.00');

SAVE TRANSACTION SP2;

INSERT INTO Customers (ID, NAME, AGE, ADDRESS, SALARY)

VALUES ('6', ' Komal ','22', 'MP', ' 4500.00');

ROLLBACK TRANSACTION SP2;

INSERT INTO Customers (ID, NAME, AGE, ADDRESS, SALARY)

VALUES ('7', ' Muffy ','24', ' Indore','10000.00');

ROLLBACK TRANSACTION SP1;

COMMIT TRANSACTION;

The only statement in Example above that is executed is the first INSERT statement. The third INSERT
statement is rolled back by the ROLLBACK SP2 statement, while the other two INSERT statements are rolled
back by the ROLLBACK SP1 statement.

See the result using select statement

Select * from Customers;

The result of Select statement is

5
Properties of Transactions:
Transactions have the following four standard properties, usually referred to by the acronym ACID:

 Atomicity: ensures that all operations within the work unit are completed successfully; otherwise, the
transaction is aborted at the point of failure, and previous operations are rolled back to their former state.

 Consistency: ensures that the database properly changes states upon a successfully committed
transaction.

 Isolation: enables transactions to operate independently of and transparent to each other.


 Durability: ensures that the result or effect of a committed transaction persists in case of a system
failure.

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.

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, Database Engine uses the entries in the
transaction log to restore the values of columns that the database had before the transaction was started.

6
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 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 so called after images. After images are all after 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.

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

In order to execute transactions in an interleaved manner it is necessary to have some form of concurrency
control. One method of avoiding problems is with the use of locks.

Locking is necessary in a concurrent environment to assure that one process does not retrieve or update a record
that is being updated by another process. Failure to use some controls (locking), would result in inconsistent and
corrupt data.

Locks enable a multi-user DBMS to maintain the integrity of transactions by isolating a transaction from others
executing concurrently. Locks are particularly critical in write-intensive and mixed workload (read/write)
environments, because they can prevent the inadvertent loss of data or Consistency problems with reads.

In addition to record locking, DBMS implements several other locking mechanisms to ensure the integrity of
other data structures that provide shared I/O, communication among different processes in a cluster and
automatic recovery in the event of a process or cluster failure.

Aside from their integrity implications, locks can have a significant impact on performance. While it may
benefit a given application to lock a large amount of data (perhaps one or more tables) and hold these locks for

7
a long period of time, doing so inhibits concurrency and increases the likelihood that other applications will
have to wait for locked resources.

Locking has several different aspects:

 Lock duration
 Lock modes
 Lock granularity

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.

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.

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

8
the same object.) If a transaction that 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.

Lock granularity specifies which resource is locked by a single lock attempt. Database Engine can lock the
following resources:

 Row
 Page
 Index key or range of index keys
 Table
 Extent
 Database itself

Lock granularity affects concurrency. In general, the larger the lock granularity used, 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.
Pagelevel locking (and table-level locking) restricts the availability of data but decreases the system overhead.

Lock Escalation:- If many locks of the same lock granularity are held during a transaction, 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.

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.)

9
Exercises
1. What is a purpose of transactions?
2. What is distributed database?
3. What is the difference between single user DBMS and multi user DBMS?
4. What is the difference between a local and a distributed transaction?
5. What is the difference between implicit and explicit transaction mode?
6. How can you test the successful execution of each T-SQL statement?
7. When should you use the SAVE TRANSACTION statement?
8. What does lock escalation mean?
9. What is deadlock?

10

You might also like