Open In App

MySQL Transaction

Last Updated : 30 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Essentially, a database transaction is a kind of safe wherein you perform a lot of operations—for instance, money transfers—in one shot. If everything goes fine, it saves all the changes; otherwise, in case something goes wrong, the database rolls back to its old state in order to make sure that your money doesn't disappear into thin air.

MySQL is one of the very popular database management systems, which lays much emphasis on integrity and consistency in data through the mechanism of transactions. Transactions allow grouping a set of operations as an inseparable single unit of operations, either all of which succeed or none of which does. This assures validity and reliability in your data, even in cases of failures or system failures.

What is a Transaction

A database transaction is a series of operations executed as a single, all-or-nothing unit of work. To be more precise, all the operations inside a transaction must be completed; otherwise, it will roll back to the previous state before the operations took place. In other words, this makes transactions very important in securing data integrity, consistency, and reliability for database systems.

Why Use Transactions in MySQL

MySQL transactions are useful in maintaining the accuracy of the data and its reliability. This is in situations where various operations need to be executed as a whole. Consider, for example, online banking, where transferring money from one account to another involves debiting the amount in one account and simultaneously crediting that amount in the other.

In this case, transactional techniques allow assurance of either both actions' success or neither, hence avoiding problems like the disappearance of money from one account and its failure to appear in another. This consistency is very important in applications such as e-commerce and banking, where data integrity is important, and in any system since transactions help manage errors gracefully and system failures.

How to Use Transactions in MySQL

The following is how you can handle transactions to ensure your database operations are carried out reliably:

Start of a Transaction

The START TRANSACTION statement can be used to start a transaction. This statement marks the beginning of the new transaction.

START TRANSACTION;

Execute SQL Statements

All the requisite operations in SQL have to then be conducted within the transaction. For example, you could do updates, insertions, or deletions of records.

UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;

Committing a Transaction

The COMMIT statement saves all the changes made during a transaction. It makes all of the changes permanent and terminates the transaction.

COMMIT;

Rolling Back a Transaction

If something goes wrong and you want to "roll back" the changes made during the transaction, issue the ROLLBACK statement. This statement restores the database to its state before the transaction started.

ROLLBACK;

Example of a Complete Transaction

Now we take a complete example of a transaction that how a transaction is done.

Create Table

-- Create the accounts table
CREATE TABLE accounts (
account_id INT PRIMARY KEY,
account_name VARCHAR(100),
balance DECIMAL(10, 2)
);

Insert Data

-- Insert some initial data into the accounts table
INSERT INTO accounts (account_id, account_name, balance) VALUES
(1, 'Alice', 1000.00),
(2, 'Bob', 500.00);

Start the Transaction

START TRANSACTION;

UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;
COMMIT;

where expalnation,

  • START TRANSACTION: Begins a new transaction.
  • UPDATE accounts SET balance = balance - 100 WHERE account_id = 1: Decreases the balance of the account with account_id = 1 by 100 units.
  • UPDATE accounts SET balance = balance + 100 WHERE account_id = 2: Increases the balance of the account with account_id = 2 by 100 units.
  • COMMIT: Finalizes the transaction.

Output:

account_id

account_name

balance

1

Alice

900.00

2

Bob

600.00

Using Savepoints

You can establish named intermediate points within a transaction by using savepoints. The basic idea behind savepoints is to give a chance for partial transaction rollbacks, which means that parts of a transaction could be cancelled without interfering with the integrity of the whole transaction.

Create Table

CREATE TABLE accounts (
account_id INT PRIMARY KEY,
account_name VARCHAR(100),
balance DECIMAL(10, 2)
);

Insert Data

INSERT INTO accounts (account_id, account_name, balance) VALUES
(1, 'Alice', 1000.00),
(2, 'Bob', 500.00);

Start Transaction

START TRANSACTION;

SAVEPOINT savepoint1;

UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;

SAVEPOINT savepoint2;

UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;

-- If an error occurs, roll back to a specific savepoint
ROLLBACK TO SAVEPOINT savepoint1;

-- Finally, commit the transaction
COMMIT;

By following these steps, you can effectively manage transactions in MySQL, ensuring that your database operations are executed reliably and that your data remains consistent and accurate.

Output:

account_id

account_name

balance

1

Alice

1000.00

2

Bob

500.00

Conclusion

MySQL transactions are one of the most powerful tools to run database operations with precision and reliability. The process wraps all the sequence of operations within a single unit of work to ensure that all changes execute successfully or none at all, thus ensuring data integrity and consistency. The core properties of transactions—Atomicity, or ACID, for short—are designed to prevent the corruption of data and to ensure that your database remains accurate in the presence of errors or system failures.


Next Article
Article Tags :

Similar Reads