On this page
SQL Transactions: BEGIN, COMMIT, ROLLBACK
SQL Transactions: BEGIN, COMMIT, ROLLBACK
SQL transactions are used to manage actions that must be executed together. If one action fails, the transaction ensures that none of the actions affect the database. This is crucial for maintaining data integrity.
BEGIN Transaction
Begins a new transaction. It’s the starting point from where the changes start being tracked.
BEGIN TRANSACTION;
COMMIT Transaction
Commits the transaction, making all changes permanent. This is used when all actions within the transaction are successful.
COMMIT TRANSACTION;
ROLLBACK Transaction
Rolls back the transaction, undoing all changes made within the transaction. This is used when one or more actions in the transaction fail.
ROLLBACK TRANSACTION;
Example
Imagine you are managing bank accounts and need to transfer money from one account to another. Both the debit from one account and the credit to another must succeed or fail together to maintain the accounts’ balance integrity.
BEGIN TRANSACTION; UPDATE Accounts SET balance = balance - 100 WHERE account_id = 1; UPDATE Accounts SET balance = balance + 100 WHERE account_id = 2; -- If both updates succeed COMMIT TRANSACTION; -- If one of the updates fails, for example due to a constraint violation ROLLBACK TRANSACTION;
Using transactions ensures that your database remains consistent, even in the face of errors or failures.
Conclusion
In summary, SQL transactions are a fundamental feature for maintaining database integrity by ensuring that a series of actions are executed as a single unit. The use of `BEGIN TRANSACTION` initiates the process, `COMMIT TRANSACTION` finalizes and saves all changes if every action within the transaction is successful, and `ROLLBACK TRANSACTION` reverts all changes if any action fails. This mechanism is particularly vital in scenarios such as financial transactions, where precision and consistency are crucial. By employing transactions, you safeguard your database against partial updates and maintain overall data accuracy, even when faced with unexpected errors or failures.