Junior — Middle
Can you explain what the COMMIT command means in SQL and its role in transaction management?
sobes.tech AI
Answer from AI
The COMMIT command in SQL is used to save all changes made in the current transaction. A transaction is a sequence of operations that must be executed as a single unit.
When you perform multiple operations (such as INSERT, UPDATE, DELETE), they are initially in a pending state and do not affect the database until a COMMIT is executed. After the COMMIT, all changes become permanent and visible to other users.
If something goes wrong, you can perform a ROLLBACK to undo all changes in the transaction.
Example:
BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
Here, money is transferred from one account to another, and only after the COMMIT are the changes permanently saved.