COMMIT permanently saves changes made during a transaction, while ROLLBACK undoes them. A transaction is a sequence of SQL operations treated as a single unit to ensure data integrity, following ACID properties. For example, in a money transfer, if one account is debited but the other isn't credited, the transaction ensures no partial updates occur. When all operations succeed, COMMIT makes the changes permanent and visible to others; once committed, changes can’t be undone without reversal. If an error occurs or changes shouldn’t persist, ROLLBACK reverts everything to the state before the transaction began. Common rollback scenarios include constraint violations, application errors, testing, or unexpected disconnections. To use COMMIT and ROLLBACK effectively: 1) wrap related operations in transactions; 2) test carefully in development; 3) avoid long-running transactions to prevent resource locking; 4) understand auto-commit settings; and 5) use savepoints for partial rollbacks when supported. Proper use of these commands ensures reliable data handling in database applications.
When you're working with databases, especially in applications that require reliable data handling, COMMIT and ROLLBACK are two essential commands that help manage transactions. They determine whether changes made during a transaction should be saved or discarded.
In simple terms:
- COMMIT saves the changes permanently to the database.
- ROLLBACK undoes the changes made during the current transaction.
What is a Transaction?
Before diving into COMMIT and ROLLBACK, it helps to understand what a transaction is. A transaction is a sequence of one or more SQL operations treated as a single unit of work. Either all of them succeed, or none do — this is part of the ACID properties (Atomicity, Consistency, Isolation, Durability) that databases follow.
For example, imagine transferring money from one bank account to another:
- Deduct money from Account A
- Add money to Account B
If something goes wrong after step 1 but before step 2, you don’t want the deduction to stick. That’s where transactions come in handy.
How Does COMMIT Work?
Once you've executed your SQL statements inside a transaction block and everything looks good, you use COMMIT to make those changes permanent.
Here's a basic example using SQL:
BEGIN TRANSACTION; UPDATE accounts SET balance = balance - 100 WHERE account_id = 1; UPDATE accounts SET balance = balance 100 WHERE account_id = 2; COMMIT;
After the COMMIT
runs, both updates become visible to other users and are stored permanently in the database.
Key points:
- Once committed, the changes can't be undone unless explicitly reversed.
- Other sessions will now see the updated data.
- Some databases auto-commit by default, meaning each statement is treated as its own transaction unless told otherwise.
When to Use ROLLBACK
If at any point during the transaction an error occurs or you decide not to proceed, ROLLBACK lets you undo everything since the start of the transaction.
Example:
BEGIN TRANSACTION; UPDATE accounts SET balance = balance - 100 WHERE account_id = 1; -- Oops! Something went wrong ROLLBACK;
Now, no changes were applied — Account A still has its original balance.
Common scenarios for rollback:
- Detecting constraint violations (e.g., negative balance)
- Handling application-level errors
- Testing without affecting real data
Rollbacks are also automatic if a session disconnects unexpectedly or a system crash happens before committing.
Tips for Using COMMIT and ROLLBACK Effectively
- Always wrap related operations in a transaction when data integrity matters.
- Test logic carefully in development environments before running transactions on production data.
- Avoid holding transactions open too long — they can lock resources and impact performance.
- Be aware of your database's auto-commit behavior (you can usually toggle it off).
- Use savepoints (
SAVEPOINT
) if your DB supports them — they let you roll back part of a transaction.
So, to recap:
You use COMMIT when you're sure the changes should take effect, and ROLLBACK when something went wrong or you're not ready to apply the changes yet.
They’re not complicated, but understanding how and when to use them makes a big difference in building robust database applications.
The above is the detailed content of How do COMMIT and ROLLBACK work?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

1. Source of the problem When analyzing performance problems, slow queries and binlog slow transactions are commonly used methods. Recently, I was analyzing a slow query and found that it contained a large number of commit statements that were slow, but the matching could not be completed when analyzing the binlog slow transactions. For example, there may be 1,000 commit statements during this period, but there may be only 100 slow transactions. This is too big a difference, so why does this phenomenon occur? 2. The respective determination methods for slow transactions are usually as follows for an explicitly submitted (insert) transaction: GTID_LOG_EVENT and XID_EVENT are the time when the command ‘COMMIT’ is initiated.

How to undo a commit submitted by git: 1. Modify the content of the last commit. If you find that there is an error in the last commit, you can use the "git commit --amend" command to modify it; 2. Undo the changes of a commit, If you need to completely undo a commit and its corresponding changes, you can use the "git revert" command; 3. If you need to completely roll back to the state before a commit, you can use the "git reset" command.

When you encounter the problem of being unable to call commit in a PHP project, it may be caused by errors in the code, insufficient permissions, or version control tool configuration issues. When encountering such problems, you can gradually check and solve them through the following methods: 1. Check for code errors. First, you need to check whether there are grammatical errors, logical errors or other errors related to the submitted code in the code. For example, when using Git as a version control tool, submission may not be possible due to file conflicts, unstaged files, etc. Therefore, you can check

How to solve the problem of being unable to call commit in PHP projects. In the process of developing PHP projects, we often encounter situations where we need to call external services or APIs and perform corresponding operations based on the returned results. However, sometimes we encounter trouble when calling the commit operation and cannot execute it normally. This article will introduce in detail how to solve the problem of being unable to call commit in PHP projects, and provide specific code examples to help developers quickly solve this problem. Problem analysis: In PHP projects, when external services need to be called

COMMITpermanentlysaveschangesmadeduringatransaction,whileROLLBACKundoesthem.AtransactionisasequenceofSQLoperationstreatedasasingleunittoensuredataintegrity,followingACIDproperties.Forexample,inamoneytransfer,ifoneaccountisdebitedbuttheotherisn'tcredi

To revoke a commit that has been pushed to a repository but keeps history, use gitrevert to create a new commit to reverse the changes to the specified commit. 1. Use gitlog--oneline to find the hash value of the target commit; 2. Execute gitrevert or such as gitrevertHEAD~2 to revoke a specific commit; 3. If there is a conflict, manually resolve it and continue with gitrevert--continue, or abort; 4. Submission information can be edited and confirmed; 5. For merged commits, the -m1 parameter needs to be added. This method is safe for shared branches and avoids problems caused by rewriting history.

Toamendthemostrecentcommitmessage,usegitcommit--amend-m"Yournewcommitmessage"ifthecommithasn’tbeenpushed;thisrewritesthelocalcommithistorywiththenewmessage.2.Toeditthemessageinyourdefaulteditor,rungitcommit--amendwithoutthe-mflag,allowingyo

Use gitlog--oneline to get the target commit hash; 2. Execute gitswitch-c to create and switch directly from the commit to the new branch, without switching the current branch first - this method accurately creates a branch based on the specified commit, suitable for fixing old version bugs or stable point-based experiments, without affecting the original branch, and ending in full.
