START TRANSACTION;
– Begins a transaction.COMMIT;
– Saves all changes permanently.ROLLBACK;
– Undoes changes if an error occurs.Let’s assume we have a bank_accounts table with columns account_id
, name
, and balance
. We want to transfer money between two accounts, ensuring that both operations succeed or fail together.
START TRANSACTION;
UPDATE bank_accounts
SET balance = balance - 500
WHERE account_id = 1;
UPDATE bank_accounts
SET balance = balance + 500
WHERE account_id = 2;
COMMIT;
COMMIT;
saves the changes.ROLLBACK;
MySQL Transactions are essential for maintaining reliable and consistent data operations. By grouping multiple queries into a single transaction, they prevent data corruption and ensure that either all operations are completed successfully or none at all.