Skip to content

Commit 06c6f86

Browse files
committed
Tech/copy edit
1 parent 7ff3c74 commit 06c6f86

File tree

1 file changed

+53
-42
lines changed
  • docs/guides/databases/mysql/primer-on-sql-transactions

1 file changed

+53
-42
lines changed

docs/guides/databases/mysql/primer-on-sql-transactions/index.md

Lines changed: 53 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,11 @@ slug: a-primer-on-sql-transactions
33
author:
44
name: Linode Community
55
6-
description: 'In this guide, you see what SQL transactions are and its importance in the database integrity with examples.'
6+
description: 'SQL transactions help maintain database integrity. This guide outlines some transaction benefits and how to use the delimiter, commit, and rollback syntax.'
77
keywords: ['sql transactions', 'commit transaction', 'rollback transaction', 'SQL transaction delimiter']
88
tags: ['mysql', 'database']
99
license: '[CC BY-ND 4.0](https://creativecommons.org/licenses/by-nd/4.0)'
10-
published: 2022-05-30
10+
published: 2022-08-25
1111
modified_by:
1212
name: Linode
1313
title: "A Primer on SQL Transactions"
@@ -18,74 +18,87 @@ contributor:
1818
link: http://nhzsolutions.com/
1919
---
2020

21-
In SQL, transactions are essential for maintaining database integrity when dealing with multiple related operations as well as when multiple users are interacting with a database concurrently. In this guide, you learn the concept of SQL Transactions, what they are, and how to work with them.
22-
2321
## What are SQL Transactions?
2422

25-
SQL Transactions is a grouping of logical statements that can contain one or more SQL statements that interact within a database. A transaction in its entirety can *commit* to a database as a single logical unit or *rollback* (undone) as a single logical unit.
23+
A SQL *transaction* is a grouping of one or more SQL statements that interact with a database. A transaction in its entirety can *commit* to a database as a single logical unit or *rollback* (undone) as a single logical unit. In SQL, transactions are essential for maintaining database integrity. They are used to preserve integrity when multiple related operations are executed concurrently, or when multiple users interact with a database concurrently.
2624

27-
## Why are SQL Transactions Necessary?
25+
## In this Guide
26+
27+
This guide demonstrates:
28+
29+
- [Why SQL transactions are necessary](#why-are-sql-transactions-necessary)
2830

29-
In certain instances, a database application has to account for every possible failure scenario while writing and reading from a database. While ensuring that every aspect of database integrity is not violated, application code is extremely complex, convoluted, and expensive to develop, and maintain.
31+
- How to better understand SQL transactions through [an example use-case of a financial brokerage](#understanding-sql-transactions-with-an-example)
3032

31-
Using SQL Transactions, code/maintenance can be simplified. Using commit and rollback transactions as necessary, database integrity can easily be maintained.
33+
- The transaction [delimiter](#sql-transaction-delimiter-syntax), [commit](#commit-transaction-syntax), and [roll back](#roll-back-transaction-syntax) syntax
3234

33-
### Understanding SQL Transactions With an Example
35+
- How the delimiter, commit, and roll back syntax are used in [an example use-case for a school](#database-transaction-examples)
36+
37+
- Some further [benefits of using transactions](#more-benefits-of-using-transactions)
38+
39+
## Why are SQL Transactions Necessary?
3440

35-
For example, consider a financial brokerage that maintains a database for its clients. The brokerage is required to generate a quarterly financial statement for each of its clients that reports on statement balance, current values of holdings, and any transactions that occurred during the quarter. Hypothetically, you may need to process the following steps:
41+
A database application has to account for every possible failure scenario while writing and reading from a database. Without SQL transactions, application code that protects database integrity would be complex and expensive to develop and maintain. With SQL transactions, application code and database maintenance can be simplified.
42+
43+
## Understanding SQL Transactions with an Example
44+
45+
Consider a financial brokerage that maintains a database for its clients. The brokerage is required to generate a quarterly financial statement for each of its clients. The financial statement reports the statement balance, current values of holdings, and any transactions that occurred during the quarter. To generate the statement, you may need to process the following steps:
3646

3747
1. Loop through each client’s transaction history account to ascertain and calculate each of the transactions that occurred during the quarter (both purchases and sales).
38-
1. Calculate each client’s total portfolio’s return for the quarter, along with year-to-date returns.
48+
1. Calculate each client portfolio’s total return for the quarter, along with year-to-date returns.
3949
1. Calculate each client’s taxable and non-taxable returns for the quarter.
40-
1. Insert a record into the (say) `statements` table to record the prior three steps.
41-
1. Update the current portfolio holdings values and investment totals for the quarter in a (say) `quarterly_values` table.
42-
1. Update the statement balance in (say) the `accounts` table.
50+
1. Insert a record into a `statements` table to record the prior three steps.
51+
1. Update the current portfolio holdings' values and investment totals for the quarter in a `quarterly_values` table.
52+
1. Update the statement balance in an `accounts` table.
53+
54+
Many read and write operations are required for the above steps. There are a number of scenarios where data integrity could be violated, including:
4355

44-
Obviously, many read and write operations are required for the above steps. What if a transaction that falls within a reported quarter is backed out or changed after calculations have already been made? What if one of the updates noted above fails after we have already inserted a record into the `statements` table? What if the total statement balance cannot be updated?
56+
- A transaction that falls within a reported quarter is backed out or changed after calculations have already been made
4557

46-
These are all valid concerns and scenarios that can occur in a database application. To have to account for every possible permutation of errors to occur in a database application would be a coding/maintenance nightmare.
58+
- One of the updates noted above fails after we have already inserted a record into the `statements` table
4759

48-
The answer here is to make use of SQL Transactions. It can dramatically simplify coding, allow all statements in a transaction block to either succeed or fail and most importantly, ensure database integrity.
60+
- The total statement balance cannot be updated
61+
62+
Without SQL transactions, application code would need to account for every possible permutation of errors that could occur in the database. With SQL transactions, all of the above statements can be contained in a transaction block that either succeeds or fails.
4963

5064
## SQL Transaction Delimiter Syntax
5165

5266
{{< note >}}
5367
The implementation of transactions is very similar in concept across most database implementations, but the syntax can vary slightly.
5468
{{< /note >}}
5569

56-
Typically, in a SQL Stored Procedure, the beginning of a transaction in a SQL Server command line is defined using the following command:
70+
Typically, the beginning of a transaction in a SQL Server command line is defined using the `BEGIN TRANSACTION` statement:
5771

5872
BEGIN TRANSACTION NameOfTransaction;
5973

6074
In MySQL, the syntax is slightly different, but has the same meaning:
6175

6276
START TRANSACTION;
6377

64-
## Commit Transactions
78+
## Commit Transaction Syntax
6579

66-
If a database application decides that all the processing of a block of change activity has succeeded, the application can use the **COMMIT TRANSACTION** statement at the end of the block to commit the requisite changes to the database. In SQL Server, the following command is used to commit the transaction:
80+
If a database application determines that all of the changes for a transaction have succeeded, the application can use the `COMMIT TRANSACTION` statement. This commits those changes to the database, and it is placed at the end of a block of statements. In SQL Server, the following command is used to commit the transaction:
6781

6882
COMMIT TRANSACTION;
6983

7084
Alternatively, you can also use the below command. The following command can also be used in MySQL.
7185

7286
COMMIT;
7387

74-
## Roll Back Transactions
88+
## Roll Back Transaction Syntax
7589

76-
If a database application decides that something in a change activity code block has failed, the application can use the **ROLLBACK** statement. This statement can effectively de-commit any statements that have already been executed since the beginning of the transaction. In SQL Server and MySQL, the following command is used to roll back a transaction:
90+
If a database application determines that something in a change in a transaction has failed, the application can use the `ROLLBACK` statement. This statement can effectively de-commit any statements that have already been executed since the beginning of the transaction. In SQL Server and MySQL, the following command is used to roll back a transaction:
7791

7892
ROLLBACK;
7993

8094
## Database Transaction Examples
8195

82-
To demonstrate the mechanism behind transaction processing, consider the example of a simple database named `School`. One of the table in the database named `Course` is defined as follows:
83-
96+
To demonstrate the mechanism behind transaction processing, consider the example of a simple database named `School`. One of the tables in the database is named `Course` and is defined as follows:
8497

85-
| COURSE |
98+
| `COURSE` |
8699
| :--------: |
87-
| CourseId |
88-
| CourseName |
100+
| `CourseId` |
101+
| `CourseName` |
89102

90103
The `Course` table is created using the below SQL command:
91104

@@ -94,11 +107,11 @@ The `Course` table is created using the below SQL command:
94107
CourseName VARCHAR(40) NOT NULL
95108
);
96109

97-
The following examples provide different use cases of using the SQL Transactions from the command line.
110+
The following examples demonstrate different ways to use SQL transactions from the command line.
98111

99-
**Example #1**: To commit a transaction
112+
### Example 1: Commit a Transaction
100113

101-
The example below obtains the largest `CourseId` value from table `Course` and adds `1` to it. It then inserts a row into the `Course` table and Commits the Transaction. Before Commit, if any part of the `CourseAdd` transaction fails to execute, then none of the transactions can be processed. That means if the `Select` or `Insert` statement fails in some capacity, the entire transaction is null and void.
114+
The example below obtains the largest `CourseId` value from table `Course` and adds `1` to it. It then inserts a row into the `Course` table and commits the transaction. Before Commit, if any part of the `CourseAdd` transaction fails to execute, then none of the transactions can be processed. That means if the `Select` or `Insert` statement fails in some capacity, the entire transaction is null and void.
102115

103116
BEGIN TRANSACTION CourseAdd;
104117

@@ -111,20 +124,20 @@ The example below obtains the largest `CourseId` value from table `Course` and a
111124

112125
COMMIT TRANSACTION;
113126

114-
**Example #2**: Roll back a transaction
127+
### Example 2: Roll Back a Transaction
115128

116-
In the example below, although rows are manually inserted into the `Course` table, all the `Insert` statements are wrapped into a Transaction. That way, if a transaction fails to execute, you can roll back the entire transaction, using the following MySQL syntax:
129+
In the example below, although rows are manually inserted into the `Course` table, all the `Insert` statements are wrapped into a transaction. That way, if a transaction fails to execute, you can roll back the entire transaction using the following MySQL syntax:
117130

118131
START TRANSACTION;
119132
INSERT Course VALUES (1, 'Biology 101');
120133
INSERT Course VALUES (2, 'Computer Science 101');
121134
ROLLBACK;
122135

123-
From the above MySQL syntax, you have ensured that the `Insert` statements have not committed (inserted) the data into the `Course` table until a `Commit` command is received. By issuing a `Rollback` statement, you have effectively undone the two prior `Insert` statements, and not Committed either of these two rows to the database.
136+
From the above MySQL syntax, you have ensured that the `Insert` statements have not committed (inserted) the data into the `Course` table until a `Commit` command is received. By issuing a `Rollback` statement, you have effectively undone the two prior `Insert` statements, and not committed either of these two rows to the database.
124137

125-
**Example #3**: Combining Commit and Rollback in a Transaction
138+
### Example 3: Combining Commit and Rollback in a Transaction
126139

127-
The example below combines the ability to both Commit and Rollback transactions in the same transaction code block.
140+
The example below combines the ability to both commit and rollback transactions in the same transaction code block.
128141

129142
BEGIN TRANSACTION InsertCourse;
130143

@@ -143,18 +156,16 @@ The example below combines the ability to both Commit and Rollback transactions
143156

144157
COMMIT TRANSACTION;
145158

146-
The MySQL code above inserts a row in the `Course` table with the next highest `CourseId`. Before committing the transaction, the code checks if there are more than one row where the `CourseName` is `Biology 101`. If yes, transaction is not committed to the database. At this point, the transaction rolls back and the code segment aborts from further processing. If it is the first instance of a `CourseName` of `Biology 101`, then the transaction proceeds, and eventually is committed to the database.
159+
The MySQL code above inserts a row in the `Course` table with the next highest `CourseId`. Before committing the transaction, the code checks if there are more than one rows where the `CourseName` is `Biology 101`. If true, the transaction is not committed to the database. At this point, the transaction rolls back and the code segment aborts from further processing. Otherwise, if the new row is the first instance of a `CourseName` of `Biology 101`, then the transaction proceeds and is committed to the database.
147160

148161
## More Benefits of Using Transactions
149162

150-
When should you use Transactions? Should you use all transactions all the time?
151-
152-
The simple answer is yes. This is especially true when you are dealing with multiple group of statements. It can be where all the statements in a sequence of statements must succeed for the associated data to be committed to the database. In this case, a failure of a component within the transaction necessitates a rollback.
163+
When should you use transactions? Should you always use transactions?
153164

154-
Moreover, the use of transactions is extremely beneficial when you run the risk of things like power failures, server crashes, disk drive failure, database crashes, etc.
165+
The simple answer is yes. This is especially true when you are dealing with multiple groups of statements. In a transaction, all of the statements in a sequence of statements must succeed for the associated data to be committed to the database. A failure of a component within the transaction necessitates a rollback.
155166

156-
In the event of any of these failures, if transactions have not yet been committed, you are guaranteed to have maintained the integrity of the database. Without the use of transactions, any atomic statements that are applied to the database remain intact, regardless of whether associated statements have been executed, or not. This may result in a data integrity issue.
167+
The use of transactions is also beneficial to protect against database failure conditions, including power failures, server crashes, disk drive failure, and database software crashes. In the event of one of these failures, if there are transactions that have not yet been committed, database integrity is maintained. Without transactions, any atomic statements that are applied to the database remain intact, regardless of whether associated statements have been executed. This may result in a data integrity issue.
157168

158169
## Conclusion
159170

160-
SQL Transactional logic is a fundamental mechanism to ensure database integrity and minimize the amount of error control logic that is required in a multi-user database application. In short, the use of transactions in SQL environments guarantees accuracy and completeness.
171+
SQL transaction logic is a fundamental mechanism for ensuring database integrity and minimizing error handling logic that is required in a multi-user database application. The use of transactions in SQL environments guarantees accuracy and completeness.

0 commit comments

Comments
 (0)