TRANSACTION
TRANSACTION in SQL is a unit of work that is treated as a single, indivisible logical operation. It's designed to ensure data integrity by enabling the ability to control a set of data modifications as a whole. If all modifications are successful, they're committed (permanently saved) to the database. If not, the transaction is rolled back, reversing all changes made within the transaction. Transaction management ensures the database remains in a consistent state and supports concurrent processing by multiple users.
Example
Output
Explanation
The example demonstrates a transaction in MySQL. The START TRANSACTION
command is used to initiate a new transaction. Two INSERT
statements follow, each adding a new row to the Students
table. The COMMIT
command concludes the transaction, applying all changes made since START TRANSACTION
. If any command within the transaction encounters an error, all changes made during the transaction would be discarded in order to maintain the database’s consistency.
Example
Output
Explanation
The given code is a simple SQL transaction. A transaction starts with BEGIN
and ends with COMMIT
. In this transaction, a new customer ‘Cardinal’ is inserted into the ‘Customers’ table, and an order for ‘Cardinal’ is inserted into the ‘Orders’ table. If there is an error in any step between BEGIN
and COMMIT
, the transaction will not be finalized.
Example
Output
Explanation
In the given example, a SQL Server transaction is started with the BEGIN TRAN;
command. A UPDATE
operation is then performed on the Employees
table, increasing the salary by 500 for the employee with the id
of 101. The COMMIT;
command is used to end the transaction and make the changes permanent. If there was an error in the execution, the changes would not be saved to the database.
Example
Output
Explanation
This example demonstrates a SQL transaction in SQLite. Initialization of the transaction is done using BEGIN TRANSACTION;
. Within the transaction, a table test
is created if it does not exist and a row is inserted into the test
table. The transaction is then committed using COMMIT;
. If any error occurred during the transaction, the changes would be rolled back and not committed. Otherwise, the changes are committed and will be permanent in the database.