0% found this document useful (0 votes)
41 views7 pages

Understanding Database Transactions in SQL

The document explains transactions in databases, detailing their properties (ACID) and modes (autocommit, implicit, explicit). It covers transaction management commands like COMMIT, ROLLBACK, and SAVEPOINT, along with concepts of locking, blocking, and deadlocks. Additionally, it introduces memory-optimized tables in SQL Server for improved performance in high-volume OLTP applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views7 pages

Understanding Database Transactions in SQL

The document explains transactions in databases, detailing their properties (ACID) and modes (autocommit, implicit, explicit). It covers transaction management commands like COMMIT, ROLLBACK, and SAVEPOINT, along with concepts of locking, blocking, and deadlocks. Additionally, it introduces memory-optimized tables in SQL Server for improved performance in high-volume OLTP applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Transactions

A transaction is the logical work unit that performs a single activity or multiple activities in a
database. Transactions may consist of a single read, write, delete, or update operations or a
combination of these. Suppose that, when we want to withdraw money from the ATM, the ATM
application will achieve this operation in three steps. As a first step, the application will check
the balance of the account, and then it will deduct the money from the source account. Along
with these two processes, it will keep the log of this money withdrawing activity. The following
image basically illustrates the working principle of the transactions in the relational database
systems.

The main idea of transactions is that when each of the statements returns an error, the entire
modifications rollback to provide data integrity. On the other hand, if all statements are
completed successfully the data modifications will become permanent on the database. As a
result, if we experience any power outage or other problems during the withdrawal of money
from an ATM, transactions guarantee our balance consistency. It would be the best method to
perform all these steps through a transaction because the four main properties of the
transactions enable all operations more accurate and consistent. All these properties are known
as the ACID (atomicity, consistency, isolation, durability) in the relational database systems with
the first letter of their names.

Atomicity: The entire of the operations that are included by the transaction performed
successfully. Otherwise, all operations are canceled at the point of the failure and all the
previous operations are rolled back
Consistency: This property ensures that all the data will be consistent after a transaction is
completed according to the defined rules, constraints, cascades, and triggers

Isolation: All transactions are isolated from other transactions

Durable: The modification of the commited transactions becomes persist in the database

Creating a sample table -

CREATE TABLE Person (


PersonID int PRIMARY KEY IDENTITY(1,1),
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255),
Age INT
)

GO

INSERT INTO Person VALUES('Hayes', 'Corey','123 Wern Ddu Lane','LUSTLEIGH',23)


INSERT INTO Person VALUES('Macdonald','Charlie','23 Peachfield Road','CEFN EINION',45)
INSERT INTO Person VALUES('Frost','Emma','85 Kingsway North','HOLTON',26)
INSERT INTO Person VALUES('Thomas', 'Tom','59 Dover Road', 'WESTER GRUINARDS',51)
INSERT INTO Person VALUES('Baxter','Cameron','106 Newmarket Road','HAWTHORPE',46)
INSERT INTO Person VALUES('Townsend','Imogen ','100 Shannon Way','CHIPPENHAM',20)
INSERT INTO Person VALUES('Preston','Taylor','14 Pendwyallt Road','BURTON',19)
INSERT INTO Person VALUES('Townsend','Imogen ','100 Shannon Way','CHIPPENHAM',18)
INSERT INTO Person VALUES('Khan','Jacob','72 Ballifeary Road','BANCFFOSFELEN',11)

Modes of the Transactions in SQL Server

[Link] Transaction mode is the default transaction for the SQL Server. In this mode,
each T-SQL statement is evaluated as a transaction and they are committed or rolled back
according to their results. The successful statements are committed and the failed statements
are rolled back immediately

[Link] transaction mode enables to SQL Server to start an implicit transaction for every
DML statement but we need to use the commit or rolled back commands explicitly at the end of
the statements
[Link] transaction mode provides to define a transaction exactly with the starting and
ending points of the transaction

Define an Implicit Transaction -

to define an implicit transaction, we need to enable the IMPLICIT_TRANSACTIONS option

SET IMPLICIT_TRANSACTIONS ON
UPDATE
Person
SET
Lastname = 'Sawyer',
Firstname = 'Tom'
WHERE
PersonID = 2
SELECT
IIF(@@OPTIONS & 2 = 2,
'Implicit Transaction Mode ON',
'Implicit Transaction Mode OFF'
) AS 'Transaction Mode'
SELECT
@@TRANCOUNT AS OpenTransactions
COMMIT TRAN
SELECT
@@TRANCOUNT AS OpenTransactions

The COMMIT TRANSACTION statement applies the data changes to the database and the
changed data will become permanent.

Define an Explicit Transaction -

Define an explicit transaction, we start to use the BEGIN TRANSACTION command because
this statement identifies the starting point of the explicit transaction.

BEGIN TRANSACTION [ {transaction_name | @tran_name_variable }


[WITH MARK ['description']]]

After defining an explicit transaction through the BEGIN TRANSACTION command, the related
resources acquired a lock depending on the isolation level of the transaction. For this reason as
possible to use the shortest transaction will help to reduce lock issues. The following statement
starts a transaction and then it will change the name of a particular row in the Person table.

BEGIN TRAN
UPDATE Person
SET Lastname = 'Lucky',
Firstname = 'Luke'
WHERE PersonID = 1

SELECT @@TRANCOUNT AS OpenTransactions

As we stated in the previous section COMMIT TRAN statement applies the data changes to the
database and the changed data will become permanent. Now let’s complete the open
transaction with a COMMIT TRAN statement.

BEGIN TRAN
UPDATE Person
SET Lastname = 'Lucky',
Firstname = 'Luke'
WHERE PersonID = 1
SELECT @@TRANCOUNT AS OpenTransactions
COMMIT TRAN
SELECT @@TRANCOUNT AS OpenTransactions

On the other hand, the ROLLBACK TRANSACTION statement helps in undoing all data
modifications that are applied by the transaction. In the following example, we will change a
particular row but this data modification will not persist.

BEGIN TRAN
UPDATE Person
SET Lastname = 'Donald',
Firstname = 'Duck' WHERE PersonID=2

SELECT * FROM Person WHERE PersonID=2

ROLLBACK TRAN

SELECT * FROM Person WHERE PersonID=2

Save Points in Transactions -

Savepoints can be used to rollback any particular part of the transaction rather than the entire
transaction. So that we can only rollback any portion of the transaction where between after the
save point and before the rollback command. To define a save point in a transaction we use the
SAVE TRANSACTION syntax and then we add a name to the save point. Now, let’s illustrates
an example of savepoint usage.

BEGIN TRANSACTION
INSERT INTO Person
VALUES('Mouse', 'Micky','500 South Buena Vista Street, Burbank','California',43)
SAVE TRANSACTION InsertStatement
DELETE Person WHERE PersonID=3
SELECT * FROM Person
ROLLBACK TRANSACTION InsertStatement
COMMIT
SELECT * FROM Person

Example -2

BEGIN TRANSACTION
SAVE TRANSACTION SavePoint1
INSERT INTO Student(Name) VALUES ( 'Ramesh')
INSERT INTO Student(Name) VALUES ( 'Suresh')
SAVE TRANSACTION SavePoint2
INSERT INTO Student(Name) VALUES ( 'Priyanka')
INSERT INTO Student(Name) VALUES ( 'Preety')
SAVE TRANSACTION SavePoint3
INSERT INTO Student(Name) VALUES ( 'John')
INSERT INTO Student(Name) VALUES ( 'David')

Rollback Transaction SavePoint2;

Commit Transaction;

Auto Rollback transactions in SQL Server

Generally, the transactions include more than one query. In this manner, if one of the SQL
statements returns an error all modifications are erased, and the remaining statements are not
executed. This process is called Auto Rollback Transaction in SQL.

BEGIN TRAN
INSERT INTO Person
VALUES('Bunny', 'Bugs','742 Evergreen Terrace','Springfield',54)

UPDATE Person SET Age='MiddleAge' WHERE PersonID=7


SELECT * FROM Person
COMMIT TRAN

Locking, Blocking, And Deadlocks

Locking, blocking and deadlocks are related concepts in SQL Server that deal with controlling
concurrent access to data in a database. Concurrent access to data in a database refers to
multiple users or processes accessing the same data simultaneously. This can occur when
multiple transactions are executed at the same time, each trying to read or modify the same
data. To ensure data integrity and consistency, a database management system like Microsoft
SQL Server uses mechanisms such as locking and blocking to control access to data and
prevent conflicting updates from occurring. Proper management of concurrent access is
important for the performance and stability of a database system.

Locking:
Locking is a mechanism used by SQL Server to control concurrent access to data and ensure
data integrity and consistency. Locks are acquired on data when a transaction starts and
released when it ends.

Blocking:
Blocking problems when one transaction holds a lock on a piece of data that another transaction
wants to access. The second transaction has to wait for the first to release the lock before it can
continue. This can lead to performance issues and delay the completion of transactions.

Deadlocks:
Deadlocks occur when two or more transactions are blocked and each is waiting for the other to
release a lock, resulting in a circular wait. This can lead to an indefinite wait situation and
requires manual intervention to resolve. Deadlocks can be identified and resolved using SQL
Server's Dynamic Management View (DMV) or by using SSMS, performance monitor or custom
code as discussed below.

The Infamous (NOLOCK)


In SQL Server, locking hints are used to specify the type of lock that should be acquired on a
table or row when a query is executed. Locking hints can be used to override the default locking
behavior of the SQL Server query optimizer.

NOLOCK:
Specifies that a query should not acquire any locks on the table or row being accessed. This
can improve performance, but can also lead to dirty reads (reading data that is in the middle of
being modified) or non-repeatable reads (reading data that has been modified since it was last
read).
How Can I Prevent SQL BLocking With NOLOCK
The NOLOCK hint can be used to specify that a query should not acquire any locks on the table
or row being accessed. This hint can be added to a SELECT statement by including the
keyword "WITH (NOLOCK)" in the FROM clause

SELECT * FROM MyTable WITH (NOLOCK)

SELECT * FROM MyTable1 WITH (NOLOCK)


JOIN MyTable2 WITH (NOLOCK) ON [Link] = [Link]

SQL Server Memory Optimized Tables

The in-memory OLTP feature was introduced with SQL Server 2014 and it has 2 parts; memory-
optimized tables and natively complied stored procedures. The main benefit of memory-
optimized tables are that rows in the table are read from and written to memory which results in
non-blocking transactions at super-fast speed. The second copy of the data is stored on the disk
and during database recovery, data is read from the disk-based table. Memory-optimized tables
are for specific types of workloads such as high volume OLTP applications.

-- Now create a memory optimized temporal table Customer2 and insert the same 3 rows
CREATE TABLE Customer2 (
CustomerId INT IDENTITY(1,1)
,FirstName VARCHAR(30) NOT NULL
,LastName VARCHAR(30) NOT NULL
,Amount_purchased DECIMAL NOT NULL
,StartDate datetime2 generated always as row START NOT NULL
,EndDate datetime2 generated always as row END NOT NULL
,PERIOD FOR SYSTEM_TIME (StartDate, EndDate),
CONSTRAINT [PK_CustomerID] PRIMARY KEY NONCLUSTERED HASH (CustomerId) WITH
(BUCKET_COUNT = 131072)
)
WITH(MEMORY_OPTIMIZED = ON, DURABILITY = SCHEMA_AND_DATA,
SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.Customer2History))
GO

You might also like