BEGIN Statement:The BEGIN statement is used to start a new transaction. Once a transaction is started, any changes made to the database will not be saved permanently until a COMMIT statement is executed.
sqlCopy code
BEGIN;
BEGIN statement initiates a new transaction. From this point on, any SQL statements executed are considered part of the transaction until a COMMIT or ROLLBACK statement is encountered.COMMIT Statement:The COMMIT statement is used to permanently save all the changes made during the current transaction. If the transaction completes successfully, the changes are saved to the database; otherwise, they are rolled back.
sqlCopy code
-- Assume we have made changes to the database during the transaction
-- ...
COMMIT;
COMMIT statement is used to save all the changes made during the current transaction to the database.ROLLBACK Statement:The ROLLBACK statement is used to undo all the changes made during the current transaction and return the database to its previous state. It is typically used when an error occurs or when you want to cancel a transaction.
sqlCopy code
-- Assume an error occurred during the transaction or we want to cancel it
-- ...
ROLLBACK;
ROLLBACK statement undoes all the changes made during the current transaction, effectively canceling it.Let's consider a real-world example of a money transfer transaction between two bank accounts. We want to ensure that the money is deducted from one account and added to another account atomically to maintain data integrity.
sqlCopy code
BEGIN;
-- Deduct $100 from Account A
UPDATE accounts
SET balance = balance - 100
WHERE account_number = 'A123';
-- Add $100 to Account B
UPDATE accounts
SET balance = balance + 100
WHERE account_number = 'B456';
-- Check if the transaction is valid
-- If any error occurs, we ROLLBACK the transaction
-- If the transaction is valid, we COMMIT it
-- ...
COMMIT;
BEGIN.