You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.'
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
-
23
21
## What are SQL Transactions?
24
22
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.
26
24
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)
28
30
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)
30
32
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
32
34
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?
34
40
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:
36
46
37
47
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 clientportfolio’s total return for the quarter, along with year-to-date returns.
39
49
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:
43
55
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
45
57
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
47
59
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.
49
63
50
64
## SQL Transaction Delimiter Syntax
51
65
52
66
{{< note >}}
53
67
The implementation of transactions is very similar in concept across most database implementations, but the syntax can vary slightly.
54
68
{{< /note >}}
55
69
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:
57
71
58
72
BEGIN TRANSACTION NameOfTransaction;
59
73
60
74
In MySQL, the syntax is slightly different, but has the same meaning:
61
75
62
76
START TRANSACTION;
63
77
64
-
## Commit Transactions
78
+
## Commit Transaction Syntax
65
79
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:
67
81
68
82
COMMIT TRANSACTION;
69
83
70
84
Alternatively, you can also use the below command. The following command can also be used in MySQL.
71
85
72
86
COMMIT;
73
87
74
-
## Roll Back Transactions
88
+
## Roll Back Transaction Syntax
75
89
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:
77
91
78
92
ROLLBACK;
79
93
80
94
## Database Transaction Examples
81
95
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:
84
97
85
-
| COURSE |
98
+
|`COURSE`|
86
99
| :--------: |
87
-
| CourseId |
88
-
| CourseName |
100
+
|`CourseId`|
101
+
|`CourseName`|
89
102
90
103
The `Course` table is created using the below SQL command:
91
104
@@ -94,11 +107,11 @@ The `Course` table is created using the below SQL command:
94
107
CourseName VARCHAR(40) NOT NULL
95
108
);
96
109
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.
98
111
99
-
**Example #1**: To commit a transaction
112
+
### Example 1: Commit a Transaction
100
113
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.
102
115
103
116
BEGIN TRANSACTION CourseAdd;
104
117
@@ -111,20 +124,20 @@ The example below obtains the largest `CourseId` value from table `Course` and a
111
124
112
125
COMMIT TRANSACTION;
113
126
114
-
**Example #2**: Roll back a transaction
127
+
### Example 2: Roll Back a Transaction
115
128
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:
117
130
118
131
START TRANSACTION;
119
132
INSERT Course VALUES (1, 'Biology 101');
120
133
INSERT Course VALUES (2, 'Computer Science 101');
121
134
ROLLBACK;
122
135
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.
124
137
125
-
**Example #3**: Combining Commit and Rollback in a Transaction
138
+
### Example 3: Combining Commit and Rollback in a Transaction
126
139
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.
128
141
129
142
BEGIN TRANSACTION InsertCourse;
130
143
@@ -143,18 +156,16 @@ The example below combines the ability to both Commit and Rollback transactions
143
156
144
157
COMMIT TRANSACTION;
145
158
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.
147
160
148
161
## More Benefits of Using Transactions
149
162
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?
153
164
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.
155
166
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.
157
168
158
169
## Conclusion
159
170
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